Conversion from List<T> to Array T[]

Conversion from ListT to array T[]

Try using

MyClass[] myArray = list.ToArray();

How to Convert ListT[] to array T[]?

You appear to be turning a List of Lists into one flat list.

If you are in C#, there are Linq utility functions for this:

// Namespaces you need
using System.Linq;
using System.Collections.Generic;

////////////////////////////////////////////
// In your code block //
////////////////////////////////////////////
List<T[]> myJaggedList = new List<T[]>();

// (Populate here)

T[] flatArray = myJaggedList.SelectMany(m => m).ToArray();

Converting a list to an array with ToArray()

This is the error (as pointed out from Darkshadw and Jon Skeet)

listItem myList = new List<listItem>();

You are assigning the value of a List to a listItem.

Replace it with

List<listItem> myList = new List<listItem>();

to create a list of listItem. Then

listItem[] myArray = myList.ToArray();

will work.

Convert ListT to Array in C#

Why don't you try doing:

myclass[] arr = data.ToArray();

Edit:
To return the array so it's visible from VBA, you'd need to have your class as ComVisible.

[ComVisible(true)]
public class main
{
public list<myclass> data { get; set; }
}
[ComVisible(true)]
public class myclass
{
public string variety { get; set; }
public string ordertype { get; set; }
public string producttype { get; set; }
}
[ComVisible(true)]
public myclass[] myclasses()
{
myclass[] arr = data.ToArray();
return arr;
}

@freeflow has a great reference link that you can use: https://analystcave.com/excel-use-c-sharp-in-excel-vba/

How to convert a listT to an array T[] using c#

You should just be able to handle this through LINQ's ToArray() method :

var array = yourCollectionOfRecords.ToArray();

How to convert ListT to Array t[] (for primitive types) using generic-method?

As of the current version (Java 12), primitive types can't be represented with Java generics. More specifically, we can't provide a primitive type as a type argument. (We can't do e.g. Foo<int>.) We also can't use type variables as the type in a new expression, so we can't do new T[n] to create an array. Therefore, there's no ideal way to do this.

It is possible to do this reasonably using some reflection (java.lang.reflect.Array), but we need to provide a Class as an argument. Here's an example of how it might be done:

/**
* Unboxes a List in to a primitive array.
*
* @param list the List to convert to a primitive array
* @param arrayType the primitive array type to convert to
* @param <P> the primitive array type to convert to
* @return an array of P with the elements of the specified List
* @throws NullPointerException
* if either of the arguments are null, or if any of the elements
* of the List are null
* @throws IllegalArgumentException
* if the specified Class does not represent an array type, if
* the component type of the specified Class is not a primitive
* type, or if the elements of the specified List can not be
* stored in an array of type P
*/
public static <P> P toPrimitiveArray(List<?> list, Class<P> arrayType) {
if (!arrayType.isArray()) {
throw new IllegalArgumentException(arrayType.toString());
}
Class<?> primitiveType = arrayType.getComponentType();
if (!primitiveType.isPrimitive()) {
throw new IllegalArgumentException(primitiveType.toString());
}

P array = arrayType.cast(Array.newInstance(primitiveType, list.size()));

for (int i = 0; i < list.size(); i++) {
Array.set(array, i, list.get(i));
}

return array;
}

Example call:

List<Integer> list = List.of(1, 2, 3);
int[] ints = toPrimitiveArray(list, int[].class);

Note that Array.set will perform a widening primitive conversion, so the following works:

List<Integer> list = List.of(1, 2, 3);
double[] doubles = toPrimitiveArray(list, double[].class);

But it won't perform a narrowing conversion, so the following throws an exception:

List<Integer> list = List.of(1, 2, 3);
byte[] bytes = toPrimitiveArray(list, byte[].class); // throws

If you wanted, that code could also be used to make duplication easier:

public static int[] toIntArray(List<Integer> list) {
return toPrimitiveArray(list, int[].class);
}
public static double[] toDoubleArray(List<Double> list) {
return toPrimitiveArray(list, double[].class);
}
...

(Having multiple methods like that isn't really generic, though.)


One solution that you'll sometimes see places looks something like this:

public static <P> P toPrimitiveArray(List<?> list) {
Object obj0 = list.get(0);
Class<?> type;
// "unbox" the Class of obj0
if (obj0 instanceof Integer)
type = int.class;
else if (obj0 instanceof Double)
type = double.class;
else if (...)
type = ...;
else
throw new IllegalArgumentException();

Object array = Array.newInstance(type, list.size());

for (int i = 0; i < list.size(); i++) {
Array.set(array, i, list.get(i));
}

return (P) array;
}

There are a variety of problems with that, though:

  • We don't know what type of array to create if the list is empty.
  • Doesn't work if there's more than one type of object in the list.
  • Unchecked casting of the result array to P, so there's a danger of heap pollution.

It's much better to just pass in a Class as an argument.


Also, while it's possible to just write many overloads which unbox arrays:

public static int[]    unbox(Integer[] arr) {...}
public static long[] unbox(Long[] arr) {...}
public static double[] unbox(Double[] arr) {...}
...

Because of the effects of type erasure, it's impossible to write overloads which unbox many different types of List, as in the following:

public static int[]    unbox(List<Integer> list) {...}
public static long[] unbox(List<Long> list) {...}
public static double[] unbox(List<Double> list) {...}
...

That won't compile, because we aren't allowed to have more than one method in the same class with the same name and erasure. The methods would have to have different names.


As a side-note, here are some non-generic solutions:

  • As of Java 8 we can unbox Lists of Integer, Long and Double using the Stream API:

    List<Long> list = List.of(1L, 2L, 3L);
    long[] longs = list.stream().mapToLong(Long::longValue).toArray();
  • Google Guava has Collection unboxing methods in their com.google.common.primitives classes, for example Doubles.toArray:

    List<Double> list = List.of(1.0, 2.0, 3.0);
    double[] doubles = Doubles.toArray(list);

Convert list to array in Java

Either:

Foo[] array = list.toArray(new Foo[0]);

or:

Foo[] array = new Foo[list.size()];
list.toArray(array); // fill the array

Note that this works only for arrays of reference types. For arrays of primitive types, use the traditional way:

List<Integer> list = ...;
int[] array = new int[list.size()];
for(int i = 0; i < list.size(); i++) array[i] = list.get(i);

Update:

It is recommended now to use list.toArray(new Foo[0]);, not list.toArray(new Foo[list.size()]);.

From JetBrains Intellij Idea inspection:

There are two styles to convert a collection to an array: either using
a pre-sized array (like c.toArray(new String[c.size()])) or
using an empty array (like c.toArray(new String[0]).

In
older Java versions using pre-sized array was recommended, as the
reflection call which is necessary to create an array of proper size
was quite slow. However since late updates of OpenJDK 6 this call
was intrinsified, making the performance of the empty array version
the same and sometimes even better, compared to the pre-sized
version. Also passing pre-sized array is dangerous for a concurrent or
synchronized collection as a data race is possible between the
size and toArray call which may result in extra nulls
at the end of the array, if the collection was concurrently shrunk
during the operation.

This inspection allows to follow the
uniform style: either using an empty array (which is recommended in
modern Java) or using a pre-sized array (which might be faster in
older Java versions or non-HotSpot based JVMs).

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.

Convert CollectionListT to 2D array T[][]

.toArray can only convert the collection into a List<Foo>[]. You need to call .toArray on each element of the array of list again to really get a Foo[][].

    @SuppressWarnings("unchecked")
final List<Foo>[] permutedList = permuted.toArray(new List[10]);
final Foo[][] permutedArray = new Foo[10][10];
for (int j = 0; j < 10; ++j) {
permutedArray[j] = permutedList[j].toArray(new Foo[10]);
}

Java List T T[] toArray(T[] a) implementation

From the javadocs:

Like the toArray() method, this method acts as bridge between
array-based and collection-based APIs. Further, this method allows
precise control over the runtime type of the output array, and may,
under certain circumstances, be used to save allocation costs.

This means that the programmer is in control over what type of array it should be.

For example, for your ArrayList<Integer> instead of an Integer[] array you might want a Number[] or Object[] array.

Furthermore, the method also checks the array that is passed in. If you pass in an array that has enough space for all elements, the the toArray method re-uses that array. This means:

Integer[] myArray = new Integer[myList.size()];
myList.toArray(myArray);

or

Integer[] myArray = myList.toArray(new Integer[myList.size()]);

has the same effect as

Integer[] myArray = myList.toArray(new Integer[0]);

Note, in older versions of Java the latter operation used reflection to check the array type and then dynamically construct an array of the right type. By passing in a correctly sized array in the first place, reflection did not have to be used to allocate a new array inside the toArray method. That is no longer the case, and both versions can be used interchangeably.



Related Topics



Leave a reply



Submit