PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, November 7, 2022

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

 November 07, 2022     arrays, casting, java, object, set     No comments   

Issue

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



Answered By - Natix
Answer Checked By - Katrina (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing