Java: Remove Duplicates In Vector

Either you do this

or this, if you do not need a new Vector object created

Related Posts Plugin for WordPress, Blogger...

12 comments

  1. This worked great! However, I have never used LinkedHashSet and don’t quite understand what is going on in option 1 above. Could you further explain? Thanks!!

  2. a LinkedHashedSet does not allow duplicates so you can just pass that as the parameter when you instantiate a Vector object and voila! no more duplicates in the Vector

  3. Thanks for your quick response! Ok I did this once and it worked fine, and it still is working fine. However I am using Method 1 above to remove duplicates from a second Vector that I am using but using LinkedHashSet is not removing them. What exactly does LinkedHashSet look for when determining if an element is a duplicate or not? Thanks!

  4. hi brandon. in the first method, the originalVect’s contents are of String. just like how the equals() method works in the String class could be the same way how LinkedHashSet checks for duplicates and removes them if found

  5. Hmm..well my both of my Vector contains Java objects and the first time I used this it worked, but I can’t figure out why it won’t work for my 2nd Vector of objects. I’m going to have to debug a little more, but any other help you could provide would be awesome. Thanks!

  6. This is a very exciting post, I was looking for this knowledge. Just so you know I found your website when I was researching for blogs like mine, so please check out my site sometime and leave me a comment to let me know what you think.

  7. Question and answer:
    We can duplicate and r remove vector by using in the equal to method.By using thes we can duplicate the vector and remove the vecotr in java

  8. Well on older Java you can do this if it is a String, or you’d have to have the equals overloaded on the object in the Vector.

    Vector newVec = new Vector();

    newVec.add(“1”);
    newVec.add(“2”);
    newVec.add(“1”);
    newVec.add(“2”);
    newVec.add(“1”);

    System.out.println(newVec.toString());
    for(int i=0; i<newVec.size(); i++)
    {
    int cP = newVec.lastIndexOf(newVec.get(i));
    if(cP != i)
    {
    newVec.remove(cP);
    i–;
    }
    }
    System.out.println(newVec.toString());

Leave a Reply

Your email address will not be published. Required fields are marked *