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

后端 未结 4 1195
借酒劲吻你
借酒劲吻你 2020-12-10 03:47

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...



        
相关标签:
4条回答
  • 2020-12-10 04:22

    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.

    0 讨论(0)
  • 2020-12-10 04:30

    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.");
    }
    
    0 讨论(0)
  • 2020-12-10 04:38
    java.lang.reflect.Array.newInstance(Class<?> componentType, int length)
    
    0 讨论(0)
  • 2020-12-10 04:42

    If you need to dynamically create an array based on a type known only at runtime (say you're doing reflection or generics) you'll probably want Array.newInstance

    0 讨论(0)
提交回复
热议问题