If a class with a generic declaration is used without an incoming type parameter, the type parameter defaults to the first upper bound type specified when the parameter is declared, which is referred to as the raw type.
eg
public class Listtest {
Public
static void Main (string[] args) {
List List = new ArrayList ();
List.add ("AAAA");
List.add ("bbbbbbb");
List.add ("CCCC");
list<integer> intlist = list;
for (int i=0; i<intlist.size (); i++) {
System.out.println (Intlist.get (i));
}
}
}
Output:
Aaaa
bbbbbbb
Cccc
The above program compiles, and runs everything normally. It can be seen that when a program assigns a variable of primitive type to a variable with generic information, as long as their type remains compatible---such as assigning a list variable to List<integer>, no matter what type of element is actually contained in the list collection, there is no problem with the system. It should be noted, however, that there is a potential problem when assigning a primitive type of variable (such as a list variable) to a variable with generic information: The JVM treats all the elements in the collection as integers. If the output involves the type of the collection element, the program runs with ClassCastException.
eg
public class Listtest {
public static void Main (string[] args) {
List List = new ArrayList ();
List.add ("AAAA");
List.add ("bbbbbbb");
List.add ("CCCC");
list<integer> intlist = list;
for (Integer i:intlist) {
System.out.println (i);
}
}
}
Output Result:
Exception in thread "main" java.lang.ClassCastException:java.lang.String cannot is cast to Java.lang.Integer
At Com.zb.zb.ListTest.main (listtest.java:11)
Eg2
public class Listtest {
public static void Main (string[] args) {
Apple<integer> a = new apple<integer> (6);
For (String apple:a.getapples ()) {
System.out.println (Apple);
}
Apple B = A; (1)
For (String apple:b.getapples ()) {(2)
System.out.println (Apple);
// }
}
}
Class Apple<t extends number>{
T size;
Public Apple () {
}
Public Apple (T size) {
this.size = size;
}
public void SetSize (T size) {
this.size = size;
}
Public list<string> Getapples () {
list<string> list = new arraylist<string> ();
for (int i = 0; i < 3; i++) {
List.add (New apple<integer> (Ten * i). toString ());
}
return list;
}
Public String toString () {
Return "apple[size=" + size + "]";
}
Note: (1) assigns the Apple<integer> object to an Apple variable, and the object loses all generic information at (2) output. That is, all information in the angle brackets, including the type of the return value of the Getapples () method list<string> the angle brackets in the information.
Java is not allowed to create generic arrays.
Java Generic Potential error