四、使用‘泛型’與‘增強for循環’的簡單例子
genericTest.Java
package tigers;
import Java.util.*;
public class genericTest {
public static void main(String[] args) {
List<String> lists = new ArrayList<String>();
lists.add("aaaaaaaaaaaa");
lists.add("bbbbbbbbbbbbb");
lists.add("cccccccccccccc");
lists.add("ddddddddddddd");
lists.add("eeeeeeeeeeeeeeeee");
for (String s :lists) {
System.out.println(s);
}
}
}
結果:
C:\forms>Javac -d c:\forms\web-inf\classes
c:\forms\src\genericTest.Java
C:\forms>Java -classpath c:\forms\web-inf\classes tigers.genericTest
aaaaaaaaaaaa
bbbbbbbbbbbbb
cccccccccccccc
ddddddddddddd
eeeeeeeeeeeeeeeee
C:\forms>
五、使用‘枚舉’類型
package tigers;
import Java.util.EnumMap;
enum Simple1 {
A,B,C,D;
}
public class SimpleEnum {
public static void main(String[] args) {
System.out.println(Simple1.A);
for (Simple1 s : Simple1.values()) {
System.out.print(s);
}
System.out.println();
Simple1 s2 = Simple1.D;
switch(s2) {
case A:
System.out.print("A");
break;
case B:
System.out.print("B");
break;
case C:
System.out.print("C");
break;
default:
System.out.print(s2);
}
System.out.println();
EnumMap<Simple1, String> aMap = new EnumMap<Simple1, String>(Simple1.class);
String str = "something";
int i = 0;
for (Simple1 s3 : Simple1.values()) {
aMap.put(s3, str += (i++ + " "));
}
System.out.println(aMap);
for (Simple1 s4 : Simple1.values()) {
System.out.println(s4 + " = " + aMap.get(s4));
}
}
}