Is there a better approach to do the below in Java, without using external libraries.
I need to model group/child (tree like) structure of int (primitive). In Json
[{1,1}, {1,2}, {2,1},{3,1}]
I need to support addition/removal of elements (element is a pair {group, child} ) without duplication.
I am thinking of, keeping a data structure like.
ArrayList<HashMap<Integer,Integer>>
To add.
Iterate through ArrayList, check HashMap key and value against the value to insert, and insert if not exist.
To delete:
Iterate through ArrayList, check HashMap key and value against the value to delete, and delete if exist.
Is there a better data structure/approach with standard library.
As per one of the answer below, I made a class like this. Please let me know anything to watchout. I am expecting (and going to try out) arraylist would handle add/remove correctly by using the equal method in KeyValue class. thanks.
static class KeyValue {
int groupPos;
int childPos;
KeyValue(int groupPos, int childPos) {
this.groupPos = groupPos;
this.childPos = childPos;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
KeyValue keyValue = (KeyValue) o;
if (childPos != keyValue.childPos) return false;
if (groupPos != keyValue.groupPos) return false;
return true;
}
@Override
public int hashCode() {
int result = groupPos;
result = 31 * result + childPos;
return result;
}
}
Set
(e.g.TreeSet
(requires your class to extend java.lang.Comparable or aComparator
class given as input) /HashSet
) would handle add/remove operations more efficiently thanArrayList
. – Dukeling Feb 7 '13 at 17:37equals()
instead ofif (o == null || getClass() != o.getClass()) return false;
useif(! (o instanceof KeyValue)) return false;
– Bimalesh Jha Feb 7 '13 at 17:41