0

Long story short, playing around with generics and comparables, having trouble printing out values directly. Here's a simple example

class Ideone<Key extends Comparable<Key>>
{
    private Key[] keys = (Key[]) new Comparable[10];
    public static void main (String[] args) throws java.lang.Exception
    {
        Ideone<Integer> test = new Ideone();
        test.keys[0] = 3;
        System.out.println(test.keys[0]);
    }
}

Error I am getting is:

Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Comparable; cannot be cast to [Ljava.lang.Integer;

Live code example: http://ideone.com/JPfUZw

Luiggi Mendoza
  • 81,685
  • 14
  • 140
  • 306
Taylor Huston
  • 1,014
  • 1
  • 13
  • 29

1 Answers1

0

A Key is a Comparable, not vice versa. Also, you cannot initialize an array of generic using downcasting.

Fix the code here:

private Key[] keys = (Key[]) new Comparable[10];

To

private Comparable[] keys = new Comparable[10];

This will work since Key is a Comparable and you can store Comparables in keys array, so a Key can be stored there.

Or pass the class of the generic as argument and use Array.newInstance as shown here:

Key[] keys;

public Ideone(Class<Key> clazz, int size) {
    keys = (Key[]) Array.newInstance(clazz, size);
}
Community
  • 1
  • 1
Luiggi Mendoza
  • 81,685
  • 14
  • 140
  • 306