Java 5.0 tiger 程序高手秘笈笔记(一)
看了一本书《Java 5.0 tiger 程序高手秘笈》下面是我的笔记:有以下10部分内容:
1. Generic
2. Enumerated
3. autoboxing 与Unboxing
4. vararg
5. Annotation
6. for/in语句
7. 静态的import
8. 格式化
9. Threading
Ps: 该书源代码地址:http://www.oreilly.com/catalog/javaadn/中文版本由中南大学出版社出版;
下面分依次总结::::
一:Generic
以前没有听说过,不知道是干什么的;作用:
Generic提供对Java的类型安全性的支持;也是许多Java5.0新特性的基石,支撑着vararg,annotation enumeration,collection,甚是是语言中的一些并行功能。
Type-safe 的 List:
语法:
List
例子1:
package com.oreilly.tiger.ch02;
import java.util.ArrayList;
import java.util.List;
public class BadIdea {
private static List
public static void fillList(List
for (Integer i : list) {
ints.add(i);
}
}
public static void printList() {
for (Integer i : ints) {
System.out.println(i);
}
}
public static void main(String[] args) {
List
myInts.add(1);
myInts.add(2);
myInts.add(3);
System.out.println("Filling list and printing in normal way...");
fillList(myInts);
printList();
try {
List list = (List)BadIdea.class.getDeclaredField("ints").get(null);
list.add("Illegal Value!");
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Printing with illegal values in list...");
printList();
}
}
总结:可以限定list可以接受的类型,避免频繁的类型转换。但List以及其他collection class仍然不能接受primitive value;
Type-safe 的Map语法:
Map
Map
Map
Interating over parameterized Type
For/in 循环提供了一个避免用java.util.Iterator 这个class的方法;
例子:
package com.oreilly.tiger.ch02;
import java.io.IOException;
import java.io.PrintStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
public class GenericsTester {
public GenericsTester() {
}
public void testTypeSafeMaps(PrintStream out) throws IOException {
Map
for (int i=0; i<100; i++) {
squares.put(i, i*i);
}
for (int i=0; i<10; i++) {
int n = i*3;
out.println("The square of " + n + " is " + squares.get(n));
}
}
public void testTypeSafeLists(PrintStream out) throws IOException {
List listOfStrings = getListOfStrings();
for (Iterator i = listOfStrings.iterator(); i.hasNext(); ) {
String item = (String)i.next();// 这里是关键
// Work with that string
}
List
onlyStrings.add("Legal addition");
/**
* Uncomment these two lines for an error
onlyStrings.add(new StringBuilder("Illegal Addition"));
onlyStrings.add(25);
*/
}
public void testTypeSafeIterators(PrintStream out) throws IOException {
List
listOfStrings.add("Happy");
listOfStrings.add("Birthday");
listOfStrings.add("To");
listOfStrings.add("You");
for (Iterator
String s = i.next();
out.println(s);
}
printListOfStrings(getListOfStrings(), out);
}
private List getList() {
List list = new LinkedList();
list.add(3);
list.add("Blind");
list.add("Mice");
return list;
}
private List
List
list.add("Hello");
list.add("World");
list.add("How");
list.add("Are");
list.add("You?");
return list;
}
public void testTypeSafeReturnValues(PrintStream out) throws IOException {
List
补充:软件开发 , Java ,