简体   繁体   中英

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 ? Why doesn't it just take Collection as a parameter, why not return 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.

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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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