3

I'm having problems casting an object array to a key-value pair array, with generic types for the key and value objects. Here is a minimal example.

public class Main {
    public static void main(String[] args) {
        array = (Map.Entry<Integer, Integer>[]) new Object[1];
    }

    private static Map.Entry<Integer, Integer>[] array;
}

Changing Map.Entry to a class (rather than interface) doesn't do the trick either.

Error trace:

run:
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.util.Map$Entry;
        at lab2.Main.main(Main.java:13)
Java Result: 1
1
  • Why would you think that new Object[1] is type compatibile with Map.Entry<Integer, Integer>[]? Of course a new vanilla Object[] array cannot be cast to something more specific. In the same way that this is not legal either: (String)new Object();. Commented Nov 2, 2010 at 16:51

1 Answer 1

3

Do you need to have an array? You can do the following with a List:

public static void main(String[] args) {
    array = new ArrayList<Map.Entry<Integer, Integer>>();
}

private static List<Map.Entry<Integer, Integer>> array;

Alternately, you can instantiate the non generic type, and cast to the generic type:

public static void main(String[] args) {
    array = (Map.Entry<Integer, Integer>[])new Map.Entry[1];
}

private static Map.Entry<Integer, Integer>[] array;

However, this will give you warnings, and is generally not preferred.

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

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.