Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Good way to store unique integers

My Question Is: What's a fast way to determine whether a number is contained in a Collection to know whether to add it to the collection and maintain uniqueness. I would rather not iterate through the list if I can help it.

I have a List<Integer> called numberList. I want it to store unique integers and never allow duplicates to be added. I would like to do something like this:

private void add(int number) {
  if (!numberList.contains(number)) {
    numberList.add(number);
  }
}

But obviously this wont work because numberList contains a list of Integer objects so regardless of the number each is a unique object.

Thanks!

like image 468
kentcdodds Avatar asked Jul 01 '12 22:07

kentcdodds


People also ask

Which collection is used to store unique values?

HashSets are used to store a collection of unique elements. HashSet cannot contain duplicate values. HashSet allows null value. HashSet is an unordered collection.

Which type of collection accepts only unique values?

Set data structure is used to store unique values only, meaning no duplicate values would be stored in a set. When a HashSet is created, it internally implements a HashMap. An element can be inserted into the HashSet using the 'add' function.

Which of the collection class can be used to store unique objects and which is sorted?

HashSet class implements Set Interface. It represents the collection that uses a hash table for storage. Hashing is used to store the elements in the HashSet. It contains unique items.


1 Answers

One is to store the Integers in a Set<Integer> such as a HashSet<Integer>. Sets do not allow duplicates.

Edit
Also, the Collection's contains(...) method uses the object's equals(...) method to see if it is held by the collection or not, so your method above will prevent duplicates as well, if you need to use a List as your collection. Test this out yourself and you'll see it's so.

For instance:

  List<Integer> numberList = new ArrayList<Integer>();
  int[] myInts = {1, 1, 2, 3, 3, 3, 3, 4};
  for (int i : myInts) {
     if (!numberList.contains(i)) {
        numberList.add(i);
      }
  }

  System.out.println(numberList);

will return: [1, 2, 3, 4]

Also, one possible problem with HashSets is that they're not ordered, so if ordering is important, you'll want to look at using one of the other varieties of ordered Sets.

like image 190
Hovercraft Full Of Eels Avatar answered Sep 20 '22 09:09

Hovercraft Full Of Eels