2015-09-07 11:44:36 -06:00
|
|
|
// arrays/ArrayOfGenerics.java
|
2016-12-30 17:23:13 -08:00
|
|
|
// (c)2017 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.
|
2016-09-23 13:23:35 -06:00
|
|
|
// Visit http://OnJava8.com 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
|
|
|
|
2017-05-15 16:15:22 -06:00
|
|
|
//- ls[1] = new ArrayList<Integer>();
|
2016-01-25 18:05:55 -08:00
|
|
|
// 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
|
|
|
}
|