Search code examples
javakey-valuetreemap

Java - TreeMap do not retrieves the key


I've topped with a problem I can not understand exactly what's happening here. I operate with a TreeMap<Custom_class, TreeMap<Custom_class, Integer>>

Here is the fragment of code:

TreeMap<Coordenada, Integer> helper_tree;
boolean newLine = false;

for (Linea l : this.lineas) {
  int helper = 0;
  newLine = true;
  Coordenada helper_co = null;

  for (Coordenada c : l.getNodosLinea()) {
    helper++;

    if (!c.getEsEstacion() && !c.getEsCruce()) continue;
    if (newLine) { map.putIfAbsent(c, new TreeMap<>()); helper_co = c; helper = 0; newLine = false; continue; }

    helper_tree = new TreeMap<>();
    helper_tree.put(helper_co, helper * 200);
    map.put(c, helper_tree);
    map.get(helper_co).put(c, helper * 200);
    helper_co = c;
    helper = 0;

  }
}

In the execution the highlighted line fails, getting 0 entry for a key: debug mode in intellij

And this is TreeMap structure: TreeMap structure

I dont understand why in fails at .get(key) when the key Coordenada(12,2) is present. All before works just fine.

Coordenada class

public class Coordenada implements Comparable<Coordenada>{
private int[] coordenada = new int[2];
private boolean esEstacion = false;
private boolean esCruce = false;

public Coordenada(int[] coordenada){
    this.coordenada[0] = coordenada[0];
    this.coordenada[1] = coordenada[1];
}

public void setCoordenada(int[] coordenada) {
    this.coordenada = coordenada;
}

public int[] getCoordenada() {
    return coordenada;
}

public void switchEstacion(){
    this.esEstacion = !this.esEstacion;
}

public void switchCruce() { this.esCruce = !this.esCruce; }

public boolean getEsEstacion() {
    return this.esEstacion;
}

public boolean getEsCruce() { return this.esCruce; }

@Override
public boolean equals(Object coord){
    Coordenada coordTemp = (Coordenada) coord;
    if (this.coordenada[0] != coordTemp.coordenada[0])
        return false;
    if (this.coordenada[1] != coordTemp.coordenada[1])
        return false;
    return true;
}

@Override
public int compareTo(Coordenada o) {
    if (this.coordenada[0] > o.coordenada[0] )
        return 1;
    if (this.coordenada[1] > o.coordenada[1] )
        return 1;
    if (this.coordenada[0] < o.coordenada[0])
        return -1;
    if (this.coordenada[1] < o.coordenada[1])
        return -1;
    return 0;
}

@Override
public String toString() {
    return "(" + coordenada[0] + ", " + coordenada[1] + ")";
}

}

Inserts perfectly Coordenada(12,2) and modifies previous helper_co = Coordenada(10,2) debugger variables

Thanks for any help!


Solution

  • Look at your compareTo function

    (0,1) compareTo (1,0) returns 1
    (1,0) compareTo (0,1) returns 1
    

    It's ambiguous.