Compare elements of JAVA messy lists

1

I have two state objects ( e1 and e2 ) in Java. These have a list of key objects as an attribute that have an X position and a Y with their respective llave.getX() , llave.getY() . I want to check that these attributes of e1 and e2 have keys in the same positions or not, but being in different order I can not make a simple comparison.

if (i.getX()==j.getX() && i.getY()==j.getY()) { ... } within:

for (Llave i : e1.llavesE) {
    for (Llave j : e2.llavesE) {
        /// COMPROBAR
    }    
}

With this algorithm:

boolean llaveaux = true;
for (Llave i : e1.llavesE) {
    if (llaveaux) {
        llaveaux = false;
        for (Llave j : e2.llavesE) {
            if (i.getX()==j.getX() && i.getY()==j.getY()) {
                llaveaux = true;
                break;
            }
        } 
    } else {
        return false;
    } 
}

return true;

I thought that my problem would be solved, but no. Any idea how I can solve this? and why does not my second idea work?

Greetings and thank you very much :)

    
asked by Davids Zarzoso Moreno 16.12.2018 в 18:11
source

1 answer

0

I'm going to assume that e1.llavesE and e2.llavesE return an arrayList of llave .

If the objects that are in a list are the same as those in the other (same object) you can use the idexOf() to see what positions they occupy in the lists. Also what you had put of keys is unnecessary.

for (Llave i : e1.llavesE) {
   if(!e2.llavesE.contains(i) || e1.llavesE.indexOf(i)!=e2.llavesE.indexOf(i)
   {             
          return false;           
   }      
}
return true;

If the Keys objects are not equal in both lists, but are easily comparable as you put in your example, which can be compared with a i.getX()==j.getX() && i.getY()==j.getY() , then I would prefer to overwrite the equals method of the Key class Sobbrescribe equals

public class Llave{
  private int x;
  private int y;

  //......Implementacion de codigo

  @Override
  public boolean equals(Object obj) {
     if(obj instanceOf Llave)
     {
        Llave otherKey=(Llave)obj;
        if(obj.getX() == x && obj.getY()== y)
        {
           return true;
        }
     }
     return false;
  }
}

If you do not overwrite the equals, you will never detect them as equals, since the objects internally have more attributes than you specify in your implementation. When overwriting the equals, we force it to only check the similarity with the attributes that we specify.

    
answered by 08.01.2019 в 09:59