1. 程式人生 > >Java-Java程式設計思想第四版 第十一章 練習

Java-Java程式設計思想第四版 第十一章 練習

練習1:

/* Create a new class called Gerbil with an int gerbilNumber that's 
* initialized in the constructor. Give it a method called hop() that displays
* which gerbil number that is, and that it's hopping. Create an ArrayList and 
* add Gerbil objects to the List. Now use the get() method to move through
* the List and call hop() for each Gerbil.
*/
import static net.mindview.util.Print.*;
import java.util.*;
class Gerbil{
    private static int counter=0;
    private final int gerbilNumber=counter++;
    int hop(){return gerbilNumber;}
}
public class Ja11_1_1{
    public static void main(String[] args){
        ArrayList<Gerbil> ger=new ArrayList<Gerbil>();
        for(int i=0;i<3;i++)ger.add(new Gerbil());
        for(Gerbil g:ger){print(g.hop());}
        for(int i=0;i<3;i++)print(ger.get(i).hop());
    }
}

練習2:

// Modify SimpleCollection.java to use a Set for c.
import java.util.*;

public class Ja11_2_2 {
  public static void main(String[] args) {
    Set<Integer> c = new HashSet<Integer>();
    for(int i = 0; i < 10; i++)
      c.add(i); // Autoboxing
    for(Integer i : c)
      System.out.print(i + ", ");
  }
} /* Output:
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
*///:~

練習3:

/* Modify innerclasses/Sequence.java so that you can add any number
* of elements to it.
*/
import java.util.*;
interface Selector {
  boolean end();
  Object current();
  void next();
}	

public class Ja11_2_3 {
  private ArrayList<Object> items=new ArrayList<Object>();
  //private int next = 0;
  //public Ja11_2_3(int size) { items = new Object[size]; }
  public void add(Object x) {
    //if(next < items.length)
      items.add(x);
  }
  private class SequenceSelector implements Selector {
    private int i = 0;
    public boolean end() { return i == items.size(); }
    public Object current() { return items.get(i); }
    public void next() { if(i < items.size()) i++; }
  }
  public Selector selector() {
    return new SequenceSelector();
  }	
  public static void main(String[] args) {
    Ja11_2_3 sequence = new Ja11_2_3(/*10*/);
    for(int i = 0; i < 10; i++)
      sequence.add(Integer.toString(i));
    Selector selector = sequence.selector();
    while(!selector.end()) {
      System.out.print(selector.current() + " ");
      selector.next();
    }
  }
} /* Output:
0 1 2 3 4 5 6 7 8 9
*///:~

練習4:

/* Create a generator class that produces character names (as String objects)
* from your favorite movie (you can use Snow White or Star Wars as a
* fallback) each time you call next(), and loops around to the beginning of
* the character list when it runs out of names. Use this generator to fill
* an array, an ArrayList, a LinkedList, a HashSet, a LinkedHashSet, and a
* TreeSet, then print each container.
*/
import java.util.*;
import static net.mindview.util.Print.*;
class Produce{
    private int key=0;
    private String st=null;
    String next(){
        switch(key){
            case 0:key++;st="Snow";break;
            case 1:key++;st="Game";break;
            case 2:key++;st="Love";break;
            case 3:key++;st="Worlun";break;
            case 4:key=0;st="Die";break;
        }
        return st;
    }
}
public class Ja11_4_4{
    public static void main(String[] args){
        String[] st=new String[7];
        ArrayList<String> al=new ArrayList<String>();
        LinkedList<String> ll=new LinkedList<String>();
        HashSet<String> hs=new HashSet<String>();
        LinkedHashSet<String> ls=new LinkedHashSet<String>();
        TreeSet<String> ts=new TreeSet<String>();
        String temp=null;
        Produce pd=new Produce();
        for(int i=0;i<7;i++){
            temp=pd.next();
            st[i]=temp;
            al.add(temp);ll.add(temp);hs.add(temp);ls.add(temp);
            ts.add(temp);
        }
        for(String s:st){printnb(s+" ");}
        print(al);
        print(ll);
        print(hs);
        print(ls);
        print(ts);
    }
}

練習5:

/* Modify ListFeatures.java so that it uses Integers (remember 
* autoboxing!) instead of Pets, and explain any difference in
* results.
*/
import typeinfo.pets.*;
import java.util.*;
import static net.mindview.util.Print.*;

public class Ja11_5_5 {
    public static List<Integer> randInteger(int i){
        List<Integer> in=new ArrayList<Integer>();

        Random rand=new Random();
        for(int j=0;j<i;j++)in.add(rand.nextInt(100));
        return in;
    }
  public static void main(String[] args) {
    Random rand = new Random(47);
    List<Integer> pets = randInteger(7);
    print("1: " + pets);
    Integer h = new Integer(4);
    pets.add(h); // Automatically resizes
    print("2: " + pets);
    print("3: " + pets.contains(h));
    pets.remove(h); // Remove by object
    Integer p = pets.get(2);
    print("4: " +  p + " " + pets.indexOf(p));
    Integer cymric = new Integer(6);
    print("5: " + pets.indexOf(cymric));
    print("6: " + pets.remove(cymric));
    // Must be the exact object:
    print("7: " + pets.remove(p));
    print("8: " + pets);
    pets.add(3, new Integer(9)); // Insert at an index
    print("9: " + pets);
    List<Integer> sub = pets.subList(1, 4);
    print("subList: " + sub);
    print("10: " + pets.containsAll(sub));
    Collections.sort(sub); // In-place sort
    print("sorted subList: " + sub);
    // Order is not important in containsAll():
    print("11: " + pets.containsAll(sub));
    Collections.shuffle(sub, rand); // Mix it up
    print("shuffled subList: " + sub);
    print("12: " + pets.containsAll(sub));
    List<Integer> copy = new ArrayList<Integer>(pets);
    sub = Arrays.asList(pets.get(1), pets.get(4));
    print("sub: " + sub);
    copy.retainAll(sub);
    print("13: " + copy);
    copy = new ArrayList<Integer>(pets); // Get a fresh copy
    copy.remove(2); // Remove by index
    print("14: " + copy);
    copy.removeAll(sub); // Only removes exact objects
    print("15: " + copy);
    copy.set(1, new Integer(87)); // Replace an element
    print("16: " + copy);
    copy.addAll(2, sub); // Insert a list in the middle
    print("17: " + copy);
    print("18: " + pets.isEmpty());
    pets.clear(); // Remove all elements
    print("19: " + pets);
    print("20: " + pets.isEmpty());
    pets.addAll(randInteger(4));
    print("21: " + pets);
    Object[] o = pets.toArray();
    print("22: " + o[3]);
    Integer[] pa = pets.toArray(new Integer[0]);
    print("23: " + pa[3]/*.id()*/);
  }
} /* Output:1: [86, 88, 9, 47, 12, 99, 32]
2: [86, 88, 9, 47, 12, 99, 32, 4]
3: true
4: 9 2
5: -1
6: false
7: true
8: [86, 88, 47, 12, 99, 32]
9: [86, 88, 47, 9, 12, 99, 32]
subList: [88, 47, 9]
10: true
sorted subList: [9, 47, 88]
11: true
shuffled subList: [47, 9, 88]
12: true
sub: [47, 12]
13: [47, 12]
14: [86, 47, 88, 12, 99, 32]
15: [86, 88, 99, 32]
16: [86, 87, 99, 32]
17: [86, 87, 47, 12, 99, 32]
18: false
19: []
20: true
21: [64, 94, 38, 39]
22: 39
23: 39*/

練習7:

/* Create a class, then make an initialized array of objects of your class
* Fill a List from your array. Create a subset of your List by using 
* subList(), then remove this subset from your List.
*/
import java.util.*;
import static net.mindview.util.Print.*;

class A{
    private int i;
    A(int i){this.i=i;}
    public String toString(){return i+"";}
}
public class Ja11_5_7{
    public static void main(String[] args){
        A a[]={new A(5),new A(6),new A(7),new A(8),new A(9)};
        List<A> la=new ArrayList<A>(Arrays.asList(a));
        List<A> sub=la.subList(1,4);
        print(sub);
        Collections.shuffle(sub,new Random(8));
        print(la);
        la.removeAll(sub);
        print(la);
    }
}
/*Output:
[6, 7, 8]
[5, 6, 8, 7, 9]
[5, 9]
 * */

練習8:

// Modify Exercise 1 so it uses an Iterator to move through the List while 
// calling hop().
import static net.mindview.util.Print.*;
import java.util.*;
class Gerbil{
    private static int counter=0;
    private final int gerbilNumber=counter++;
    int hop(){return gerbilNumber;}
}
public class Ja11_6_8{
    public static void main(String[] args){
        ArrayList<Gerbil> ger=new ArrayList<Gerbil>();
        for(int i=0;i<3;i++)ger.add(new Gerbil());
        Iterator<Gerbil> it=ger.iterator();
        Gerbil g;
        while(it.hasNext()){g=it.next();print(g.hop());}
        //for(Gerbil g:ger){print(g.hop());}
        //for(int i=0;i<3;i++)print(ger.get(i).hop());
    }
}

練習9:

// Modify innerclasses/Sequence.java so that Sequence works with an Iterator
// instead of a Selector.
import static net.mindview.util.Print.*;
import java.util.*;

interface Selector {
  boolean end();
  Object current();
  void next();
}	

public class Ja11_6_9 {
  /*private Object[] items;
  private int next = 0;
  public Sequence(int size) { items = new Object[size]; }
  public void add(Object x) {
    if(next < items.length)
      items[next++] = x;
  }
  private class SequenceSelector implements Selector {
    private int i = 0;
    public boolean end() { return i == items.length; }
    public Object current() { return items[i]; }
    public void next() { if(i < items.length) i++; }
  }
  public Selector selector() {
    return new SequenceSelector();
  }*/	
    static class Sequence{
        private int i;
        Sequence(int i){this.i=i;}
        public String toString(){return Integer.toString(i);}
    }
  public static void main(String[] args) {
    List<Sequence> sequence = new ArrayList<Sequence>();
    for(int i = 0; i < 10; i++)
      sequence.add(new Sequence(i));
    Iterator<Sequence> it=sequence.iterator();
    //Selector selector = sequence.selector();
    /*while(!selector.end()) {
      System.out.print(selector.current() + " ");
      selector.next();
    }*/
    Sequence se;
    while(it.hasNext()){se=it.next();print(se);}
  }
} /* Output:
 */

練習10:

/* Change Exercise 9 in the Polymorphism chapter to use an ArrayList to
* hold the Rodents and an Iterator to move through the sequence of 
* Rodents.
*/
//import static org.greggordon.tools.Print.*;
import static net.mindview.util.Print.*;
import java.util.*;

class Rodent {
	private String name = "Rodent";
	protected void eat() { print("Rodent.eat()"); }
	protected void run() { print("Rodent.run()"); }
	protected void sleep() { print("Rodent.sleep()"); }
	public String toString() { return name; }
}

class Mouse extends Rodent {
	private String name = "Mouse";
	protected void eat() { print("Mouse.eat()"); }
	protected void run() { print("Mouse.run()"); }
	protected void sleep() { print("Mouse.sleep()"); }
	public String toString() { return name; }
}

class Rat extends Rodent {
	private String name = "Rat";
	protected void eat() { print("Rat.eat()"); }
	protected void run() { print("Rat.run()"); }
	protected void sleep() { print("Rat.sleep()"); }
	public String toString() { return name; }
}

class Squirrel extends Rodent {
	private String name = "Squirrel";
	protected void eat() { print("Squirrel.eat()"); }
	protected void run() { print("Squirrel.run()"); }
	protected void sleep() { print("Squirrel.sleep()"); }
	public String toString() { return name; }
}

public class Ja11_6_10 {
	//private static RandomRodentGenerator gen = new RandomRodentGenerator();
	public static void main(String[] args) {
		Rodent[] rodents ={new Squirrel(),new Rat(),new Mouse()};
        ArrayList<Rodent> rd=new ArrayList<Rodent>(Arrays.asList(rodents));
        Iterator<Rodent> it=rd.iterator();
        Rodent r;
        while(it.hasNext()){
            r=it.next();
			//r = gen.next();
			print(r + ": ");
			r.eat();
			r.run();
			r.sleep();			
		}		
	}
}

練習11:

/* Write a method that uses an Iterator to step through a Collection and
* print the toString() of each object in the container. Fill all the different
* types of Collections with objects and apply your method to each container.
*/
import static net.mindview.util.Print.*;
import java.util.*;

class A{
    private int i;
    A(int i){this.i=i;}
    public String toString(){return Integer.toString(i);}
}
public class Ja11_6_11{
    public static void display(Iterator<A> it){
        while(it.hasNext()){print(it.next());}
    }
    public static void main(String[] args){
        ArrayList<A> al=new ArrayList<A>();
        A a[]={new A(3),new A(6),new A(8)};
        Collections.addAll(al,a);
        LinkedList<A> ll=new LinkedList<A>(al);
        HashSet<A> hs=new HashSet<A>(al);
        Collection<A> cl=new ArrayList<A>(al);
        display(al.iterator());
        display(ll.iterator());
        display(hs.iterator());
        display(cl.iterator());

    }
}

練習12: 

/* Create and populate a List<Integer>. Create a second List<Integer> of the
* same size as the first, and use ListIterator to read elements of the first
* List and insert them into the second in reverse order. (You may want to 
* explore a number of different ways to solve this problem.)
*/
import static net.mindview.util.Print.*;
import java.util.*;

public class Ja11_6_12{
    public static void main(String[] args){
        List<Integer> li=new ArrayList<Integer>();
        Integer ii[]={new Integer(4),new Integer(9),new Integer(6)};
        Collections.addAll(li,ii);
        ListIterator<Integer> lit=li.listIterator();
        while(lit.hasNext()){lit.next();}
        while(lit.hasPrevious()){
            print(lit.previous());
        }
    }
}

練習14:

/* Create an empty LlinkedList<Integer>. Using a ListIterator, add Integers
* to the list by always inserting them in the middle of the list.
*/
import java.util.*;

import static net.mindview.util.Print.*;
public class Ja11_7_14{
    static LinkedList<Integer> addMiddle(LinkedList<Integer> ll,Integer[] ai){
        
        for(Integer i:ai){
            ListIterator<Integer> lit=ll.listIterator(ll.size()/2);
            lit.add(i);
        }
        return ll;
    }
    public static void main(String[] args){
        LinkedList<Integer> ll=new LinkedList<Integer>();
        Integer[] ai={4,5,7,3,2};
        print(addMiddle(ll,ai));
    }
}

練習15:

/* Stacks are often used to evaluate expressions in programming 
* languages. Using net.mindview.util.Stack, evaluate the following
* expression, where '+' means "push the following letter onto the 
* stack," and '-' means "pop the top of the stack and print it":
* "+U+n+c---+e+r+t---+a+i+n+t+y---+-+r+u--+l+e+s---"
*/
import net.mindview.util.Stack;
import static net.mindview.util.Print.*;
import java.util.*;
public class Ja11_8_15{
    public static void main(String[] args){
        Stack<Character> stack=new Stack<Character>();
        char ss[]="+U+n+c---+e+r+t---+a+i+n+t+y---+-+r+u--+l+e+s---".toCharArray();
        Character sss[]=new Character[30];
        for(int i=0;i<30;i++){sss[i]=ss[i];}
        LinkedList<Character> ll=new LinkedList<Character>();
        Collections.addAll(ll,sss);
        ListIterator<Character> it=ll.listIterator();
        Character s;
        while(it.hasNext()){
            s=it.next();
            if(s=='+'){s=it.next();stack.push(s);}
            else if(s=='-'){print(stack.pop());}
        }
        print(ll);
    }
}
/*Output:
c
n
U
t
r
e
y
t
[+, U, +, n, +, c, -, -, -, +, e, +, r, +, t, -, -, -, +, a, +, i, +, n, +, t, +
, y, -, -]*/


練習16:

/* Create a Set of the vowels. Working from UniqueWords.java, count and
* display the number of vowels in each input word, and also display the total
* number of vowels in the input file.
*/
import java.util.*;
import static net.mindview.util.Print.*;
import net.mindview.util.TextFile;
import net.mindview.util.*;
public class Ja11_9_16{
    public static void main(String[] args){
        Set<String> st=new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
        st.addAll(new TextFile("Ja11_8_15.java","\\W+"));
        Set<Character> yuan=new TreeSet<Character>();
        Collections.addAll(yuan,'a','o','e','i','u','A','O','E','I','U');
        int i=0;
        for(String s:st){
            int count=0;
            for(Character c:s.toCharArray()){
                if(yuan.contains(c)){count++;i++;}
            }
            print(s+" "+count);
        }
        print(i);
    }
}

PS: char值可以被賦值給Character,但char[]陣列不能賦給Character[]。

練習17:

/* Modify the solution to Exercise 19 from the Interfaces chapter to use
* anonymous inner classes. 
* (Exercise 19, Interfaces: Create a framework using Factory Methods
* that performs both coin tossing and dice tossing.
*/
import java.util.*;
import static net.mindview.util.Print.*;

class Gerbil{
    private static int counter=0;
    private final int gerbilNumber=counter++;
    private String name;
    Gerbil(String name){this.name=name;}
    public String toString(){return "Gerbil: "+name;}
    int hop(){return gerbilNumber;}
}
public class Ja11_9_17{
    public static void main(String[] args){
        Map<String,Gerbil> mg=new HashMap<String,Gerbil>();
        mg.put("a",new Gerbil("a"));//存入鍵和值
        mg.put("b",new Gerbil("b"));
        mg.put("c",new Gerbil("c"));
        Set<String> sg=mg.keySet();//提取出鍵交給Set
        Iterator<String> it=sg.iterator();//使用Set的iterator()方法

        while(it.hasNext()){
            String name=it.next(); //鍵
            print(name+": "+mg.get(name)+": "+mg.get(name).hop());//列印鍵+名字+hop()方法;因為是HashMap,所以序號是無序的
        }
    }
}
/*
b: Gerbil: b: 1
c: Gerbil: c: 2
a: Gerbil: a: 0
*/

練習18:

/* Fill a HashMap with key-value pairs. Print the results to show ordering
* by hash code. Extract the pairs, sort by key, and place the result into a 
* LinkedHashMap. Show that the insertion order is maintained. 
*/
import java.util.*;
import static net.mindview.util.Print.*;

class Gerbil{
    private static int counter=0;
    private final int gerbilNumber=counter++;
    private String name;
    Gerbil(String name){this.name=name;}
    public String toString(){return "Gerbil: "+name;}
    int hop(){return gerbilNumber;}
}
public class Ja11_9_18{
    public static void main(String[] args){
        Map<String,Gerbil> mg=new HashMap<String,Gerbil>();
        mg.put("a",new Gerbil("a"));
        mg.put("b",new Gerbil("b"));
        mg.put("c",new Gerbil("c"));
        print(mg+" ");
        TreeSet<String> sg=new TreeSet<String>(mg.keySet());//Set型別的轉換方式

        LinkedHashMap<String,Gerbil> lhm=new LinkedHashMap<String,Gerbil>();
        for(String s:sg){
            lhm.put(s,mg.get(s));
        }
        print(lhm);
     }
}
/*{b=Gerbil: b, c=Gerbil: c, a=Gerbil: a}
{a=Gerbil: a, b=Gerbil: b, c=Gerbil: c}*/

練習19:

// Repeat the previous exercise with a HashSet and a LinkedHashSet.
import java.util.*;
import static net.mindview.util.Print.*;

class Gerbil{
    private static int counter=0;
    private final int gerbilNumber=counter++;
    private String name;
    Gerbil(String name){this.name=name;}
    public String toString(){return "Gerbil: "+name;}
    int hop(){return gerbilNumber;}
}
public class Ja11_10_19{
    public static void main(String[] args){
        Map<String,Gerbil> mg=new HashMap<String,Gerbil>();
        mg.put("a",new Gerbil("a"));
        mg.put("b",new Gerbil("b"));
        mg.put("c",new Gerbil("c"));
        print(mg+" ");
        HashSet<String> hs=new HashSet<String>(mg.keySet());
//        TreeSet<String> sg=new TreeSet<String>(hs);
        LinkedHashSet<String> lhs=new LinkedHashSet<String>(mg.keySet());
//        TreeSet<String> sg2=new TreeSet<String>(lhs);

        LinkedHashMap<String,Gerbil> lhm=new LinkedHashMap<String,Gerbil>();
        for(String s:hs){
            lhm.put(s,mg.get(s));
        }
        print(lhm);
        for(String s:lhs){
            lhm.put(s,mg.get(s));
        }
        print(lhm);
     }
}
/*{b=Gerbil: b, c=Gerbil: c, a=Gerbil: a}
{b=Gerbil: b, c=Gerbil: c, a=Gerbil: a}
{b=Gerbil: b, c=Gerbil: c, a=Gerbil: a}*/

練習20:

// Modify Exercise 16 so that you keep a count of the occurence of each vowel. 

import java.util.*;
import static net.mindview.util.Print.*;
import net.mindview.util.TextFile;
import net.mindview.util.*;
public class Ja11_10_20{
    public static void main(String[] args){
        Set<String> st=new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
        st.addAll(new TextFile("Ja11_8_15.java","\\W+"));
        Set<Character> yuan=new TreeSet<Character>();
        Collections.addAll(yuan,'a','o','e','i','u','A','O','E','I','U');

        //For No.20:
        Integer i=0;
        Map<Character,Integer> map=new HashMap<Character,Integer>();
        for(String s:st){
            Integer count=0;
            for(Character c:s.toCharArray()){
                if(yuan.contains(c)){
                    count++;i++;
                    Integer freq=map.get(c);
                    map.put(c,freq==null?1:freq+1);
                }
            }
            //print(s+" "+count);
        }
        //print(i);
        print(map);
    }
}
/*{U=2, u=8, e=29, A=2, a=26, o=19, O=1, I=1, i=25}*/

練習21:

/* Using a Map<String,Integer>, follow the form of UniqueWords.java to create a
* program that counts the occurrence of words in a file. Sort the results using 
* Collections.sort() with a second argument of String.CASE_INSENSITIVE_ORDER (to
* produce an alphabetic sort), and display the result.
*/
import java.util.*;
import static net.mindview.util.Print.*;
import net.mindview.util.TextFile;
//import net.mindview.util.*;
public class Ja11_10_21{
    public static void main(String[] args){
        List<String> ctext=new ArrayList<String>(new TextFile("Ja11_10_20.java","\\W+"));
        Collections.sort(ctext,String.CASE_INSENSITIVE_ORDER);//Collections only available for class List, can't suit class Set.

        Map<String,Integer> map=new LinkedHashMap<String,Integer>();
        for(String c:ctext){
            Integer in=map.get(c);
            map.put(c,in==null?1:in+1);
        }
        print(map);
    }
}
/*{0=2, 1=4, 16=1, 19=1, 2=2, 20=1, 25=1, 26=1, 29=1, 8=1, a=3, A=2, addAll=2, 
args=1, c=4, CASE_INSENSITIVE_ORDER=1, Character=5, class=1, Collections=1, 
contains=1, count=4, 
e=2, E=1, each=1, Exercise=1, For=1, for=2, freq=3, get=1, HashMap=1, 
i=5, I=2, if=1, import=4, Integer=5, Ja11_10_20=1, Ja11_8_15=1, java=2, keep=1,
main=1, Map=1, map=4, mindview=3, Modify=1, net=3, new=4, No=1, null=1, o=2,
O=2, occurence=1, of=2, Print=1, print=3, public=2, put=1, s=3, Set=2, so=1, 
st=3, static=2, String=5, TextFile=2, that=1, the=1, toCharArray=1, TreeSet=2,
u=2, U=2, util=4, void=1, vowel=1, W=1, you=1, yuan=3}*/

練習22:

/* Modify the previous exercise so that it uses a class containing a String and
* a count field to store each different word, and a Set of these objects to 
* maintain the list of words.
*/
import java.util.*;
import static net.mindview.util.Print.*;
import net.mindview.util.TextFile;

class MapLike{
    private String name;
    private  int number=1;
    MapLike(String name){this.name=name;}
    public String toString(){return name;}
    void addNumber(){number++;}
    int getNumber(){return number;}
    String getName(){return name;}
}
public class Ja11_10_22{
    public static void main(String[] args){
        List<String> ls=new ArrayList<String>(new TextFile("Ja11_10_20.java","\\W+"));
        Collections.sort(ls,String.CASE_INSENSITIVE_ORDER);

        Set<MapLike> mapLike=new LinkedHashSet<MapLike>();
        MapLike m,m2;
        for(String s:ls){
            //if(mapLike.contains(s))  //contains()方法用不起來
            boolean flag=false;//用了一個flag做標誌
            Iterator<MapLike> it=mapLike.iterator();//取Set中元素只能用Iterator
            while(it.hasNext()){
                m=it.next();
                if(m.getName().equals(s)) {m.addNumber();flag=true;}//只能用equals(),不能用==
            }
            /*else*/if(!flag) mapLike.add(new MapLike(s));
        }
        Iterator<MapLike> it=mapLike.iterator();//要想重置Iterator,需要重新定義
        while(it.hasNext()){
            m2=it.next();
            print(m2.getName()+" "+m2.getNumber());
        }
    }
}
/*0 2
1 4
16 1
19 1
2 2
20 1
25 1
26 1
29 1
8 1
a 3
A 2
addAll 2
args 1
c 4
CASE_INSENSITIVE_ORDER 1
Character 5
class 1
Collections 1
contains 1
count 4
e 2
E 1
each 1
Exercise 1
For 1
for 2
freq 3
get 1
HashMap 1
i 5
I 2
if 1
import 4
Integer 5
Ja11_10_20 1
Ja11_8_15 1
java 2
keep 1
main 1
Map 1
map 4
mindview 3
Modify 1
net 3
new 4
No 1
null 1
o 2
O 2
occurence 1
of 2
Print 1
print 3
public 2
put 1
s 3
Set 2
so 1
st 3
static 2
String 5
TextFile 2
that 1
the 1
toCharArray 1
TreeSet 2
u 2
U 2
util 4
void 1
vowel 1
W 1
you 1
yuan 3*/

練習24:

/* Fill a LinkedHashMap with String keys and objects of your choice.
* Now extract the pairs, sort them based on the keys, and reinsert
* them into the Map.
*/
import java.util.*;
import static net.mindview.util.Print.*;
class MapLike{
    private String name;
    private  int number=1;
    MapLike(String name){this.name=name;}
    public String toString(){return name;}
    void addNumber(){number++;}
    int getNumber(){return number;}
    String getName(){return name;}
}
public class Ja11_10_24{
    public static void main(String[] args){
        Map<String,MapLike> m1=new LinkedHashMap<String,MapLike>();
        m1.put("m",new MapLike("m"));
        m1.put("a",new MapLike("a"));
        m1.put("x",new MapLike("x"));
        m1.put("d",new MapLike("d"));
        Set<String> s1=m1.keySet();
        Set<String> s2=new TreeSet<String>(s1);
        Iterator<String> its2=s2.iterator();
        Map<String,MapLike> m2=new LinkedHashMap<String,MapLike>();
        while(its2.hasNext()){
            String s=its2.next();
            m2.put(s,m1.get(s));
            m1.remove(s);
        }
        m1=m2;
        print(m1);

    }
}
/*{a=a, d=d, m=m, x=x}*/

練習25:

/* Create a Map<String, ArrayList<Integer>>. Use net.mindview.TextFile
* to open a text file and read it in a word at a time (use "\\W+\" as
* the second argument to the TextFile constructor). Count the words as
* you read them in, and for each word in the file, record in the
* ArrayList<Integer> the word count associated with that word - that is,
* in effect, the location in the file where that word was found.
*/

import java.util.*;
import static net.mindview.util.Print.*;
import net.mindview.util.TextFile;
public class Ja11_10_25{
    public static void main(String[] args){
        Map<String,ArrayList<Integer>> m1=new LinkedHashMap<String,ArrayList<Integer>>();
        List<String> ll=new ArrayList<String>(new TextFile("Ja11_10_24.java","\\W+"));
        Iterator<String> it=ll.iterator();
        int count=0;
        while(it.hasNext()){
            String s=it.next();
            count++;
            ArrayList<Integer> al;
            al=m1.get(s);
            if(al==null)al=new ArrayList<Integer>();
            al.add(count);
            m1.put(s,al);
        }
        print(m1);
    }
}
/*{Fill=[1], a=[2, 93, 96, 154, 155], LinkedHashMap=[3, 82, 131], with=[4], String
=[5, 40, 47, 53, 64, 75, 78, 83, 110, 115, 119, 122, 127, 132, 137], keys=[6, 21
], and=[7, 22], objects=[8], of=[9], your=[10], choice=[11], Now=[12], extract=[
13], the=[14, 20, 26], pairs=[15], sort=[16], them=[17, 24], based=[18], on=[19]
, reinsert=[23], into=[25], Map=[27, 77, 126], import=[28, 31], java=[29], util=
[30, 35], static=[32, 72], net=[33], mindview=[34], Print=[36], class=[37, 69],
MapLike=[38, 46, 79, 84, 89, 95, 101, 107, 128, 133], private=[39, 42], name=[41
, 48, 50, 51, 56, 67], int=[43, 60], number=[44, 59, 63], 1=[45], this=[49], pub
lic=[52, 68, 71], toString=[54], return=[55, 62, 66], void=[57, 73], addNumber=[
58], getNumber=[61], getName=[65], Ja11_10_24=[70], main=[74], args=[76], m1=[80
, 85, 91, 97, 103, 112, 144, 147, 150, 153], new=[81, 88, 94, 100, 106, 117, 130
], put=[86, 92, 98, 104, 142], m=[87, 90, 158, 159], x=[99, 102, 160, 161], d=[1
05, 108, 156, 157], Set=[109, 114], s1=[111, 120], keySet=[113], s2=[116, 124],
TreeSet=[118], Iterator=[121], its2=[123, 135, 139], iterator=[125], m2=[129, 14
1, 151], while=[134], hasNext=[136], s=[138, 143, 146, 149], next=[140], get=[14
5], remove=[148], print=[152]}*/

練習26:

/* Take the resulting Map from the previous exercise and re-create the 
* order of the words as they appeared in the original file.
*/
import java.util.*;
import static net.mindview.util.Print.*;
import java.util.*;
import static net.mindview.util.Print.*;
import net.mindview.util.TextFile;
public class Ja11_10_26{
    public static void main(String[] args){
        Map<String,ArrayList<Integer>> m1=new LinkedHashMap<String,ArrayList<Integer>>();
        List<String> ll=new ArrayList<String>(new TextFile("Ja11_10_24.java"," "));
        Iterator<String> it=ll.iterator();
        int count=0;
        while(it.hasNext()){
            String s=it.next();
            count++;
            ArrayList<Integer> al;
            al=m1.get(s);
            if(al==null)al=new ArrayList<Integer>();
            al.add(count);
            m1.put(s,al);
        }
        Map<Integer,String> m2=new LinkedHashMap<Integer,String>();
        

        Set<String> set=m1.keySet();
        Iterator<String> it2=set.iterator();
        while(it2.hasNext()){
            String s=it2.next();
            ArrayList<Integer> al=m1.get(s);
            Iterator<Integer> itAl=al.iterator();
            while(itAl.hasNext())
            {
                int i=itAl.next();
                m2.put(i,s);
            }
        }
        for(int j=0;j<m2.size();j++){
            System.out.print(m2.get(j)+" ");
        }

    }
}

練習27:

/* Write a class called Command that contains a String and has a method operation()
* that displays the String. Write a second class with a method that fills a Queue
* with Command objects and returns it. Pass the filled Queue to a method in a third
* class that consumes the objects in the Queue and calls their operation() methods.
*/
import java.util.*;
import static net.mindview.util.Print.*;
class Command{
    private String ss="ji";
    String operation(){return ss;}
}
class B{
    Queue coco(Queue Q){
        Command co=new Command();
        Q.offer(co);
        return Q;
    }
}
public class Ja11_11_27{
    public static void main(String[] args){
        B b=new B();
        Queue<Command> q=new LinkedList<Command>();
        q=b.coco(q);
        print(q.remove().operation());
    }
}

練習28:

/* Fill a PriorityQueue (using offer()) with Double values created using 
* java.util.Random, then remove the elements using poll() and display them.
*/
import java.util.Random;
import java.util.*;
import static net.mindview.util.Print.*;
public class Ja11_11_28{
    public static void main(String[] args){
       Random rand=new Random(47);
       PriorityQueue<Double> q=new PriorityQueue<Double>();
       for(int i=0;i<5;i++)q.offer(rand.nextDouble());
       print(q);
    }
}

練習29:

/* Fill a PriorityQueue (using offer()) with Double values created using 
* java.util.Random, then remove the elements using poll() and display them.
*/
import java.util.*;
import static net.mindview.util.Print.*;
class A{}
public class Ja11_11_29{
    public static void main(String[] args){
        A a=new A();
        PriorityQueue<A> pQ=new PriorityQueue<A>();
        pQ.offer(a);
        A b=new A();
        pQ.offer(b);
    }
}

練習30:

//: holding/CollectionSequence.java
import typeinfo.pets.*;
import java.util.*;
class InterfaceVsIterator {
  public static void display(Iterator<Pet> it) {
    while(it.hasNext()) {
      Pet p = it.next();
      System.out.print(p.id() + ":" + p + " ");
    }
    System.out.println();
  }
  public static void display(Collection<Pet> pets) {
    for(Pet p : pets)
      System.out.print(p.id() + ":" + p + " ");
    System.out.println();
  }	
  
}
public class Ja11_12_30
    implements Collection<Pet> {
  private Pet[] pets = Pets.createArray(8);
  public int size() { return pets.length; }
  public Iterator<Pet> iterator() {
    return new Iterator<Pet>() {
      private int index = 0;
      public boolean hasNext() {
        return index < pets.length;
      }
      public Pet next() { return pets[index++]; }
      public void remove() { // Not implemented
        throw new UnsupportedOperationException();
      }
    };
  }
  public boolean add(Pet p){throw new UnsupportedOperationException();}
  public boolean addAll(Collection<? extends Pet> c){throw new UnsupportedOperationException();} 
  public void clear() { 
		if(this.size() != 0)
		for(Pet p : pets)
			p = null;
	}
  public boolean retainAll(Collection<?> c) { 
		throw new UnsupportedOperationException();
	}
  public boolean removeAll(Collection<?> c) { 
		throw new UnsupportedOperationException();
	}
  public boolean contains(Object o) {	
		throw new UnsupportedOperationException();
	}
  public boolean isEmpty() {	
		return (this.size() == 0) ? true : false;
	}
  public boolean containsAll(Collection<?> c) { 
		throw new UnsupportedOperationException();
	}
  
  public boolean remove(Object o) { 
		throw new UnsupportedOperationException();
	}
  public Object[] toArray() {
		return pets;
	}
  public <T> T[] toArray(T[] a) {
            throw new UnsupportedOperationException();
       }

  public static void main(String[] args) {
    Ja11_12_30 c = new Ja11_12_30();
    InterfaceVsIterator.display(c);
    InterfaceVsIterator.display(c.iterator());
  }
} /* Output:
*///:~

練習31:

/* Modify polymorphism/shape/RandomShapeGenerator.java to make it
* Iterable. You'll need to add a constructor that takes the number of
* elements that you want the iterator to produce before stopping. Verify
* that it works.
*/
import java.util.*;
import static net.mindview.util.Print.*;

class RandomShapeGenerator implements Iterable<Shape>{
  private Random rand = new Random(47);
  Shape[] shape;
  RandomShapeGenerator(int count){
      shape=new Shape[count];
      for(int i=0;i<shape.length;i++)shape[i]=next();
  }
  public Shape next() {
    switch(rand.nextInt(3)) {
      default:
      case 0: return new Circle();
      case 1: return new Square();
      case 2: return new Triangle();
    }
  }
  public Iterator<Shape> iterator(){
    return new Iterator<Shape>(){
        private int index=-1;
        public boolean hasNext(){return index<shape.length;}
        public Shape next(){index++;return shape[index];}
        public void remove(){throw new UnsupportedOperationException();}
    };
  
  }  
}
public class Ja11_13_31{
    public static void main(String[] args){
        RandomShapeGenerator rs=new RandomShapeGenerator(4);
        Iterator<Shape> it=rs.iterator();
        while(it.hasNext()){
            print(it.next());
            it.remove();
        }
    }
}

練習32:

/* Following the example of MultiIterableClass, add reversed() and randomized() 
* methods to NonCollectionSequence.java, as well as making  NonCollectionSequence.java
* implement Iterable and show that all the approaches * work in foreach statements.
*/
import java.util.*;
import static net.mindview.util.Print.*;
import typeinfo.pets.*;

class PetSequence {
  protected Pet[] pets = Pets.createArray(8);
}

public class Ja11_13_32 extends PetSequence /*implements Iterable<Pet>*/ {
    public Iterable<Pet> iterator(){
        return new Iterable<Pet>(){
          public Iterator<Pet> iterator() {
            return new Iterator<Pet>() {
              private int index = 0;
              public boolean hasNext() {
                return index<pets.length;
              }
              public Pet next() { return pets[index++]; }
              public void remove() { // Not implemented
                throw new UnsupportedOperationException();
              }
            };
          }
        };
    }
    public Iterable<Pet> reversed(){
        return new Iterable<Pet>(){
          public Iterator<Pet> iterator() {
            return new Iterator<Pet>() {
              private int index = pets.length-1;
              public boolean hasNext() {
                return index>-1;
              }
              public Pet next() { return pets[index--]; }
              public void remove() { // Not implemented
                throw new UnsupportedOperationException();
              }
            };
          }
        };
    }
    public Iterable<Pet> randomized(){
        return new Iterable<Pet>(){
            public Iterator<Pet> iterator(){
                Random rand=new Random(6);
                List<Pet> lp=new ArrayList<Pet>(Arrays.asList(pets));
                Collections.shuffle(lp,rand);
                return lp.iterator();
             }
        };
    }
  public static void  display(Iterable<Pet> itb){
    for(Pet i:itb){print(i);}
  }
  public static void main(String[] args) {
    Ja11_13_32 nc = new Ja11_13_32();
    display(nc.randomized());
    print();
    display(nc.iterator());
        print();
    display(nc.reversed());
  }
}
/*Pug
Rat
Manx
Pug
Mutt
Cymric
Manx
Cymric

Rat
Manx
Cymric
Mutt
Pug
Cymric
Pug
Manx

Manx
Pug
Cymric
Pug
Mutt
Cymric
Manx
Rat*/