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.
source share