A good way to store unique integers

My question is:. What a quick way to determine if a number is in a Collection , to know whether to add it to the collection and to maintain uniqueness. I would rather not go through the list if I can help him.

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 it is obvious that this does not work, because numberList contains a list of Integer objects, therefore, regardless of the number, each is a unique object.

Thanks!

+6
source share
2 answers

One of them is storing integers in Set<Integer> , such as HashSet<Integer> . Sets do not allow duplication.

Edit
In addition, the Collection contains(...) method uses the equals (...) method to determine if it is stored in the collection or not, so your method above will also prevent duplication if you need to use List as your collection. Check it is your own and you will see it.

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]

In addition, one of the possible problems with HashSets is that they are not ordered, so if ordering is important, you need to look at using one of the other varieties of ordered sets.

+12
source

Wouldn't the most compact form be a BitSet ? It is efficient in terms of storage, as it will expand indefinitely. He will also not use memory unnecessarily.

Do you work in a multi-threaded environment? If so, there are other structures that may be better / more efficient.

+3
source

Source: https://habr.com/ru/post/919454/


All Articles