Using generics for arrays

Can generics be used for arrays?

+3
source share
9 answers

Arrays are already the main types of objects, that is, they are not a class that describes a collection of other objects, such as ArrayList or HashMap.

You also cannot have an array of generic types. In Java, the following is prohibited:

List<String>[] lists = new List<String>[ 10 ];

This is because the compiler must correctly type arrays, and since Java generics are subject to type erasure, you cannot satisfy this compiler in this way.

+5
source

I do not think this is possible because the array is a basic data type.

ArrayList, - . - .

+3

. .

:

class IntArrayList extends ArrayList<Integer> { }
IntArrayList[] iarray = new IntArrayList[5];

, .

+3

. .

+3

? Ofc. :

public static <T> T[] mergeArrays(T[]... arrays) {
    ArrayList<T> arrayList = new ArrayList<T>();

    for (T[] array : arrays) {
        arrayList.addAll(Arrays.asList(array)); //we steal the reflection from core libs
    }
    return arrayList.toArray(arrays[0]);//we steal the reflection from core libs
}

? . - . . . , , .

+1

, . , Collections.

. Sun , . 15.

0

- , , , , String MyPairClass<String, Integer>, , , "", ,

class Maguffin {
    private static class StringIntegerPair extends MyPairClass<String, Integer> {
        private static final long serialVersionUID = 1L;
    };

    ...

    private final StringIntegerPair[] horribleOldArray;

    ...

, , , , , . - :

    ...

    MyPairClass<String, Integer> getSomethingFromTheArray(int index) {
        return horribleOldArray[index];
    }

    ...

}

, - , - . - , , , Java 8.

0

Java Generics .

, , . reified , , .

new List<Integer>[10] ;  

List<String>[] stringListArray=(List<String>[])new List[10];

. .

Which generally indicates that we should avoid using generic arrays.

0
source

If you mean the presence of the List array, then the answer will be negative. new List<Number>[10]is illegal in java. such questions can be accountable if you search them on Google yourself or check out the official textbook tutorial.

0
source

Source: https://habr.com/ru/post/1712388/


All Articles