java - 如何检查 java 中 vector 中是否有用户定义的条目?

标签 java vector contains comparable

我有一个条目 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)).

在这种情况下,ocontain 的方法参数。

关于java - 如何检查 java 中 vector 中是否有用户定义的条目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13213549/

相关文章:

c++ - 将 vector 的迭代器发送到函数中。 (C++)

c++ - 如何在 C++ 中比较两个数组并返回不匹配的值

如果两个字符串共享任何字符,SQL 则返回 TRUE

java - 在具有单个 HTTP 请求的 servlet 线程上运行长时间运行的进程总是不好吗?

java - Gradle with Eclipse - 资源未被过滤

c++ - 通过属性值从 vector 中删除对象的 unique_ptr

java - 两个相同的数组但包含方法不起作用

c# - 使用 "List<int[]>.Contains(new int[] { .. })"检查列表中的数组,总是返回 false

java - 回滚 liferay 中的 webcontent 版本

java - 调用静态 Void 方法