展开全部
可以62616964757a686964616fe59b9ee7ad9431333262366364实现,不过要自定义一个高级HashMap,它的效率是高出list很多。
下面是我以前写的一个sampler,试试看:(它不但可以操作基本数据类型,一般的对象也能,只要重写其hashcode和equals方法)
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
class Test {
public static void main(String[] args) {
Map map = new fuzzyMap(new HashMap()) {
@Override
public Collection instanciateNewCollection() {
return new ArrayList(3);
}
};
O o = new O("a1", "b1");
map.put(o, o);
O o2 = new O("a1", "b2");
map.put(o2, o2);
System.out.println(o.equals(o2));
o = new O("a3", "b3");
map.put(o, o);
o = new O("a4", "b4");
map.put(o, o);
Object o_return = map.get(o2);
if (o_return instanceof List) {
List localList = (List) o_return;
for (O o_ret : localList) {
System.out.println(o_ret.a + "===" + o_ret.b);
}
} else {
O o_ret = (O) o_return;
System.out.println(o_ret.a);
}
}
}
class O {
public String a = "";
public String b = "";
public boolean hashCodeDirty = true;
private int hashCode = 1;
public O(String str1, String str2) {
a = str1;
b = str2;
}
@Override
public int hashCode() {
if (this.hashCodeDirty) {
final int prime = 5;
int result = 1;
result = prime * result + ((this.a == null) ? 0 : this.a.hashCode());
this.hashCode = result;
this.hashCodeDirty = false;
}
return this.hashCode;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final O other = (O) obj;
if (this.b == null) {
if (other.a != null)
return false;
} else if (!this.a.equals(other.a))
return false;
return true;
}
}
abstract class fuzzyMap implements Map {
private Map map;
public fuzzyMap(Map map) {
super();
this.map = map;
}
public int size() {
return map.size();
}
public boolean isEmpty() {
return map.isEmpty();
}
public boolean containsKey(Object key) {
return map.containsKey(key);
}
public boolean containsValue(Object value) {
return map.containsValue(value);
}
public Object get(Object key) {
return map.get(key);
}
public Object put(Object key, Object value) {
Object v = map.get(key);
if (v != null) {
if (v instanceof List) {
((List) v).add(value);
} else {
Collection list = instanciateNewCollection();
list.add(v);
list.add(value);
map.put(key, list);
}
} else {
return map.put(key, value);
}
return v;
}
public abstract Collection instanciateNewCollection();
public Object removeValue(Object key, Object value) {
Object v = map.get(key);
if (v != null) {
if (v instanceof List) {
((List) v).remove(value);
return value;
} else if (value.equals(v)) {
remove(key);
return value;
}
return null;
}
return null;
}
public Object remove(Object key) {
return map.remove(key);
}
public void putAll(Map t) {
map.putAll(t);
}
public void clear() {
map.clear();
}
public Set keySet() {
return map.keySet();
}
public Collection values() {
return map.values();
}
public Set entrySet() {
return map.entrySet();
}
}
希望能帮助到你
已赞过
已踩过<
你对这个回答的评价是?
评论
收起