我有一個名爲Empl
的類和兩個名爲MySalaryComp
和MyNameComp
的比較器。使用比較器在TreeMap中獲取空值
當我運行此代碼時,我得到null
作爲MySalaryComp
中的值,如下面的輸出所示。
public class Test{
public static void main(String a[]) {
TreeMap<Empl, String> tm = new TreeMap<Empl, String>(new MyNameComp());
tm.put(new Empl("zzz", 3000), "RAM");
tm.put(new Empl("aaa", 6000), "JOHN");
Set<Empl> keys = tm.keySet();
for (Empl key : keys) {
System.out.println(key + " ==> " + tm.get(key));
}
TreeMap<Empl, String> trmap = new TreeMap<Empl, String>(new MySalaryComp());
trmap.put(new Empl("zzz", 3000), "RAM");
trmap.put(new Empl("aaa", 6000), "JOHN");
Set<Empl> ks = trmap.keySet();
for (Empl key : ks) {
System.out.println(key + " ==> " + trmap.get(key));
}
}
}
class MyNameComp implements Comparator<Empl> {
@Override
public int compare(Empl e1, Empl e2) {
return e1.getName().compareTo(e2.getName());
}
}
class MySalaryComp implements Comparator<Empl> {
@Override
public int compare(Empl e1, Empl e2) {
if (e1.getSalary() > e2.getSalary()) {
return 1;
} else {
return -1;
}
}
}
class Empl {
private String name;
private int salary;
public Empl(String n, int s) {
this.name = n;
this.salary = s;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
}
以上代碼的輸出是:
Name: aaa-- Salary: 6000 ==> JOHN
Name: zzz-- Salary: 3000 ==> RAM
Name: zzz-- Salary: 3000 ==> null
Name: aaa-- Salary: 6000 ==> null
有人能幫助我理解爲什麼空值顯示?以及如何解決它。
爲什麼返回0,在GET()的映像樹的方法反映,請解釋 –
笑,因爲它需要在返回0第一次投入 –
但是我能夠把這些元素放在KT中嗎?問題是當我從KT獲取元素時。請通過以上的答案 –