16

I am novice to java. I have an ArrayList and I want to avoid duplicates on insertion. My ArrayList is

ArrayList<kar> karList = new ArrayList<kar>();

and the the field I want to check is :

 kar.getinsertkar().

I have read that I can use HashSet or HashMap but I have no clue.

ibtarek
  • 795
  • 4
  • 16
user2766131
  • 187
  • 1
  • 1
  • 7
  • 3
    "but i have no clue" What do you mean? Use a `HashSet`, just like you've read. – Jeroen Vannevel Sep 25 '13 at 19:45
  • [clue](http://docs.oracle.com/javase/tutorial/collections/interfaces/set.html) – ajb Sep 25 '13 at 20:20
  • Note that there's no rule that says you can't have *both* an `ArrayList` and a `HashSet` with the same elements. You can use an `ArrayList` to keep the elements in the order you want, and a `HashSet` to check whether an element is already present. (The check will be quicker than searching the `ArrayList`, but maintaining two collections will slow things down.) Sometimes this is the right way to do things. – ajb Sep 25 '13 at 20:24

7 Answers7

29

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.

Mike Clark
  • 11,769
  • 6
  • 39
  • 43
  • 5
    Also usually we use interface for vars type: `Set stringSet = new HashSet();` not the implementation –  Sep 25 '13 at 19:50
12

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.

r0t0xd
  • 206
  • 1
  • 6
8

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().

blackpanther
  • 10,998
  • 11
  • 48
  • 78
  • I used arraylist all over in my class for other methods, how can i change it? – user2766131 Sep 25 '13 at 19:46
  • +1 good suggestion, and we could point out that the objects going into the set should have a proper equals() and hashCode() method implemented. – vikingsteve Sep 25 '13 at 19:46
  • The methods used in a HashSet should be the same as an ArrayList because they both implement the same interface. – blackpanther Sep 25 '13 at 19:46
  • 1
    @blackpanther No, `ArrayList` has methods that `HashSet` and `LinkedHashSet` don't have, particularly `get(int index)`. We don't know how important it is to have those methods available. – ajb Sep 25 '13 at 20:30
  • @ajb my bad. I forgot about that. – blackpanther Sep 25 '13 at 20:49
6

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

Kent
  • 189,393
  • 32
  • 233
  • 301
0

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

Sajan Chandran
  • 11,287
  • 3
  • 29
  • 38
0

You can implement own List which extends LinkedList and override its add methods:

  1. public boolean add(E e)
  2. public void add(int index, E element)
  3. public boolean addAll(Collection collection)
  4. public boolean addAll(int index, Collection collection)
0

An example removing repeated Strings in an ArrayList:

var list = new ArrayList<>(List.of(
        "hello",
        "java",
        "test",
        "hello"
));

System.out.println(list);

System.out.println(new ArrayList<>(new HashSet<>(list)));

Output:

[hello, java, test, hello]
[java, test, hello]
ericmp
  • 1,163
  • 4
  • 18