Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: How can I dynamically create an array of a specified type based on the type of an object?

Tags:

java

arrays

I would like to take a passed List that I know is homogeneous and from it create an array of the same type as the elements within it.

Something like...

List<Object> lst = new ArrayList<Object>;

lst.add(new Integer(3));

/// somewhere else ...

assert(my_array instanceof Integer[]);
like image 439
JeffV Avatar asked Jun 30 '10 18:06

JeffV


People also ask

How do you create an array of objects dynamically in Java?

Creating an Array Of Objects In Java – An Array of Objects is created using the Object class, and we know Object class is the root class of all Classes. We use the Class_Name followed by a square bracket [] then object reference name to create an Array of Objects.

How do you create an array dynamically?

It's easy to initialize a dynamic array to 0. Syntax: int *array{ new int[length]{} }; In the above syntax, the length denotes the number of elements to be added to the array.

Can array grow dynamically in Java?

An array cannot be resized dynamically in Java.

Can we create array of objects in Java?

Answer: Yes. Java can have an array of objects just like how it can have an array of primitive types. Q #2) What is an Array of Objects in Java? Answer: In Java, an array is a dynamically created object that can have elements that are primitive data types or objects.


2 Answers

The conversion would happen runtime, while the type is lost at compile time. So you should do something like:

public <T> T[] toArray(List<T> list) {
    Class clazz = list.get(0).getClass(); // check for size and null before
    T[] array = (T[]) java.lang.reflect.Array.newInstance(clazz, list.size());
    return list.toArray(array);
}

But beware that the 3rd line above may throw an exception - it's not typesafe.

like image 108
Bozho Avatar answered Oct 19 '22 03:10

Bozho


This method is type safe, and handles some nulls (at least one element must be non-null).

public static Object[] toArray(Collection<?> c)
{
  Iterator<?> i = c.iterator();
  for (int idx = 0; i.hasNext(); ++idx) {
    Object o = i.next();
    if (o != null) {
      /* Create an array of the type of the first non-null element. */
      Class<?> type = o.getClass();
      Object[] arr = (Object[]) Array.newInstance(type, c.size());
      arr[idx++] = o;
      while (i.hasNext()) {
        /* Make sure collection is really homogenous with cast() */
        arr[idx++] = type.cast(i.next());
      }
      return arr;
    }
  }
  /* Collection is empty or holds only nulls. */
  throw new IllegalArgumentException("Unspecified type.");
}
like image 26
erickson Avatar answered Oct 19 '22 03:10

erickson