0

下面的函数返回产品列表。产品列表应该是唯一的。

向量 ServAttributes 存储自定义类的对象。自定义类有一个函数 getProduct,它给出了可能包含重复的产品名称。

我是否需要滚动整个向量、检索对象、调用函数 getProduction 并添加到哈希集中以删除重复的产品?Vector 有时会存储 400 个自定义类的对象。有没有做以下功能的捷径?

private Vector<ServAttributes> ServAttributes = null;

public HashSet<String> retProduct() {

    HashSet<String> Produset = new HashSet<String>();

    for (int x = 0; x < ServAttributes.size(); x++) {
        ServAttributes record = ServAttributes.get(x);

        if (record.getProduct()) != null) {
            Produset.add(record.getProduct());
        }   

    return Produset;
}
4

2 回答 2

1

使用像 Guava 这样的通用帮助程序库,您可以通过函数方式执行此操作:

return Sets.newHashSet(Iterables.filter(Iterables.transform(serverAttributes, new Function<ServAttributes, String>() {
    public void apply(ServAttributes attributes) {
        return attributes.getProduct();
    }
}), Predicates.notNull()));

使用股票 Java,您可以进行一些改进。您可以为初学者使用增强的 for 循环:

for ( ServAttributes attributes : serverAttributes ) {
    productSet.add(attributes.getProduct());
}
于 2012-06-19T04:06:06.790 回答
0

如果您有权访问ServAttributes类,则覆盖equalshashCode方法,然后使用以下代码删除重复项:

注意:这将返回 HashSet ServAttributes。如果您只需要产品名称,那么您将不得不遍历向量。

HashSet<ServAttributes> noDub= new HashSet(new LinkedHashSet(ServAttributes));

ServAttributes类中重写equalsandhashCode如下:

@Override
public int hashCode() {
    return product.hashCode();
}
@Override
public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if(obj instanceof ServAttributes) {
        ServAttributes s1 = (ServAttributes)obj;

        if(s1.getProduct().equals(this.getProduct())) {
            return true;
        }
    }
    return false;
}
于 2012-06-19T04:31:11.200 回答