Java - TreeMap不检索密钥

时间:2018-05-11 19:57:00

标签: java key-value treemap

我遇到了一个问题,我无法理解这里发生了什么。 我使用TreeMap<Custom_class, TreeMap<Custom_class, Integer>>

进行操作

以下是代码片段:

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;

  }
}

在执行中,突出显示的行失败,获得一个键的0条目: debug mode in intellij

这是TreeMap结构: TreeMap structure

我不明白为什么当密钥.get(key)出现时,Coordenada(12,2)失败了。所有工作之前都很好。

Coordenada上课

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] + ")";
}

}

完全插入Coordenada(12,2)并修改之前的helper_co = Coordenada(10,2) debugger variables

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

查看您的compareTo功能

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

这是模棱两可的。