如何在java中检查vector中是否有用户定义的条目?
我有一个输入向量。每个条目都是此类的一个实例:如何在java中检查vector中是否有用户定义的条目?,java,vector,contains,comparable,Java,Vector,Contains,Comparable,我有一个输入向量。每个条目都是此类的一个实例: public class Entry implements Comparable<Entry>{ private String _key; private CustomSet _value; [...] @Override public int compareTo(Entry a) { return this._key.compareTo(a._key); } }
public class Entry implements Comparable<Entry>{
private String _key;
private CustomSet _value;
[...]
@Override
public int compareTo(Entry a) {
return this._key.compareTo(a._key);
}
}
这似乎不起作用。为什么?我怎样才能让它工作
p.S.CustomSet是另一个用户定义的类,与我的观点无关您必须在Entry类中重新定义equals方法,因为这是确定元素是否属于集合的依据,如文档所述:
如果此向量包含指定的元素,则返回true。更多
形式上,当且仅当此向量至少包含
一个元素e使得o==null?e==null:o.equalse
在本例中,o是contain的方法参数。您必须在Entry类中重新定义equals方法,因为contains依赖于此来确定元素是否属于集合,如文档所述:
如果此向量包含指定的元素,则返回true。更多
形式上,当且仅当此向量至少包含
一个元素e使得o==null?e==null:o.equalse
在本例中,o是contain的方法参数。问题在于您没有相同的对象,而是有两个具有相同键的不同对象 这: 创建一个新对象,如果现在调用entries.addsample,然后尝试调用entries.containssample,它将返回true,因为它确实是同一个对象。但是,如果您有以下情况,则情况并非如此:
Entry sample = new Entry(key, new CustomSet());
Entry sample1 = new Entry(key, new CustomSet());
entries.add(sample);
if(entries.contains(sample1)) // It will still return false.
解决方案包括重新定义方法,即使用键来区分对象。因此,在Entry类中,您应该添加以下内容:
public boolean equals(Object o)
{
if(o == null || !getClass().equals(o.getClass())) return false;
if(o == this) return true;
Entry p = (Entry) o;
return this.key.compareTo(p.key) == 0;
}
问题是您没有相同的对象,而是有两个具有相同键的不同对象 这: 创建一个新对象,如果现在调用entries.addsample,然后尝试调用entries.containssample,它将返回true,因为它确实是同一个对象。但是,如果您有以下情况,则情况并非如此:
Entry sample = new Entry(key, new CustomSet());
Entry sample1 = new Entry(key, new CustomSet());
entries.add(sample);
if(entries.contains(sample1)) // It will still return false.
解决方案包括重新定义方法,即使用键来区分对象。因此,在Entry类中,您应该添加以下内容:
public boolean equals(Object o)
{
if(o == null || !getClass().equals(o.getClass())) return false;
if(o == this) return true;
Entry p = (Entry) o;
return this.key.compareTo(p.key) == 0;
}
public boolean equals(Object o)
{
if(o == null || !getClass().equals(o.getClass())) return false;
if(o == this) return true;
Entry p = (Entry) o;
return this.key.compareTo(p.key) == 0;
}