Search code examples
javaarraysobjectcastingset

How do I fill a Set with array of different object that extends the object in the Set


How can I fill a Set<SomeObject>with array (Object[]) of different object that extends the object in the Set.

I got this array of objects which I want to cast into a Set of objects that extends the objects in the array Like this:

Object[] a = new Object[1];
a[0] = new SomeObject();
Set<SomeObject> aSet = new HashSet<SomeObject>(a);

If it is impossible to cast an array to a Set like that, is it then possible to cast an array to a List?

NOTE: If you want to achieve this the loop way like this:

Object[] a = new Object[1];
a[0] = new SomeObject("Something");
Set<SomeObject> aSet = new HashSet<SomeObject>();

for(int i = 0; i < a.length; i++){
    aSet.add((SomeObject)a[i])  
}

But I don't want to do it the loop way, and, yes, I know all objects extends the java.lang.Object class.


Solution

  • In response to OP's recent comment:

    Somehow I can't cast this List to a Set so I let the method cast the List to a Array and return that Array

    In that case you can simply do this:

    List<SomeObject> list = ...
    Set<SomeObject> set = new HashSet<SomeObject>(list);
    

    What is important: This code has absolutely nothing to do with casting! What actually happens is that you have a List of objects and you create a new Set and copy all the elements from the list into it. The original list isn't modified by this operation.

    To repeat my comment, you obviously have misunderstood what casting in Java means. Casting of object works in a very different way that casting of primitive values. Please read some article on this subject, such as this one: http://www.volantec.biz/castingObjects.htm