我正在尝试创建一个HashMap
,它将对象添加到一行,如果它们不在此行中。这是我检查它的方式:
if (!waiting.containsKey(p)) {
waiting.put(current, p);
current++;
}
p
是我们的对象,它与Integer
一起存储。但是,当我运行此代码时。它会在不同的整数下多次存储同一个对象,如何防止它?
答案 0 :(得分:1)
这是因为你使用containsKey
拨打object
而不是key
:
参数必须是Integer
键
Integer lKey = 0;
if(!waiting.containsKey(lKey)){
waiting.put(current, p);
current++;
}
如果您的对象有标识符,请使用此标识符作为地图。
if(!waiting.containsKey(p.getId())){
waiting.put(p.getId(), p);
current++;
}
否则使用containsValue():
if(!waiting.containsValue(p)){
waiting.put(current, p);
current++;
}
但是你必须覆盖equals方法。
答案 1 :(得分:0)
如果要将对象用作键,可以覆盖equals()
和hashCode()
方法以返回并比较对象的id
。
import java.util.HashMap;
import java.util.Map;
public class Driver {
public static void main(String[] args) {
Map<MyObject, Integer> map = new HashMap<MyObject, Integer>();
map.put(new MyObject(1000L, "One"), 1);
map.put(new MyObject(1001L, "Two"), 2);
map.put(new MyObject(1002L, "Three"), 3);
Long id = 1001L;
System.out.println(contains(map, id)); // true
System.out.println(get(map, id)); // 2
}
public static <T, U> boolean contains(Map<T, U> map, T obj) {
return map.containsKey(obj);
}
public static boolean contains(Map<MyObject, Integer> map, Long id) {
return contains(map, new MyObject(id, ""));
}
public static <T, U> U get(Map<T, U> map, T obj) {
return map.get(obj);
}
public static Integer get(Map<MyObject, Integer> map, Long id) {
return get(map, new MyObject(id, ""));
}
}
public class MyObject {
private Long id;
private String name;
protected Long getId() {
return id;
}
protected void setId(Long id) {
this.id = id;
}
protected String getName() {
return name;
}
protected void setName(String name) {
this.name = name;
}
public MyObject(Long id, String name) {
this.id = id;
this.name = name;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
MyObject other = (MyObject) obj;
if (id == null) {
if (other.id != null) return false;
} else if (!id.equals(other.id)) return false;
return true;
}
@Override
public String toString() {
return "MyObject { id : " + id + ", name : " + name + "}";
}
}