我有一个条目 vector 。每个条目都是此类的一个实例:
public class Entry implements Comparable<Entry>{
private String _key;
private CustomSet _value;
[...]
@Override
public int compareTo(Entry a) {
return this._key.compareTo(a._key);
}
}
vector 声明如下:
Vector<Entry> entries = new Vector<Entry>();
之后, vector 被填充。然后我想检查 vector 中是否有某个键。所以我这样做:
Entry sample = new Entry(key, new CustomSet());
if (entries.contains(sample)) {
// do something
}
这似乎行不通。为什么?我怎样才能让它发挥作用?
附言CustomSet 是另一个用户定义的类,在我看来无关紧要
最佳答案
你必须在你的 Entry
类中重新定义 equals
方法,因为这是 contains
所依赖的来确定一个元素是否属于集合,正如文档所说:
Returns true if this vector contains the specified element. More formally, returns true if and only if this vector contains at least one element e such that (o==null ? e==null : o.equals(e)).
在这种情况下,o
是contain
的方法参数。
关于java - 如何检查 java 中 vector 中是否有用户定义的条目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13213549/