Patashu's idea seems the simplest. You can use Arrays.sort()
to easily and efficiently sort the array.
If you really want to SEARCH, you probably would use one of the Arrays.binarysearch()
methods. But they also require sorted arrays.... For each element in your array (say at index n), search the portion 0...(n-1) and also search the portion (n+1)...(length-1) but that would be grossly wasteful if you could just compare with one element adjacent to n. So it's back to the previous suggestion.
If you want to do slightly less coding, probably at the expense of speed, you could use the contains()
method of one of the implementing classes of AbstractCollection
- probably ArrayList
(can contain duplicates), TreeSet
(sorted, contains unique values) or HashSet
(unsorted, contains unique values). You can call the constructor for these collections with the parameter Arrays.asList(yourArray)
so you don't need to populate one-by-one.
As ay89 rightly mentions, it is simpler to have an array with unique values (a set in other words), then check if your value is already contained before trying to add it. Makes things lot simpler. But you might not always have that luxury with what you are given.