mynameisJEFF
mynameisJEFF

Reputation: 4239

Java: Can we cast a set into an arraylist ?

I have a hashmap called gg. I want to take out its keys using keySet() method and pass them as parameter of another method.

method_A( gg.keySet());

public void method_A(ArrayList<Integer> jj){
 ....
}

But I got this error: error: incompatible types: Set<Integer> cannot be converted to ArrayList<Integer>.

Then I saw this:

method_A (new ArrayList<Integer>(gg.keySet()));

What is it doing actually ? It looks like type casting to me. I am puzzled. Could someone explain to me what is going on ?

Upvotes: 0

Views: 184

Answers (1)

Eran
Eran

Reputation: 394156

new ArrayList<Integer>(gg.keySet()) is not type casting. It's more like a copy constructor (though actual copy constructors usually take an argument of the same type that is being instantiated, which is not the case here).

It's creating a new ArrayList<Integer> instance using the constructor that accepts a Collection as an argument. It adds all the elements found in the Collection to the new ArrayList.

Here's the doc of that constructor :

   /**
     * Constructs a list containing the elements of the specified
     * collection, in the order they are returned by the collection's
     * iterator.
     *
     * @param c the collection whose elements are to be placed into this list
     * @throws NullPointerException if the specified collection is null
     */
    public ArrayList(Collection<? extends E> c)

Upvotes: 2

Related Questions