0

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?

j3ny4
  • 442
  • 2
  • 8
Kibbles
  • 3
  • 2

4 Answers4

3

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);
            }
        }
    }
}
Axel
  • 13,939
  • 5
  • 50
  • 79
  • I didnt realize I put semiconlon there... Thank you. Why is semicolon always returning the if statement true? Just curious. – Kibbles May 30 '14 at 08:26
  • It isn't. The semicolon just stands for an empty statement and terminates your then-clause. You might want to have a look at http://stackoverflow.com/questions/14112515/semicolon-at-end-of-if-statement – Seb May 30 '14 at 08:33
1

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)) {
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
1

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
        }

    }
  }
}
Deepak Bhatia
  • 6,230
  • 2
  • 24
  • 58
1

You have an extra semicolon. Do as follows:

if(s2.equals(s))             
    list.remove(j + 1);

and this change should work.

Shrikant Kakani
  • 1,511
  • 2
  • 17
  • 37