1

I'm getting an error that I can't understand. I defined the class Couple in Java this way :

public class Couple<T1, T2>{
private T1 t1;
private T2 t2;
 public Couple(T1 t1, T2 t2) {
 this.t1 = t1;
 this.t2 = t2;
 }
 public Couple() {
 this.t1 = null;
 this.t2 = null;
 }
 public T1 getFirst(){return t1;}
 public T2 getSecond(){return t2;}
}

And in an another class, I try to define an array this way :

Couple<byte[], byte[]>[] res = new Couple<byte[], byte[]>[10];

But Eclipse tells me the error "Cannot create a generic array of Couple<byte[], byte[]> ". Well, the thing that I don't understand is that I mentionned that I wanted a couple of byte[], so there is no genericity at this point, am I wrong ?

asked Jan 31, 2015 at 15:20
4
  • 1
    You may not create arrays of generic types. Couple<byte[], byte[]> is a generic type, and you're trying to create an array of this type. So that won't compile. Use a List<Couple<<byte[], byte[]>> instead. Commented Jan 31, 2015 at 15:25
  • Ok, I will try it. Thought that if I mentionned the type of couple there was no more genericity. Ty anyway Commented Jan 31, 2015 at 15:26
  • As DennisW said, you cannot do that, Java is quite peculiar about it. But you can do this: Couple<byte[], byte[]>[] res = new Couple[10]; You will probably get some warnings, suppress them. Oh, and, by the way: this has absolutely nothing to do with eclipse. Commented Jan 31, 2015 at 15:56
  • 2
    possible duplicate of How to create a generic array in Java? Commented Jan 31, 2015 at 16:11

1 Answer 1

3

Java generics are not reified, which means that the 'implementations' are not classes in their own right. The fact that you can't create arrays of generic types is an inherent limitation of the language.

I'd recommend you to use a List instead of an array.

answered Jan 31, 2015 at 15:29

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.