3

Is it possible to use generics for arrays?

4
  • I know that I can use ArrayList,but I want to know that can I use generics for arrays?? Commented Jul 11, 2009 at 18:57
  • ...why? What's deficient in the collection classes? Commented Jul 11, 2009 at 19:11
  • 1
    sometimes api's require arrays. Commented Aug 21, 2009 at 19:33
  • possible duplicate of How to create an array of Type Variables, in Java? Commented May 23, 2011 at 11:56

9 Answers 9

5

Arrays are already basic objects types, that is to say they're not a class that describes a collection of other objects like ArrayList or HashMap.

You cannot have an array of generified types either. The following is illegal in Java:

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

This is because arrays must be typed properly by the compiler, and since Java's generics are subject to type erasure you cannot satisfy the compiler this way.

Sign up to request clarification or add additional context in comments.

1 Comment

Erasure only affects the runtime, so it's not a type safety constraint that arrays don't allow generics.
3

I don't think this is possible because an array is a basic datatype.

But you can use a ArrayList to have something similar. In most of the cases using a collection of some kind pays of very well.

Comments

3

No. Arrays must have a compile-time type.

Comments

3

Have a look at this site. It should contain all generics related FAQs.

On a sidenote:

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

If you subclass a generic object with a concrete type, that new class can be used as array type.

Comments

1

Can you use it? Ofc. Example:

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
}

Is it a good idea? No. This code is just me playing around with generics. It led to a dark ally. You are better of using collections. They do what you want, and the syntax is prettier in the long run.

Comments

0

It's possible, but far from pretty. In general, you're better of using the Collections framework instead.

See Sun's Generics tutorial, page 15, for a detailed explanation.

Comments

0

If I ever want to, say, refactor the elements of an array to a better type, like from String to MyPairClass<String, Integer>, I tend to avoid the unchecked cast problem by making an empty subclass that "bakes in" the generic parameters, e.g.

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

    ...

    private final StringIntegerPair[] horribleOldArray;

    ...

This nested class will probably also need constructors that delegate up to the generic type's constructors, depending on what you do when adding new array elements. When passing the elements out of the enclosing class, just cast them up to the generic type:

    ...

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

    ...

}

All this being said, there should rarely be a need to do something like this if you are writing something new from scratch. The only real benefit of arrays over the Collections framework classes is that you can write them out as literals, and this will no longer be an advantage come next year when Java 8 is released.

Comments

0

Excerpt from Java Generics and collections.

Arrays reify their component types, meaning that they carry run-time information about the type of their components. This reified type information is used in instance tests and casts, and also used to check whether assignments into array components are permitted.

Therefore one is not allowed to have the suntax

new List<Integer>[10] ;  

However the following is allowed

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

Now this is not a really good practice. Such casts are not safe and should be avoided.

Which in general points to the fact that we should avoid using arrays of generic type.

Comments

0

If you mean having an array of List then the answer is no. new List<Number>[10] is illegal in java. questions like these could be answerable by searching it in Google alone or checking out the official Generics tutorial

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.