J2SE 1.5 Tiger新特性学习
时间:2011-01-31
一、定义一个简单的“泛型”类
package tigers;
public class GenericIdentify {
public static void main(String[] args) {
Generic1 gStr = new Generic1();
gStr.set("aaaaaaaaaaaaaaaaa");
Generic1 gInt = new Generic1();
gInt.set(new Integer(1321423));
Generic1 gBool = new Generic1();
gBool.set(new Boolean(true));
System.out.println(gStr.get() + "\n" +
gInt.get() + "\n" +
gBool.get() + "\n");
((Generic1)gInt).set("bbbbbbbbbbbbb"); //避开类型检查
System.out.println(gInt.get());
}
}
class Generic1 { //声明泛型
private A a;
public void set(A a) {
this.a = a;
}
public A get() {
return this.a;
}
}
C:\tiger>javac -d c:\tiger\cls\ c:\tiger\src\*.java
Note: c:\tiger\src\GenericIdentify.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
C:\tiger>java -classpath c:\tiger\cls tigers.GenericIdentify
aaaaaaaaaaaaaaaaa
1321423
true
bbbbbbbbbbbbb
C:\tiger>
J2SE 1.5 Tiger新特性学习(2)
时间:2011-01-31
二、关于格式化输出的简单例子
package tigers;
import java.util.Formatter;
public class FormatPrint2 {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
Formatter forma = new Formatter(sb);
forma.format("%12.10f", Math.PI);
System.out.println(forma);
System.out.printf("%12.10f", Math.PI);
}
}
结果:
C:\tiger>javac -d c:\tiger\cls c:\tiger\src\FormatPrint2.java
C:\tiger>java -classpath c:\tiger\cls tigers.FormatPrint2
3.1415926536
3.1415926536
三、可变长度参数与格式化输出
package tigers;
public class FormatPrint {
public static void main(String[] args) {
printf("%, %, % and % are my friends!", "BITAN", "HELEN", "KATHY", "SUSAN");
printf("%, %, %, % and % are my favorites" ,"A", "B", "C", "D");
}
public static void printf(String msg, String... strs) {
int i = 0;
char[] chars = msg.toCharArray();
for ( char c : chars) {
System.out.print(c == ''%'' ? strs[i++] : c);
}
System.out.println();
}
}
C:\tiger>javac -d c:\tiger\cls\ c:\tiger\src\*.java
C:\tiger>java -classpath c:\tiger\cls tigers.FormatPrint
BITAN, HELEN, KATHY and SUSAN are my friends!
A, B, C, D and Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at tigers.FormatPrint.printf(FormatPrint.java:12)
at tigers.FormatPrint.main(FormatPrint.java:6)
J2SE 1.5 Tiger新特性学习(3)
时间:2011-01-31
四、使用‘泛型’与‘增强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&q
|