Java: Avoid inserting duplicate in arraylist
Asked Answered
T

7

18

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.

Throng answered 25/9, 2013 at 19:44 Comment(3)
"but i have no clue" What do you mean? Use a HashSet, just like you've read.Leadership
clueLeek
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.Leek
R
31

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.

Rictus answered 25/9, 2013 at 19:47 Comment(1)
Also usually we use interface for vars type: Set<String> stringSet = new HashSet<String>(); not the implementationSimonne
A
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.

Amazon answered 25/9, 2013 at 19:48 Comment(0)
M
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().

Mussman answered 25/9, 2013 at 19:45 Comment(5)
I used arraylist all over in my class for other methods, how can i change it?Throng
+1 good suggestion, and we could point out that the objects going into the set should have a proper equals() and hashCode() method implemented.Sawhorse
The methods used in a HashSet should be the same as an ArrayList because they both implement the same interface.Mussman
@Mussman 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.Leek
@Leek my bad. I forgot about that.Mussman
I
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

Ilsa answered 25/9, 2013 at 19:47 Comment(0)
M
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

Maleate answered 25/9, 2013 at 19:50 Comment(0)
C
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)
Couching answered 28/3, 2018 at 14:26 Comment(0)
S
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]
Starlastarlene answered 2/1, 2022 at 17:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.