Thinking 容器

2017-11-18  本文已影响14人  Demons_96

P217泛型和类型安全的容器

不显示指定泛型的将自动继承自Object,此时容器可装任何类型的类,取出时需强制转换为指定的类型。

public class ApplesAndOrangesWithoutGenerics {
    @SuppressWarnings("unchecked")
    public static void main(String[] args) {
        ArrayList arrayList = new ArrayList();
        for (int i = 0; i < 3; i++)
            arrayList.add(new Apple());
        
        arrayList.add(new Orage());
        
        for (int i=0;i<arrayList.size();i++)
            System.out.println(((Apple)arrayList.get(i)).getId());  //最后一个取值报错
    }
}

class Apple {
    private static long counter;
    private final long id = counter++;

    public long getId() {
        return id;
    }
}

class Orage {

}

结果

0
1
2
Exception in thread "main" java.lang.ClassCastException: eleven.Orage cannot be cast to eleven.Apple at eleven.ApplesAndOrangesWithoutGenerics.main(ApplesAndOrangesWithoutGenerics.java:15)

P220添加一组元素

/**
 * Arrays.asList():接收一个数组或者是用逗号分隔的元素列表
 * Collections.addAll():接收一个Collection对象、一个数组、用都逗号分隔的列表 传统的addAll()方法
 */
public class AboutAsListAddAll {
    public static void main(String[] args) {
        Integer[] ints = { 1, 2, 3, 4, 5 };
        Collection<Integer> collection = new ArrayList<Integer>(Arrays.asList(ints));
        
        // 只能接收另一个Collection对象作为参数,不灵活
        collection.addAll(Arrays.asList(6, 7, 8, 9, 10));   

        Collections.addAll(collection, 11, 12, 13, 14, 15); // 这个快,首选
        Collections.addAll(collection, ints);

        print(collection);

        List<Integer> list = Arrays.asList(ints);
        list.set(0, 0); //将数组第一个元素设置成0,能改变ints的值
        print(list);
        //会有运行时错误,底层表示为数组,不能调整尺寸
//      list.add(1);
        
        List<Integer> list2 = new ArrayList<Integer>();
        list2.addAll(Arrays.asList(ints));
        list2.add(6);
        print(list2);
    }
    public static void print(Collection<Integer> c) {
        for (Integer i : c) System.out.print(i + " ");
        System.out.println();
    }
}

结果

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 1 2 3 4 5
0 2 3 4 5
0 2 3 4 5 6

P222

容器的区别

P234 Map统计随机数生成的分布

public class Statistics {
    public static void main(String[] args) {
        Random rand = new Random(47);
        Map<Integer, Integer> m = new TreeMap<Integer, Integer>();
        for (int i = 0; i < 1000; i++) {
            int r = rand.nextInt(20);
            Integer freq = m.get(r);
            m.put(r, freq == null ? 1 : freq + 1);
        }
        System.out.println(m);
    }
}

结果

{0=42, 1=44, 2=53, 3=43, 4=44, 5=53, 6=42, 7=53, 8=46, 9=56, 10=58, 11=55, 12=48, 13=55, 14=52, 15=50, 16=53, 17=50, 18=51, 19=52}



















































这是空白页
上一篇 下一篇

猜你喜欢

热点阅读