简体   繁体   English

java - 如何检查hashset中是否存在向量元素?

[英]how to check if vector element is present in hashset or not in java?

I have to return vector that doesnot conatins duplicate element.我必须返回不包含重复元素的向量。

    static Vector removeDuplicates(Vector<Integer> arr)
    { 
    Vector<Integer> v =new Vector<>();
    Set<Integer> set=new HashSet<Integer>();
    for(int i=0;i<arr.size();i++)
    {
    if(!set.contains(arr[i]))//  it says array required but found vector   
    }
    }

So many questions about this code...关于这段代码的很多问题......

Why Vector ?为什么是Vector Why doesn't it just take Collection as a parameter, why not return Set ?为什么不直接把Collection作为参数,为什么不返回Set呢?

Anyway, it's really only总之,真的只是

static Vector<Integer> removeDuplicates(Vector<Integer> arr) {
    return new Vector<>(new HashSet<>(arr));
}

if you insist on the signature.如果你坚持签名。

Or或者

static <T> Vector<T> removeDuplicates(Vector<T> arr)) { // ...

if you want the generic version.如果你想要通用版本。 But again, I recommend但我再次推荐

static <T> Set<T> removeDuplicates(Collection<T> arr)) { // ...
    return new new HashSet<>(arr);
}

and get rid of the code altogether by inlining it.并通过内联完全摆脱代码。

Here is the code for what you were trying to do:这是您尝试执行的操作的代码:

And the output of the program is :程序的输出是:

[1, 2, 3, 1, 2, 4]
[1, 2, 3, 4]

But I recommend you to use list or arraylist or any other data structures as nobody uses vector in java these days.但是我建议您使用 list 或 arraylist 或任何其他数据结构,因为现在没有人在 java 中使用 vector 。

In the code, you need to check first that if the current element is present in the set or not if it is not present then only add the element to the new vector that you are returning.在代码中,您需要首先检查当前元素是否存在于集合中,如果不存在则只将元素添加到您要返回的新向量中。

package test;

import java.util.HashSet;
import java.util.Set;
import java.util.Vector;

public class test {

    public static void main(String[] args) {
        Vector<Integer> vector = new Vector<>();
        vector.addElement(1);
        vector.addElement(2);
        vector.addElement(3);
        vector.addElement(1);
        vector.addElement(2);
        vector.addElement(4);

        System.out.println(vector);

        vector = removeDuplicates(vector);
        System.out.println(vector);
    }

    static Vector<Integer> removeDuplicates(Vector<Integer> vector) {
        Vector<Integer> v = new Vector<>();
        Set<Integer> set = new HashSet<Integer>();
        for (int i = 0; i < vector.size(); i++) {
            if (set.add(vector.elementAt(i))) {
                v.addElement(vector.elementAt(i));
            }
        }
        return v;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM