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!
HashSets are used to store a collection of unique elements. HashSet cannot contain duplicate values. HashSet allows null value. HashSet is an unordered collection.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With