I’m making an arraylist of numbers, appropriately
private ArrayList<Integer> numbers = new ArrayList();
and I have to check if they’re all unique. So I have this code:
public boolean isUnique()
{
ArrayList<Integer> checkNumbers = new ArrayList();
for(int i = 1; i<=numbers.size(); i++)
{
if(numbers.contains(i) && !checkNumbers.contains(i))
{
checkNumbers.add(i);
return true;
}
}
return false;
}
The idea is, I have to take in a square number (n) of integer inputs, unique from 1 to n.
But no matter what I add to numbers (13 2 13 2), it always returns true.
What’s wrong with my logic here?
if the list can contain more numbers than n and all you want is to verify that 1 .. n all exist and without duplication, then your code should be modified to this:
if on the other hand the list can’t contain more than n elements, you don’t need the other list at all: