Java编程思想 ch11 持有容器

package Cha11;
import java.util.*;
class Apple{
    private static long counter;
    private final long id = counter++;
    public long id(){return id;}
        }

class Orange{}
/**
 * Created by YL on 2017/9/3.
 */
public class ApplesAndOrangesWithoutGenerics {
    //@SuppressWarnings("unchecked")
    public static void main(String[] args) {
        ArrayList apples = new ArrayList();
        for (int i = 0; i < 3; i++) {
            apples.add(new Apple());
        }
        apples.add(new Orange());
        for(int i=0; i<apples.size(); i++){
            ((Apple)apples.get(i)).id();//没有泛型,取出来的是object类对象
            /*(Apple)apples.get(i).id();
                这样写是将取得的id转为Apple类
             */
        }
    }
}

Exception in thread "main" java.lang.ClassCastException: Cha11.Orange cannot be cast to Cha11.Apple
    at Cha11.ApplesAndOrangesWithoutGenerics.main(ApplesAndOrangesWithoutGenerics.java:22)

package Cha11;
import java.util.*;

class GrannySmith extends Apple{}
class Fuji extends Apple{}
class Gala extends Apple{}
class raeburn extends Apple{}

public class GenericsAndUpcasting {
    public static void main(String[] args){
        ArrayList<Apple> apples = new ArrayList<>();
        apples.add(new GrannySmith());
        apples.add(new Gala());
        apples.add(new Fuji());
        apples.add(new raeburn());
        // foreach 也可用于ArrayList
        for(Apple c:apples){
            System.out.println(c);//向上转型
        }

    }
}

Cha11.GrannySmith@1540e19d
Cha11.Gala@677327b6
Cha11.Fuji@14ae5a5
Cha11.raeburn@7f31245a

11.2 基本概念

1)Collection 一个独立元素的序列–一种存放一组对象的方式。服从一个或者多个规则。
List必须按照插入的顺序保存元素。
set不能有重复元素。
Queue按照排队规则来确定对象。
2)Map。一组成对的”键值对“对象。

List<Apple> apples = new ArrayList<>();
//List是接口,不能实例化,必须用ArrayList或者LinkedList实例化。
向上转型。如果需要使用ArrayList方法就不能向上转型。

11.3 添加一组元素

Arrays.asList();接受数组或者逗号分开的元素列表,将其转换为List对象。
Collection.addAll(Collectioni<>);
只能接受Collection作为输入。不如
Collections.addAll(Collectin c,数组或者逗号分开列表) 灵活。
先构造不含变量的空Collection,再调用Collections.addAll();

“`
public class AddingGroups {
public static void main(String[] args){
Collection collection = new ArrayList<>(Arrays.asList(1,2,3,4,5));
for(Integer e:collection){
System.out.print(e+” “);
}
System.out.println();
Integer[] moreInts1 = new Integer[]{6,7,8,9,10};
//Integer[] moreInts2 = {6,7,8,9,10};只能用于方法定义处
collection.addAll(Arrays.asList(moreInts1));
for(Integer e:collection){
System.out.print(e+” “);
}
System.out.println();
Collections.addAll(collection,11,12,13,14,15);
for(Integer e:collection){
System.out.print(e+” “);
}
System.out.println();
Collections.addAll(collection,moreInts1);
for(Integer e:collection){
System.out.print(e+” “);
}

    List<Integer> list = Arrays.asList(1,2,3,4,5);
    list.set(1,99);
  list.add(21);
  // 可以直接使用Arrays.asList()的输出,将其当作list。但其底层是数组。无法改变数组大小。
  //Runtime error because the underleying array cannot be resized;
}

}

1 2 3 4 5
Exception in thread “main” java.lang.UnsupportedOperationException
1 2 3 4 5 6 7 8 9 10
at java.util.AbstractList.add(AbstractList.java:148)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
at java.util.AbstractList.add(AbstractList.java:108)
at Cha11.AddingGroups.main(AddingGroups.java:32)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 6 7 8 9 10

“`

11.4 容器打印

“`
public class PrintingContainers {
public static void print(Object o){
System.out.println(o);
}
static Collection fill(Collection collection){
collection.add(“rat”);
collection.add(“cat”);
collection.add(“dog”);
collection.add(“dog”);
return collection;
}
static Map fill(Map

    public class ListIteration {
    public static void main(String[] args){
        List<Integer> list = new ArrayList<>();
        Collections.addAll(list,1,2,3,4,5,6);
        // 构造函数
        ListIterator<Integer> it = list.listIterator();
        // 两个方向移动。
        while(it.hasNext()){
            System.out.println(it.previousIndex()+" "+" "+it.nextIndex()+". "+it.next());
        }
        while(it.hasPrevious()){
            System.out.print(it.previous()+" ");
        }
        System.out.println();
        System.out.println(list);
        //创建一个一开始就指向列表索引为n的元素处的迭代器。
        it = list.listIterator(3);
        while(it.hasNext()){
            it.next();
            it.set((int)(Math.random()*10));
        }
        System.out.println(list);

    }
}
/*  index 0 ,1 ,2 ,3, 4, 5
    value 1 ,2 ,3 ,4 ,5 ,6

    关于迭代器位置,可以看到在最初previous=-1;next=0;
    迭代器真正的位置不是在index上,而是在两个index之间。next(),使的index向前移,返回的是index越过的函数。
    而 it = list.listIterator(n);语句产生的迭代器,位于n-1和n之间。
*/
-1  0. 1
0  1. 2
1  2. 3
2  3. 4
3  4. 5
4  5. 6
6 5 4 3 2 1 
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 0, 3, 0]

11.7 LinkedList

“`
package Cha11;
import java.util.*;
public class LinkedListFeatures {
static void print(Object o){
System.out.println(o);
}
public static void main(String[] args){
LinkedList arr= new LinkedList<>();
Collections.addAll(arr,1,2,3,4,5,6);
print(arr);
print(“arr.getFirst():”+arr.getFirst());
print(“arr.element():”+arr.element());
print(“arr.peek():”+arr.peek());
//getFirst和element完全一样。返回第一个且不移除。列表为空抛出
//noSuchElement异常。peek() 在列表为空时,返回null
print(“arr.remove():”+arr.remove());
print(“arr.removeFirst():”+arr.removeFirst());
print(“arr.poll():”+arr.poll());
print(arr);
//remove和removeFirst一样。移除并返回第一个元素。为空抛出NoSuchElemnt异常。
//poll则返回空。
arr.addFirst(0);
print(“After addFirst”+arr);
arr.offer(7);
print(“After offer()”+arr);
arr.add(8);
print(“After add”+arr);
arr.addLast(9);
print(“After addLast”+arr)
//都是加到最后。;
print(“arr.removeLast():”+arr.removeLast());
//移除并返回最后一个元素。
}
}

[1, 2, 3, 4, 5, 6]
arr.getFirst():1
arr.element():1
arr.peek():1
arr.remove():1
arr.removeFirst():2
arr.poll():3
[4, 5, 6]
After addFirst[0, 4, 5, 6]
After offer()[0, 4, 5, 6, 7]
After add[0, 4, 5, 6, 7, 8]
After addLast[0, 4, 5, 6, 7, 8, 9]
arr.removeLast():9
“`
11.8 stack

    public class StackTest{
        private LinkedList<T> storage = new LinkedList<T>();
        public void push(T v){storage.addFirst(v);}
        public T peek(){return storage.getFirst();}
        public T pop(){return storage.removeFirst();}
        public boolean Empty(){return storage.isEmpty();}
    }

11.9 Set

TreeSet将元素存储在红黑树中,而HashSet使用散列函数。LinkedHashSet也使用散列,它使用了链表来维护元素插入顺序。

public class SortedSetOfInteger {
public static void main(String[] args){
Random rand = new Random(47);
SortedSet<Integer> intset = new TreeSet<>();
for(int i=0; i<10000; i++){
intset.add(rand.nextInt(30));
}
System.out.println(intset);
}
}
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29]

“`
package Cha11;
import java.util.*;
public class SetOperations {
public static void main(String[] args){
Set set1 = new HashSet<>();
Collections.addAll(set1,”A B C D E F”.split(” “));
set1.add(“K”);

    System.out.println("F: "+set1.contains("F"));
    System.out.println("H: "+set1.contains("H"));

    Set<String> set2 = new HashSet<>();
    Collections.addAll(set2,"E,F,D".split(","));

    System.out.println("set2 in set1 :"+set1.containsAll(set2));

    set1.remove("F");
    System.out.println("set1"+set1);

    System.out.println("set2 in set1 :"+set1.containsAll(set2));

    set1.removeAll(set2);
    System.out.println("set2 remove from set1: "+set1);
}

}

F: true
H: false
set2 in set1 :true
set1[A, B, C, D, E, K]
set2 in set1 :false
set2 remove from set1: [A, B, C, K]
“`
11.10 Map

import java.util.*;

public class Statistics {

    public static void main(String[] args){

        Random rand = new Random(47);// 47是seed。伪随机
        Map<Integer, Integer> map = new HashMap<>();
        for(int i=0; i<10000; i++){
            int r =rand.nextInt(20);
            Integer freq = map.get(r);
            // get方法没找到返回null,否则返回对应值。
            map.put(r,freq==null?1:freq+1);
        }
        System.out.println(map);
    }
}
{0=481, 1=502, 2=489, 3=508, 4=481, 5=503, 6=519, 7=471, 8=468, 9=549, 10=513, 11=531, 12=521, 13=506, 14=477, 15=497, 16=533, 17=509, 18=478, 19=464}

containsKey();

containsValue();

set

import java.util.*;
class QueueDemo{
    public static void printQ(Queue queue){
        while(queue.peek()!=null){
            System.out.print(queue.remove()+" ");
        }
        System.out.println();
    }
}
public class PriorityQueueDemo {
    public static void main(String[] args) {
        PriorityQueue<Integer> priorityQueue = new PriorityQueue<>();
        Random rand = new Random(47);
        for(int i=0; i<10; i++){
            priorityQueue.offer(rand.nextInt(i+10));
        }
        QueueDemo.printQ(priorityQueue);

        List<Integer> ints = Arrays.asList(25,22,20,18,14,9,3,1);
        priorityQueue = new PriorityQueue<>(ints);
        QueueDemo.printQ(priorityQueue);
        priorityQueue = new PriorityQueue<Integer>(ints.size(),Collections.reverseOrder());
        // 使用反向paractor
        priorityQueue.addAll(ints);
        QueueDemo.printQ(priorityQueue);

        String fact = "E S E O";
        List<String> strings = Arrays.asList(fact.split(" "));
        PriorityQueue<String> stringPQ = new PriorityQueue<>(strings);
        QueueDemo.printQ(stringPQ);

        stringPQ = new PriorityQueue<String>(strings.size(),Collections.reverseOrder());
        stringPQ.addAll(strings);
        QueueDemo.printQ(stringPQ);

        Set<Character> charSet = new HashSet<Character>();
        for(char c: fact.toCharArray())
            charSet.add(c);
        PriorityQueue<Character> characterPQ = new PriorityQueue<Character>(charSet);
        QueueDemo.printQ(characterPQ);
    }
}
// Integer,String,Character自身带有自然排序。可以和PriorityQueue一起工作
output:
0 1 1 1 1 1 3 5 8 14 
1 3 9 14 18 20 22 25 
25 22 20 18 14 9 3 1 
E E O S 
S O E E 
  E O S 

11.2 Collectoin和Iteractor

Collection是描述所有序列容器的共性的根接口

迭代器

public Iterator<T> iterator(){
    return new Iterator<T>(){
        private int index =0;
        public boolean hasNext(){
            return index<arr.size();
        }
        public T next(){return arr[index++];}
        publiv void remove(){

        }
    }

}

11.13 Foreach和迭代器
Iterator接口。foreach使用。

11.13.1 适配器惯用方法。
package Cha11;
import java.util.*;

public class MultiIterableClass implements Iterable<String>{
    static String[] S;
    MultiIterableClass(String[] s){
        this.S = s;
    }
    @Override
    public Iterator<String> iterator(){
        return new Iterator<String>(){
            private int index = 0;
            public boolean hasNext(){
                return index<S.length;
            }
            public String next(){
                return S[index++];
            }
        };
    }
    /*
        foreach中对象是实现了Iterable接口的对象。
        而实现Iterable接口,要覆盖其 iterator()方法。
        覆盖iterator方法,要覆盖next(),hasNext()方法。
    */
    public Iterable<String> reversed() {
        return new Iterable<String>(){
            @Override
            public Iterator<String> iterator(){
                return new Iterator(){
                    //private
                    int index = S.length-1;
                    @Override
                    public boolean hasNext(){
                        return index > -1;
                    }
                    @Override
                    public String next(){
                        return S[index--];
                    }
                };
            }
        };
    }

    public Iterable<String> randomized(){
        return new Iterable<String>(){
            public Iterator<String> iterator(){
             List<String> shuffled = new ArrayList<>(Arrays.asList(S));
             /*List<String> shuffled = Arrays.asList(S);
             如果直接使用Arrays.asList(S)的结果来乱序,会打乱底层数组的顺序。
             要用 new ArrayList<>(Arrays.asList(S))将其包装起来。
             */
             /* Randomly permute the specified list using the specified source of randomness.
              All permutations occur with equal likelihood assuming that the source of randomness is fair. 
             */
             Collections.shuffle(shuffled, new Random(47));
             return shuffled.iterator();
            }
        };
    }

    public static void main(String[] args) {
        MultiIterableClass mic = new MultiIterableClass(("And that is how we know " +
                "the Earth to be banana-shaped").split(" "));
        for(String s: mic.reversed())
            System.out.print(s+" ");
        System.out.println();
        for(String s:mic.randomized())
            System.out.print(s+" ");
        System.out.println();
        for(String s:mic)
            System.out.print(s+" ");
    }
}

banana-shaped be to Earth the know we how is that And 
is banana-shaped Earth that how the be And we know to 
And that is how we know the Earth to be banana-shaped 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值