0

I'm having a problem with the function remove() from ArrayList. I'll try to be as brief as possible. I have an ArrayList, Posicao is another class that I created, and I put some Objects in the Array. The problem is that when I print all the value in the ArrayList I get what a expect, but when I try to use remove(object) or lastIndexOf(value) it doesn't work. Remove() doesn't remove anything and lastIndexOf(), or even indexOf(), I get an error saying that the object that I requested is not in the Array. I double checked and the Object is in fact there. Is there anything that I'm doing wrong? The part of my code that I'm getting the problem. If there is something else that I need to post just ask. (=

System.out.println("BEGIN - Print beforeremove:" + tabuleiro0.posicoesLivres.contains(pos));
    for(int i = 0 ; i < tabuleiro0.posicoesLivres.size() ; i++)
        System.out.println(((Posicao)tabuleiro0.posicoesLivres.get(i)).x + " " + ((Posicao)tabuleiro0.posicoesLivres.get(i)).y);
    System.out.println("END - Print before remove :");

    tabuleiro0.posicoesLivres.remove(pos);

    System.out.println("BEGIN - Print after remove:" + tabuleiro0.posicoesLivres.contains(pos));
    for(int i = 0 ; i < tabuleiro0.posicoesLivres.size() ; i++)
        System.out.println(((Posicao)tabuleiro0.posicoesLivres.get(i)).x + " " + ((Posicao)tabuleiro0.posicoesLivres.get(i)).y);
    System.out.println("END - Print after remove :");

Thanks already for the patience (=

FCGomes.92
  • 83
  • 1
  • 3
  • Can you please tell us where the `pos` variable is being set? Have you printed out `pos` before calling `remove()` to verify it's not a logic error...? – xikkub Apr 09 '14 at 03:14
  • Wait `tabuleiro0.posicoesLivres.contains(pos)`? Is `pos` a value or a position? – Elliott Frisch Apr 09 '14 at 03:17
  • Another function sets pos and then calls this function that I printed. I printed pos and I get the right values but it can't be found to remove. Pos is an object that I created in the class Posicao, it has 2 integers, x and y. – FCGomes.92 Apr 09 '14 at 04:06

1 Answers1

0

Your problem probably is that your class needs to override Object#hashCode and Object#equals methods.

These methods are mandatory to be implemented in order for the Java Collections to be able to work properly when they have to look for some element, order themselves and everything...

You can read more about when do I need to override equals and hashcode methods?, and about overriding equals and hashCode in Java ;)

For the record, using Eclipse (or any decent Java IDE, I guess), you can have these implemented for you using some menu item function: Source -> Generate hashCode() and equals() methods...

Community
  • 1
  • 1
ccjmne
  • 7,914
  • 3
  • 41
  • 56
  • Thanks man. I did this but it didn't work. When I use remove(), indexOf() or lastIndexOf(), all of them can't find the value. But if I remove by the index, that I know it's the first it works. – FCGomes.92 Apr 09 '14 at 04:36