Introduction
Generic arrays, where the array elements share a common type parameter, present a unique challenge in Java due to the interplay between generics and arrays' covariant 행동.
question
일반 유형이 비슷한 확장되는 제네릭 배열을 만들 수 있습니까? Attempts to cast an Object array to a generic array that extends Comparable face issues, raising the following question: Is there a workaround?
Answer
Generics and Arrays: A Compatibility Puzzle
Generics and arrays have fundamentally different ways of handling 유형 :
방법 :
private Hashtable; ... hashtable = (비교 가능 []) array.newinstance (비교 가능 .class, tablesize);
private Comparable[] hashtable;
...
hashtable = (Comparable[])Array.newInstance(Comparable.class, tableSize);
이 접근법은 일반 유형의 슈퍼 유형 (이 경우 비슷한)의 배열을 만들 수 있지만,이 배열은 원하는 일반 유형이 아니라는 점에 유의해야합니다.
Generics?
해결 방법이있는 동안, 제네릭을 사용하는 배열을 사용하는대로 :
휴대 가능성 및 유지 가능성 : 다른 Java Virtual Machines (jvms)는 유형의 지우기를 다르게 처리 할 수있어 동작을 덜 휴대하기 쉽고 유지하기가 더 어려워 질 수 있습니다.
이는 일반 객체의 컬렉션을 관리하는 효율적이고 유형 안전 방법을 제공합니다. Arraylist는 제네릭의 유연성을 제공하고 배열 및 제네릭과 관련된 잠재적 인 함정을 피합니다.
부인 성명: 제공된 모든 리소스는 부분적으로 인터넷에서 가져온 것입니다. 귀하의 저작권이나 기타 권리 및 이익이 침해된 경우 자세한 이유를 설명하고 저작권 또는 권리 및 이익에 대한 증거를 제공한 후 이메일([email protected])로 보내주십시오. 최대한 빨리 처리해 드리겠습니다.
Copyright© 2022 湘ICP备2022001581号-3