chapter 17 容器深入研究
填充容器
package cn.test; import java.util.ArrayList;
import java.util.Collections;
import java.util.List; class StringAddress{
private String s;
public StringAddress(String s) {this.s=s;};
public String toString() {
return super.toString()+" "+s;
} }
public class FillingLists {
public static void main(String[] args) {
List<StringAddress> list=new ArrayList<StringAddress>(Collections.nCopies(4, new StringAddress("Hello")));
System.out.println(list);
Collections.fill(list, new StringAddress("World!"));
System.out.println(list);
}
}
一种Generator解决方案
public interface Generator<T> {
T next();
}
package cn.test; import java.util.ArrayList; public class CollectionData<T> extends ArrayList<T> {
public CollectionData(Generator<T> gen,int quantity) {
for(int i=0;i<quantity;i++) {
add(gen.next());
}
}
public static <T> CollectionData<T>
list(Generator<T> gen,int quantity){
return new CollectionData<T>(gen,quantity);
}
}
Set和存储顺序
队列
package cn.test; import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.PriorityBlockingQueue; public class QueueBehavior {
private static int count=10;
static <T> void test(Queue<T> queue,Generator<T> gen) {
for(int i=0;i<count;i++) {
queue.offer(gen.next());
while(queue.peek()!=null) {
System.out.print(queue.remove()+" ");
}
}
System.out.println();
}
static class Gen implements Generator<String>{
String[] s=("one two three four five six seven "
+ "eight nine ten").split(" ");
int i;
public String next() {
return s[i++];
} }
public static void main(String[] args) {
test(new LinkedList<String>(),new Gen());
test(new PriorityQueue<String>(),new Gen());
test(new ArrayBlockingQueue<String>(count),new Gen());
test(new ConcurrentLinkedQueue<String>(),new Gen());
test(new LinkedBlockingQueue<String>(),new Gen());
test(new PriorityBlockingQueue<String>(),new Gen()); } }
优先级队列
理解Map
性能
SortedMap
散列与散列码
package cn.test; import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.Map;
import java.util.Random; class Groundhog{
protected int number;
public Groundhog(int n) {number = n;}
public String toString() {
return "Groundhog # "+number;
}
}
class Prediction{
private static Random rand=new Random(47);
private boolean shadow=rand.nextDouble() > 0.5;
public String toString() {
if(shadow)
return "Six more weeks of Winter!";
else
return "Early Spring!";
}
}
public class SpringDetector {
public static <T extends Groundhog>
void detectSpring(Class<T> type)throws Exception{
Constructor<T> ghog = type.getConstructor(int.class);
Map<Groundhog,Prediction> map=new HashMap<Groundhog,Prediction>();
for(int i=0;i<10;i++)
map.put(ghog.newInstance(i), new Prediction());
System.out.println("map = "+map);
Groundhog gh = ghog.newInstance(3);
System.out.println("Looking up prediction for "+gh);
if(map.containsKey(gh))
System.out.println(map.get(gh));
else
System.out.println("Key not found: "+gh);
}
public static void main(String[] args) throws Exception {
detectSpring(Groundhog.class);
}
}
为速度而散列
覆盖hashCode()
Collection或Map的同步控制
public class Synchronization {
public static void main(String[] args) {
Collection<String> c = Collections.synchronizedCollection(new ArrayList<String>());
List<String> list = Collections.synchronizedList(new ArrayList<String>());
Set<String> s = Collections.synchronizedSet(new HashSet<String>());
SortedSet<String> ss = Collections.synchronizedSortedSet(new TreeSet<String>());
Map<String,String> m=Collections.synchronizedMap(new HashMap<String,String>());
Map<String,String> sm=Collections.synchronizedSortedMap(new TreeMap<String,String>());
}
}
快速报错
public class FailFast {
public static void main(String[] args) {
Collection<String> c=new ArrayList<String>();
Iterator<String> it=c.iterator();
c.add("An object");
try {
String s=it.next();
} catch (ConcurrentModificationException e) {
System.out.println(e);
} }
}
// java.util.ConcurrentModificationException
在获取迭代器后,容器发生了变化。
持有引用
Hashtable
Hashtable 过时的类,线程安全,键值不为null;
HashMap 线程不安全 ,但可以通过Collections类转为线程安全。Map m = Collections.synchronizeMap(hashMap),键值可以为null;
Stack
package cn.test; import java.util.LinkedList;
import java.util.Stack; enum Month{
january,february,march,april,may,june,july,august,september,october,november
}
public class Stacks {
public static void main(String[] args) {
Stack<String> stack=new Stack<String>();
for(Month m:Month.values())
stack.push(m.toString());
System.out.println("stack = "+ stack);
stack.addElement("The last line");
System.out.println("element 5 = "+stack.elementAt(5));
System.out.println("popping elements : ");
while(!stack.empty())
System.out.println(stack.pop()+" ");
LinkedList<String> lstack=new LinkedList<String>();
for(Month m: Month.values())
lstack.addFirst(m.toString());
System.out.println("lstack = "+lstack);
while(!lstack.isEmpty())
System.out.println(lstack.removeFirst()+" ");
}
}
chapter 18 Java I/O系统
输入和输出
XML
I/O流的典型使用方式
对象序列化
对于某些实现了Serialiazable 又不想被序列化的字段,可以在字段前添加 transient 关键字。