《Think in Java》17~18
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 关键字。
《Think in Java》17~18的更多相关文章
- 读书笔记 之《Thinking in Java》(对象、集合)
一.前言: 本来想看完书再整理下自己的笔记的,可是书才看了一半发现笔记有点多,有点乱,就先整理一份吧,顺便复习下前面的知识,之后的再补上. 真的感觉,看书是个好习惯啊,难怪人家说"书籍是人类 ...
- 《Head First Java》读书笔记(1) - Java语言基础
<Head First Java>(点击查看详情) 1.写在前面的话 这本书的知识点说实话感觉有点散乱,但是贵在其将文字转换成了生动和更容易接受的图片,大量的比喻让人感受到了知识点的有趣之 ...
- 读书笔记 之《Thinking in Java》(对象、集合、异常)
一.前言 本来想看完书再整理下自己的笔记的,可是书才看了一半发现笔记有点多,有点乱,就先整理一份吧,顺便复习下前面的知识,之后的再补上. 真的感觉,看书是个好习惯啊,难怪人家说“书籍是人类进步的阶梯” ...
- 《Play for Java》学习笔记(一)项目框架
从今天开始认真复习<Play for JAVA>,该书以一个案例为主线,以前为应付项目马马虎虎看了一遍,好多地方都不明白!现在跟着这本书再走一遍,认真模拟,当做一个项目啦!! 一.Play ...
- 《图书管理系统——java》
/* (程序头部凝视開始) * 程序的版权和版本号声明部分 * Copyright (c) 2011, 烟台大学计算机学院学生 * All rights reserved. * 文件名: < ...
- 【书海】《Head First Java》 ——读后总结
<Head First Java> 中文版 (第二版) IT`huhui前言录 <Head First Java>这本书我不算特别细的看了一遍.认为十分适合初学者,甚至是没接触 ...
- 我本人一直以来犯的错误,在看了《Think In Java》后才抓了出来(转)
也许你是只老鸟,也许你的程序编的很精,但是,在你的程序生活,你也许没有注意到一些“常识性”的问题,因为有些时候我们不需要去注意,我们的程序 照样能够运行得飞快,但是如果那天有一个无聊的人问你一个像这样 ...
- 《Thinking in Java》 And 《Effective Java》啃起来
前言 今天从京东入手了两本书,<Thinking in Java>(第四版) 和 <Effective Java>(第二版).都可以称得上是硬书,需要慢慢啃的,预定计划是在今年 ...
- D1——初读《Head First Java》
今天随便看了点<Head First Java>,发觉这本书的风格真是有趣.打算先把这本书踏踏实实的看了.学习切忌好高骛远.心浮气躁,尤其入门基础阶段更应该踏踏实实地学习知识.下面随便谈谈 ...
随机推荐
- Build/Run Instructions for Codec Engine Examples
General Information This page explains how to build the examples provided in the Codec Engine (CE) p ...
- 使用ControllerClassNameHandlerMapping实现SpringMVC的CoC配置
使用CoC,惯例优先原则(convention over configuration)的方式来配置SpringMVC可以帮我们声明Controller的时候省下很多功夫. 只要我们的Controlle ...
- spring MVC模式拦截所有入口方法的入参出参打印
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.serializer.SerializerFeature; im ...
- 阻塞和唤醒线程——LockSupport功能简介及原理浅析
目录 1.LockSupport功能简介 1.1 使用wait,notify阻塞唤醒线程 1.2 使用LockSupport阻塞唤醒线程 2. LockSupport的其他特色 2.1 可以先唤醒线程 ...
- 01-MySQL优化大的思路
首先不是看它的表结构等等.从整体上去观察,不断去看它的状态.这个状态往往不是一两个小时可以看出来的,得写一个脚本,观察它的24小时的周期性变化,不断刷新它的脚本,观察它的Status.主要是看它有没有 ...
- U3D OnDrawGizmos
private void OnDrawGizmos() { Debug.Log("OnDrawGizmos"); Gizmos.DrawWireSphere(this.transf ...
- Python open()文件处理使用介绍
1. open()语法open(file[, mode[, buffering[, encoding[, errors[, newline[, closefd=True]]]]]])open函数有很多 ...
- spring4-4-jdbc-02
1.简化 JDBC 模板查询 每次使用都创建一个 JdbcTemplate 的新实例, 这种做法效率很低下. JdbcTemplate 类被设计成为线程安全的, 所以可以再 IOC 容器中声明它的单个 ...
- 洛谷 P3627 [APIO2009](抢掠计划 缩点+spfa)
题目描述 Siruseri 城中的道路都是单向的.不同的道路由路口连接.按照法律的规定, 在每个路口都设立了一个 Siruseri 银行的 ATM 取款机.令人奇怪的是,Siruseri 的酒吧也都设 ...
- GC Roots的理解以及如何判断一个对象为“垃圾”
http://blog.csdn.net/Great_Smile/article/details/49935307 这篇博客中讲解了哪些可以作为GC Roots以及如何判断一个对象为垃圾