OnJava8-Examples/arrays/ArrayOfGenerics.java

34 lines
1.1 KiB
Java
Raw Normal View History

2015-09-07 11:44:36 -06:00
// arrays/ArrayOfGenerics.java
2015-12-15 11:47:04 -08:00
// (c)2016 MindView LLC: see Copyright.txt
2015-11-15 15:51:35 -08:00
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
2015-06-15 17:47:35 -07:00
import java.util.*;
public class ArrayOfGenerics {
@SuppressWarnings("unchecked")
public static void main(String[] args) {
List<String>[] ls;
List[] la = new List[10];
2016-01-25 18:05:55 -08:00
ls = (List<String>[])la; // Unchecked cast
2015-06-15 17:47:35 -07:00
ls[0] = new ArrayList<>();
2016-01-25 18:05:55 -08:00
// -ls[1] = new ArrayList<Integer>();
// error: incompatible types: ArrayList<Integer>
// cannot be converted to List<String>
// ls[1] = new ArrayList<Integer>();
// ^
2015-06-15 17:47:35 -07:00
// The problem: List<String> is a subtype of Object
Object[] objects = ls; // So assignment is OK
// Compiles and runs without complaint:
objects[1] = new ArrayList<>();
// However, if your needs are straightforward it is
// possible to create an array of generics, albeit
2016-01-25 18:05:55 -08:00
// with an "unchecked cast" warning:
2015-06-15 17:47:35 -07:00
List<BerylliumSphere>[] spheres =
(List<BerylliumSphere>[])new List[10];
2016-01-25 18:05:55 -08:00
Arrays.setAll(spheres, n -> new ArrayList<>());
2015-06-15 17:47:35 -07:00
}
2015-09-07 11:44:36 -06:00
}