Java Creates a New Map.Entry Array

I am having problems casting an array of objects into an array of key-value pairs, with generic types for 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 for a class (rather than an interface) also doesn't do the trick.

Error tracing:

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
+3
source share
2 answers

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

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

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

Alternatively, you can create an instance of a non-generic type and apply it 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 usually not preferred.

+2
source

Object Map. ?

0

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


All Articles