Home > Blockchain >  Java initialize array with mutiple type parameters error java.lang.ClassCastException: [Ljava.lang.O
Java initialize array with mutiple type parameters error java.lang.ClassCastException: [Ljava.lang.O

Time:05-01

public class ArrayPQK<P extends Comparable<P>, T> implements PQK<P, T> {
int maxsize;
int size;
int head,tail;
Pair<P, T>[] nodes;
public ArrayPQK(int k) {
    maxsize=k;
    size=0;
    head=tail=0;
    nodes= (Pair<P, T>[])new Object[k];
    
}

Whenever I try to run this code in main,

private static void testPQK() {
    System.out.println("-------------------");
    PQK<Integer, String> pq = new ArrayPQK<Integer, String>(3);// error here
 }

I got the error as, Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [LPair; at ArrayPQK.(ArrayPQK.java:11)

now from what i searched, we cannot create a generic type array so we use Object[k], but apparently things are different when a class is extended,

public class ArrayPQK<P extends Comparable<P>, T> implements PQK<P, T> {

and what i have found is that i better use ArrayList with generic types instead of an array, but i have to figure this out without using it.

CodePudding user response:

Change it to new Pair[k]. – shmosel

This worked, thank you.

  • Related