Reputation: 1161
I am trying to get a boolean method to return true or false on wether two arrayLists
are equal to each other. The arraysLists
are array
and array1
. The user inputs them. Right now here is the code that I thought would work:
public boolean equals(){
//if both are equal return true, else false
boolean test = false;
for(int i = 0; i < array1.size() && !test; i++){
if(array1.get(i) == (array.get(i))){
test = true;
}
}
return test;
}
except even when all the arrayLists
numbers match the other arrayLists
numbers, it returns false
.
Upvotes: 0
Views: 4101
Reputation: 12207
You don't need to overwrite the equals method, as there is one already provided for lists that does exactly what you need.
If you insist of writing it yourself there is a simple error in your code. Because you initialize test to be false, "&& !test" lets your loop exist right at the start.
The correct version would be:
public boolean equals(){
if(array.size()!=array1.size) return false; // test for different length
for(int i = 0; i < array1.size(); i++){
if(!array1.get(i).equals(array.get(i))){
return false;
}
}
return true;
}
Upvotes: 2
Reputation: 1358
You'll need to change your code to this:
public boolean equals(){
if (array1.size() != array.size()) return false;
for(int i = 0; i < array1.size(); i++){
if(!array1.get(i).equals(array.get(i))){
return false;
}
}
return true;
}
First off, you have to start with test
being true and return false if you find something that isn't equal, because this clearly shows that the ArrayLists are not equal. You actually don't need the test
variable at all, so I took it out. Just return false if you find something that isn't equal. If you don't find something that isn't equal, it will never return false and will just return true at the end. Second, you have to use the equals()
method, because ArrayLists use the Integer
class, not the int
primitive so ==
will check if they are the same object, not if they are the same number. Lastly, to deal with comparing arrays of different sizes, you should compare their size and return false if they are not the same size, since there is no way they can be equal.
Upvotes: 0
Reputation: 319
You should just 'reverse' your method. Assume the arrays are equal first. It should then check on each iteration if the element differs. If the element differs, then set a "not equal" flag. In pseudo-codee
boolean different = false;
for (each element of array 1) {
if (element != element of array 2) different = true
break;
}
Upvotes: 0
Reputation: 8432
Think that you are only iterating one array. Think what can go wrong there. Also take a look at your control statement.
If you carefully follow the flux of your code you quickly will realize why is false.
Upvotes: 0
Reputation: 35096
double equals (==) is dangerous. You are actually returning objects in your code up there, so you should definitely use equals() instead
Upvotes: 0