Reputation: 3
Suppose: list = ["be", "be", "is", "not", "or", "question", "that", "the", "to", "to"]
public static void removeDuplicates(ArrayList<String> list) {
for(int i = 0; i < list.size(); i++) {
String s = list.get(i);
for(int j = 0; j < list.size() - 1; j++) {
String s2 = list.get(j);
if(s2.equals(s)); {
list.remove(j + 1);
}
}
}
}
When I debug it, s2.equals(s)
seems to be returning true all the time when s2 and s does not equal to each other at all. What am I doing wrong?
Upvotes: 0
Views: 95
Reputation: 6276
You should start your second loop from i+1
, because in every iteration for j
loop the i
value will be equal to j
and it will satisfy the equals condition ....
public static void removeDuplicates(ArrayList<String> list)
{
for(int i = 0; i < list.size(); i++)
{
String s = list.get(i);
for(int j = i+1; j < list.size(); j++)
{
String s2 = list.get(j);
if(s2.equals(s))
{
list.remove(j + 1);
j--; //Subtract one as j+1 element is removed from list and index changes
}
}
}
}
Upvotes: 1
Reputation: 382150
You're testing elements against themselves too and you have a semicolon effectively removing the if
. You probably want
if (i!=j && s2.equals(s)) {
Upvotes: 1
Reputation: 14159
Remove the semicolon:
if(s2.equals(s)); {
Should be
if(s2.equals(s)) {
EDIT: Explanantion: In your code, you have an empty statement after the if
, and so the block will be executed regardless of the comparison result:
public static void removeDuplicates(ArrayList<String> list) {
for(int i = 0; i < list.size(); i++) {
String s = list.get(i);
for(int j = 0; j < list.size() - 1; j++) {
String s2 = list.get(j);
if(s2.equals(s))
; // <-- conditional
{ // <-- unconditional
list.remove(j + 1);
}
}
}
}
Upvotes: 3
Reputation: 1561
You have an extra semicolon. Do as follows:
if(s2.equals(s))
list.remove(j + 1);
and this change should work.
Upvotes: 1