OnJava8-Examples/generics/ArrayOfGeneric.java

29 lines
910 B
Java
Raw Normal View History

2015-09-07 11:44:36 -06:00
// generics/ArrayOfGeneric.java
// (c)2021 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
public class ArrayOfGeneric {
static final int SIZE = 100;
static Generic<Integer>[] gia;
@SuppressWarnings("unchecked")
public static void main(String[] args) {
2016-01-25 18:05:55 -08:00
try {
gia = (Generic<Integer>[])new Object[SIZE];
} catch(ClassCastException e) {
System.out.println(e.getMessage());
}
2015-06-15 17:47:35 -07:00
// Runtime type is the raw (erased) type:
gia = (Generic<Integer>[])new Generic[SIZE];
System.out.println(gia.getClass().getSimpleName());
gia[0] = new Generic<>();
2015-12-18 11:28:19 -08:00
//- gia[1] = new Object(); // Compile-time error
2015-06-15 17:47:35 -07:00
// Discovers type mismatch at compile time:
2015-12-18 11:28:19 -08:00
//- gia[2] = new Generic<Double>();
2015-06-15 17:47:35 -07:00
}
2015-09-07 11:44:36 -06:00
}
/* Output:
2016-01-25 18:05:55 -08:00
[Ljava.lang.Object; cannot be cast to [LGeneric;
2015-06-15 17:47:35 -07:00
Generic[]
2015-09-07 11:44:36 -06:00
*/