I am novice to java. I have an ArrayList
and I want to avoid duplicates on insertion. My ArrayList
is
ArrayList karList
A set is simply a collection that can contain no duplicates so it sounds perfect for you.
It is also very simple to implement. For example:
Set<String> mySet = new HashSet<String>();
This would provide you a set that can hold Objects of type String.
To add to the set is just as simple:
mySet.add("My first entry!");
By definition of a set, you can add whatever you want and never run into a duplicate.
Have fun!
EDIT : If you decide you are dead-set on using an ArrayList, it is simple to see if an object is already in the list before adding it. For example:
public void addToList(String newEntry){
if(!myList.contains(newEntry))
myList.add(newEntry);
}
Note: All my examples assume you are using String objects but they can easily be swapped to any other Object type.
Use a HashSet
instead of an ArrayList
. But, to really make the HashSet
really work well, you must override the equals()
and hashCode()
methods of the class/objects that are inserted into the HashSet
.
Foe example:
Set<MyObject> set = new HashSet<MyObject>();
set.add(foo);
set.add(bar);
public class MyObject {
@Override
public boolean equals(Object obj) {
if (obj instanceof MyObject)
return (this.id = obj.id)
else
return false;
}
// now override hashCode()
}
Please see the following documentation for overriding hashCode()
and equals()
.
You can use LinkedHashSet
, to avoid duplicated elements and keep the insertion order.
http://docs.oracle.com/javase/7/docs/api/java/util/LinkedHashSet.html
You can implement own List which extends LinkedList and override its add methods:
You need to use any Set
implementation, e.g you can use HashSet
.
If you want to add
custom object kar
into your HashSet
, you need to override
equals
and hashcode
method.
You can read more about equals
and hashcode
, see
Whenever you want to prevent duplicates, you want to use a Set
.
In this case, a HashSet would be just fine for you.
HashSet karSet = new HashSet();
karSet.add(foo);
karSet.add(bar);
karSet.add(foo);
System.out.println(karSet.size());
//Output is 2
For completeness, I would also suggest you use the generic (parameterized) version of the class, assuming Java 5 or higher.
HashSet<String> stringSet = new HashSet<String>();
HashSet<Integer> intSet = new HashSet<Integer>();
...etc...
This will give you some type safety as well for getting items in and out of your set.