1

I have a function that returns an Object. The Object can contain an array of primatives or an array of objects. In C# I can create an empty array of objects or primatives using code like:

Array values = Array.CreateInstance(/*Type*/type, /*int*/length);

Is there an equivalent in Java?

3 Answers 3

1

How to create an array of objects of a specific class type

Test[] tests = new Test[length] ;

And if you want to have a mix up of Primitives and Objects, though it is not suggestable, If you want to mix primitives with Objects

Object[] objs = new Object[length];

That allows you to both primitives(in form of wrappers) and normal Objects together.

If you have a class called Test of your own, you can create an array of Test's like

Note that until you initialise the elements in that array, they have null as their value.

Sign up to request clarification or add additional context in comments.

Comments

1

Assuming you only know the element type at execution time, I think you're looking for Array.newInstance.

Object intArray = Array.newInstance(int.class, 10);
Object stringArray = Array.newInstance(String.class, 10);

(That will create an int[] and a String[] respectively.)

2 Comments

OK that works great. Thanks. Now what if I am creating the object type from a class path string. For example: Class<?> cls = Class.forName("myclasspath");
@Mike: So use Object array = Array.newInstance(cls, 10);
0
Object[] array = new Object[length];

Or with your own type:

MyType[] array = new MyType[length];

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.