J'ai ce code:Comment puis-je créer un tableau d'éléments dont les entrées ont des champs génériques?
import java.util.*;
import java.lang.*;
import java.io.*;
class Main{
public static void main (String[] args){
Foo<String> foo = new Foo<String>(1000);
}
}
class Foo<Key extends Comparable<Key>>{
private Entry[] a;
private class Entry{
Key key;
}
public Foo(int size){
a = (Entry[])new Object[size]; // <- this is the problem
}
}
quand je compile, je reçois une erreur, en disant:
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [LFoo$Entry;
at Foo.<init>(Main.java:17)
at Main.main(Main.java:7)
J'ai essayé:
import java.util.*;
import java.lang.*;
import java.io.*;
class Main{
public static void main (String[] args){
Foo<String> foo = new Foo<String>(1000);
}
}
class Foo<Key extends Comparable<Key>>{
private Entry[] a;
private class Entry{
Key key;
}
public Foo(int size){
a = new Entry[size];
}
}
Mais je suis une erreur en disant :
Main.java:17: error: generic array creation
a = new Entry[size];
^
Est-il possible de créer ce tableau du tout?
Pourquoi ne peut pas faire cela par défaut? Cela ressemble à une douleur d'avoir à lancer et à écrire cet appel de méthode à long terme. – Pavel
vous pouvez toujours faire 'import java.lang.reflect;' et écrire simple '... Array.newInstance (...' – Andremoniy