Srikanth Nakka
Srikanth Nakka

Reputation: 758

Converting Vector to HashSet in Java

Could someone explain, how the following code printed the Vector elements (in which order they were printed)?

Code:

import java.util.HashSet;
import java.util.Vector;
class Test
{
    public static void main(String [] args) throws Exception
    {
        Vector data = new Vector();
        data.add("apple");
        data.add("mango");
        data.add("papaya");
        data.add("cherry");
        data.add("banana");
        data.add("apple");
        System.out.println(getData(data));
    }
    public static Vector getData(Vector v)
    {
        return new Vector(new HashSet(v));
    }
}

Output:

[banana, cherry, papaya, apple, mango]

Upvotes: 0

Views: 4189

Answers (1)

Vivek Vermani
Vivek Vermani

Reputation: 2004

  1. Hashset doesn't store elements in a user specified Order. As soon as you created the Hashset using Vector, Elements lost the specified order.

  2. Moreover they don't allow duplicates, so the second apple got lost.

Upvotes: 2

Related Questions