Java convert generic list to array

Convert a generic list to an array

You can just call list.toArray[T[] array] and not have to worry about implementing it yourself, but as aioobe said, you can't create an array of a generic type due to type erasure. If you need that type back, you need to create a typed instance yourself and pass it in.

This is due to type erasure. The generics are removed in compilation, thus the Helper.toArray will be compiled into returning an Object[].

For this particular case, I suggest you use List.toArray[T[]].

String[] array = list.toArray[new String[list.size[]]];

If you want to produce your method through brute force, and you can guarantee that you'll only call the method with certain restrictions, you can use reflection:

public static T[] toArray[List list] { T[] toR = [T[]] java.lang.reflect.Array.newInstance[list.get[0] .getClass[], list.size[]]; for [int i = 0; i < list.size[]; i++] { toR[i] = list.get[i]; } return toR; }

This approach has problems. As list can store subtypes of T, treating the first element of the list as the representative type will produce a casting exception if your first element is a subtype. This means that T can't be an interface. Also, if your list is empty, you'll get an index out of bounds exception.

This should only be used if you only plan to call the method where the first element of the list matches the Generic type of the list. Using the provided toArray method is much more robust, as the argument provided tells what type of array you want returned.

You can't instantiate a Generic type like you did here:

T[] array = [T[]] new Object[list.size[]];

As, if T is bounded to a type, you're typecasting the new Object array to a bounded type T. I would suggest using List.toArray[T[]] method instead.

See Guava's Iterables.toArray[list, class].

Example:

@Test public void arrayTest[] { List source = Arrays.asList["foo", "bar"]; String[] target = Iterables.toArray[source, String.class]; } String[] array = list.toArray[new String[0]]; public static T[] toArray[Collection c, T[] a] { return c.size[]>a.length ? c.toArray[[T[]]Array.newInstance[a.getClass[].getComponentType[], c.size[]]] : c.toArray[a]; } /** The collection CAN be empty */ public static T[] toArray[Collection c, Class klass] { return toArray[c, [T[]]Array.newInstance[klass, c.size[]]]; } /** The collection CANNOT be empty! */ public static T[] toArray[Collection c] { return toArray[c, c.iterator[].next[].getClass[]]; }

The problem is the component type of the array that is not String.

Also, it would be better to not provide an empty array such as new IClasspathEntry[0]. I think it is better to gives an array with the correct length [otherwise a new one will be created by List#toArray which is a waste of performance].

Because of type erasure, a solution is to give the component type of the array.

Example:

public static C[] toArray[Class componentType, List list] { @SuppressWarnings["unchecked"] C[] array = [C[]]Array.newInstance[componentType, list.size[]]; return list.toArray[array]; }

The type C in this implementation is to allow creation of an array with a component type that is a super type of the list element types.

Usage:

public static void main[String[] args] { List list = new ArrayList[]; list.add["abc"]; // String[] array = list.toArray[new String[list.size[]]]; // Usual version String[] array = toArray[String.class, list]; // Short version System.out.println[array]; CharSequence[] seqArray = toArray[CharSequence.class, list]; System.out.println[seqArray]; Integer[] seqArray = toArray[Integer.class, list]; // DO NOT COMPILE, NICE ! }

Waiting for reified generics..

As pointed earlier this will work:

String[] array = list.toArray[new String[0]];

And this will also work:

String[] array = list.toArray[new String[list.size[]]];

However, in the first case a new array will be generated. You can see how this is implemented in Android:

@Override public T[] toArray[T[] contents] { int s = size; if [contents.length < s] { @SuppressWarnings["unchecked"] T[] newArray = [T[]] Array.newInstance[contents.getClass[].getComponentType[], s]; contents = newArray; } System.arraycopy[this.array, 0, contents, 0, s]; if [contents.length > s] { contents[s] = null; } return contents; } Worked solution!

Just copy interface and class inside your project. This :

public interface LayerDataTransformer { T transform[F from]; Collection transform[Collection from]; T[] toArray[Collection from]; }

and this :

public abstract class BaseDataLayerTransformer implements LayerDataTransformer { @Override public List transform[Collection from] { List transformed = new ArrayList[from.size[]]; for [F fromObject : from] { transformed.add[transform[fromObject]]; } return transformed; } @Override public T[] toArray[Collection from] { Class clazz = [Class] [[ParameterizedType] getClass[].getGenericSuperclass[]].getActualTypeArguments[][1]; T[] transformedArray = [T[]] java.lang.reflect.Array.newInstance[clazz, from.size[]]; int index = 0; for [F fromObject : from] { transformedArray[index] = transform[fromObject]; index++; } return transformedArray; } }

Usage.

Declare a subclass of BaseDataLayerTransformer

public class FileToStringTransformer extends BaseDataLayerTransformer { @Override public String transform[File file] { return file.getAbsolutePath[]; } }

And use :

FileToStringTransformer transformer = new FileToStringTransformer[]; List files = getFilesStub[];// returns List //profit! String[] filePathArray = transformer.toArray[files];

I use this simply function. IntelliJ just hates that type cast T[] but it works just fine.

public static T[] fromCollection[Class c, Collection collection] { return collection.toArray[[T[]]java.lang.reflect.Array.newInstance[c, collection.size[]]]; }

And call looks like this:

Collection col = new ArrayList[Arrays.asList[1,2,3,4]]; fromCollection[Integer.class, col];

This gist that I wrote gives a good solution to this problem.

Following siegi's suggestion on Atreys' answer, I wrote a constructor which finds the "nearest common ancestor" [NCA] class and uses that class to create the array. If checks for nulls and if the provided Collection is length 0 or all nulls, the default type is Object. It totally ignores Interfaces.

import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.ArrayList; import java.lang.reflect.Array; import java.util.Iterator; public class FDatum { public T[] coordinates; // magic number is initial size -- assume FDatum d = new FDatum[new ArrayList[Arrays.asList[[double]1, [Double]3.3]]] class java.lang.Double NCA: class java.lang.Double d ==> com.nibrt.fractal.FDatum@9660f4e jshell> d.coordinates $12 ==> Double[2] { 1.0, 3.3 } jshell> d = new FDatum[new ArrayList[Arrays.asList[[double]1, [Double]3.3, [byte]7]]] class java.lang.Byte class java.lang.Double NCA: class java.lang.Number d ==> com.nibrt.fractal.FDatum@6c49835d jshell> d.coordinates $14 ==> Number[3] { 1.0, 3.3, 7 } jshell> d = new FDatum[new ArrayList[Arrays.asList[[double]1, [Double]3.3, [byte]7, "foo"]]] class java.lang.Byte class java.lang.Double class java.lang.String NCA: class java.lang.Object d ==> com.nibrt.fractal.FDatum@67205a84 jshell> d.coordinates $16 ==> Object[4] { 1.0, 3.3, 7, "foo" }

When you have a generic List you will be able to know the class of the object at the runtime. Therefore, the best way to implement it is like this:

public static T[] list2Array[Class clazz, List elements] { T[] array = clazz.cast[Array.newInstance[clazz.getComponentType[], elements.size[]]]; return elements.toArray[array]; }

Why do you need the Class parameter?

Because, we have a generic list and it will not provide the information necessary to get an array of precisely the type we are looking for, of course, while preserving type safety. As opposed to the other answers, which will either give you back an Object array or result in warnings at compile time. This approach will gives you a clean solution. The "hack" here is the clazz.cast[] call, which compiles without warnings for whatever type you declare an instance of list2Array[].

Now, how can you use it?

Simple, just call it like this:

List list = Stream.of["one", "two", "three"].collect[Collectors.toList[]]; String[] numbers = list2Array[String[].class, list]; System.out.println[Arrays.toString[numbers]];

Here is the compiling sample of this: //ideone.com/wcEPNI

Why does it work?

It works because class literals are treated by the compiler as instances of java.lang.Class. This also works for interfaces, enums, any-dimensional arrays [e.g. String[].class], primitives and the keyword void.

Class itself is generic [declared as Class, where T[] stands for the type that the Class object is representing], meaning that the type of String[].class is Class.

Note: You won't be able to get an array of primitives, since primitives can't be used for type variables.

Comments

  1. Davion

    • 2015/3/12

    .

  2. Jeffery

    • 2020/1/20

    We can use Java 8 Stream API to convert int array to list of Integer. Below are the steps: Convert the specified primitive array to a sequential stream using Arrays.stream[] Box each element of the stream to an Integer using IntStream.boxed[] Use Collectors.toList[] to accumulate the input elements into a new List.

  3. Saint

    • 2016/3/21

    In your example, it is because you can't have a List of a primitive type. In other words, List is not possible. You can, however, have a List using the​

  4. Brandon

    • 2018/10/2

    Input :array['k', [45, 23, 56, 12]] Output :[45, 23, 56, 12] Explanation: the array with elements [45, 23, 56, 12] are converted into list with the same elements. Approach to the problem: We want to convert an array into an ordinary list with the same items. For doing so we need to use a function

  5. Peterson

    • 2015/9/17

    How do you turn an array into a collection?

    • Not Equal To notation in Javascript to use in jQuery
    • node.js require all files in a folder?
    • ComboBox OwnerDrawVariable Font format size problem
    • shorthand for arrow-functions for object property names
    • Get last insert id after a prepared insert with PDO
  6. Dakota

    • 2015/6/29

    My question is: How do I convert the values in the Object[] array into a List so that the datatable is populated? I have tried using the Arrays.toList[] method, and then iterating through that adding the values to a list, but I understand that that simply returns a fixed size list of the backed array. It does not return a List of values. Any

  7. Beau

    • 2019/4/27

    Can you put an array inside an array?

  8. Cesar

    • 2019/5/2

    I need an easy way to convert a List to a string array. I have: var the_list = new List[]; the_list.Add[1]; the_list.Add[2]; the_list.Add[3]; string[] the_array = new string[the_list.Count]; for[var i = 0 ; i < the_array.Count; ++i] the_array[i] = the_list[i].ToString[]; which looks to be very ugly to me. Is there an easier way?

  9. Larry

    • 2017/1/6

    The following code explains the conversion of string array to List and printing the values. using System;; using System.Text;; using System.Collections.Generic

  10. Kingsley

    • 2018/8/2

    Converts an array of one type to an array of another type. public: generic static cli::array ^ ConvertAll [cli::array ^ array, Converter ^ converter]; C#.

    • Table make responsive
    • Difficulty with Powershell regex
    • C++ class extension [different size of array in inheriting classes]
    • Python - error with OOP
    • Tag problem c# listbox
  11. Roger

    • 2017/11/30

    .

  12. Kash

    • 2019/9/4

    Java example to show you how to convert a Array to a List. ArrayToList.java. package com.mkyong; import java.util.ArrayList; import java.util.

  13. Rogers

    • 2016/9/10

    using Collectors. toList[]

  14. Colson

    • 2020/12/29

    We can use numpy ndarray tolist[] function to convert the array to a list. If the array is multi-dimensional, a nested list is returned. For one-dimensional array, a list with the array elements is returned.

  15. Morgan

    • 2017/3/9

    Java program to convert a List to an array. // using get[] in a loop. import java.io.*;. import java.util.List;. import java.util.LinkedList;. class GFG. {. public static void

    • How to get the average intensity value of the red color area in C# using EMGU CV library?
    • Xorg loading an image
    • JPA / Hibernate unidirectional one-to-one mapping with shared primary key
    • Get random enum from a select group
    • Best way to store last name/business name in a customer table
  16. Enoch

    • 2016/5/23

    Java example to show you how to convert a Array to a List. ArrayToList.java. package com.mkyong; import java.util.ArrayList; import java.util.

  17. Murati

    • 2016/8/11

    Step 1: We create a List and populate it with some strings. The List here can only hold strings [or null]. List Step 2: Next we use ToArray on the List. To test it, we pass the string array to the Test [] method.

  18. D'Angelo

    • 2020/7/27

    .

  19. Edison

    • 2017/3/11

    Following methods can be used for converting Array To ArrayList: It returns an List containing all of the elements in this // array in the same order. Note that there is a collection parameter c into which elements to be inserted and array

  20. Brodie

    • 2020/1/24

    If you want to convert List to an array of primitive types, you need to loop through the elements of the List and fill the array as given in the below example. You can also use the Apache commons library. a] Using For loop 1

    • How to create a Facebook-App style notifications custom table?
    • How to select the next and previous entities via Entity Framework?
    • android.os.NetworkOnMainThreadException in AsynkTask Class
    • Informatica issue - transformation
    • Pointers passed by reference updated with every loop iteration: [Sanity check - Part 2]
  21. Terry

    • 2016/6/9

    These C# programs convert Lists and strings. They use If you require per-item conversion, you can loop over the string array returned by Split. C# program that​

  22. Tucker

    • 2021/3/17

    Convert JSON Array to and from Java List using Gson #Java #JSON November 30, 2019 In this quick tutorial, you'll learn how to use the Gson library to convert a JSON array string into a list of Java Objects and vice versa.

  23. Rex

    • 2016/8/15

    How to Convert between an Array and a List Using plain Java, Guava or Apache Commons Collections.

  24. Brody

    • 2017/9/30

    In the last tutorial we have shared two methods of converting an ArrayList to Array with example. Here we are sharing three different ways to convert an Array to ArrayList. Basically we are converting an String Array to ArrayList of String type. String array[] to ArrayList Method 1: Conversion using Arrays.asList[] Syntax:

  25. Justin

    • 2020/10/6

    The question is "how to convert the following array to an ArrayList?". copyOf[​elementData, size, Object[].class]; }. 2. Actually the list returned is not java.util.

    • Word Automation: Replace an Image using C#
    • Difference between priority queue and a heap
    • Installing Apache Web Server on 64 Bit Mac
    • custom combobox win32
    • EEFileLoadException when using C# classes in C++[win32 app]
  26. Cade

    • 2019/2/10

    The simplest way I've found to convert a Stack into a List is using the following line: List stackToList = new ArrayList[stack]; However, this yields the stack reversed. Meaning, if your stack was 1, 2, 3 you would expect in the list 3, 2, 1 because that's the order the stack objects

  27. Nicolas

    • 2021/2/5

    Converting between List and Array is a very common operation in Java.The best and easiest way to convert a List into an Array in Java is to use

  28. Quincy

    • 2020/7/26

    List list = Arrays.asList[str]; // unmodifiable list list.add["D"]; // java.lang.​UnsupportedOperationException List list2 = new

  29. Daxton

    • 2015/12/19

    How do you convert an array to a list in Java?

  30. Colombo

    • 2020/5/15

    How do I convert an array to a list in Java? I used the Arrays.asList[] but the behavior [and signature] somehow changed from Java SE 1.4.2 [docs now in archive] to 8 and most snippets I found on the web use the 1.4.2 behaviour. For example: int[] spam = new int[] { 1, 2, 3 }; Arrays.asList[spam] on 1.4.2 returns a list containing the elements

    • Js mouse click events
    • Using LINQ to create pairs from two different list where the entries have same attribute
    • Try block without any catch statements
    • How to call a php controller method using jquery?
    • How to implement iterator design pattern on C++?
  31. Gomez

    • 2017/8/27

    ];

  32. Allen

    • 2019/10/11

    Previous Next In this post, we will see how to convert array to list in java. There are may ways to convert array to list: By using Arrays.asList[]: This is an easy method to convert Array into list.We just need to pass array as parameter to asList[] method.It is a Static method available in Arrays class so, called it by class name Arrays.asList[].

  33. Yehuda

    • 2019/10/29

    How do you add an int array to an ArrayList in Java?

Comments are closed.

Video liên quan

Chủ Đề