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!
One is to store the Integers in a
Set<Integer>such as aHashSet<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:
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.