码迷,mamicode.com
首页 > 编程语言 > 详细

《Think in Java》17

时间:2019-01-08 17:49:01      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:div   code   sts   lin   .com   pie   ict   port   cep   

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

  在获取迭代器后,容器发生了变化。

 

《Think in Java》17

标签:div   code   sts   lin   .com   pie   ict   port   cep   

原文地址:https://www.cnblogs.com/mryangbo/p/10240231.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!