Gau*_*lla -1 java collections treemap
使用get方法获取值时, TreeMap将值打印为null,而它正常工作HashMap().请在下面找到示例代码并为此提供输入.
它适用于Hashmap,因为它使用equals()/hashcode()方法,而TreeMap是SortedMap,它不使用equals方法来比较两个对象.相反,它使用比较器/可比较来比较对象,但在使用get方法获取对象时,它将null作为响应.请在此提供一些清晰度.
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
class Employees implements Comparable<Employees>, Comparator<Employees> {
public Employees(String name, int id) {
super();
this.name = name;
this.id = id;
}
private String name;
private int id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof Employees))
return false;
Employees other = (Employees) obj;
if (id != other.id)
return false;
return true;
}
@Override
public int hashCode() {
return 1;
}
@Override
public int compareTo(Employees o) {
return 1;
}
@Override
public int compare(Employees o1, Employees o2) {
return 1;
}
}
public class Employee {
public static void main(String[] args) {
// Map<Employees, Integer> m = new HashMap<>(); // equals will be used here.
Map<Employees, Integer> m = new TreeMap<Employees, Integer>(); // no equals/hashcode used here as we use comparator/comparable to compare objects.
Employees e1 = new Employees("abc", 11);
Employees e2 = new Employees("abc", 12);
System.out.println(m.put(e1, 1));
System.out.println(m.put(e2, 2));
**System.out.println(m.get(e2));**
}
}
Run Code Online (Sandbox Code Playgroud)
你的compareTo方法总是返回1,这意味着没有任何Employees对象等于任何其他Employees对象(甚至不是自己)compareTo.
仅在compareTo返回时0,两个比较实例被认为是相同的TreeMap.
顺便说一下,你hashCode总是回来的实施1也很糟糕.当它工作(for HashMap)时,它会导致所有条目存储在同一个桶中,从而破坏了它的性能HashMap.
| 归档时间: |
|
| 查看次数: |
262 次 |
| 最近记录: |