THINKING IN JAVA(4TH) 答案免費分享 chapter 11 Holding Your Object

// holding/Ex1.java
// TIJ4 Chapter Holding, Exercise 1, page 394
/* 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 java.util.*;

class Gerbil {
 private int gerbilNumber;
 public Gerbil(int i) {
  gerbilNumber = i;
 }
 public void hop() {
  System.out.println("Gerbil " + gerbilNumber + " hops");
 }
}

public class Ex1 {
 public static void main(String[] args) {
  ArrayList<Gerbil> gerbils = new ArrayList<Gerbil>();
  for(int i = 0; i < 10; i++)
   gerbils.add(new Gerbil(i));
  for(int i = 0; i < 10; i++)
   gerbils.get(i).hop();
  // or, alternatively, using foreach syntax:
  for(Gerbil g : gerbils)
   g.hop();
 }
}

 


// holding/Ex2.java
// TIJ4 Chapter Holding, Exercise 2, page 396
// Modify SimpleCollection.java to use a Set for c.
import java.util.*;

public class Ex2 {
 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 + ", ");
 } 
}

 


// holding/Sequence3.java
// TIJ4 Chapter Holding, Exercise 3, page 396
/* 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 Sequence3 {
 private ArrayList<Object> items = new ArrayList<Object>();
 public void add(Object x) {
  items.add(x);
 }
 private class Sequence3Selector implements Selector {
  private int i = 0;
  public boolean end() {
   return i == items.size();   
  }
  public Object current() {
   return items.get(i);
  }
  public void next() {
   i++;
  } 
 }
 public Selector selector() {
  return new Sequence3Selector();
 }
 public static void main(String[] args) {
  Sequence3 s3 = new Sequence3();
  for(int i = 0; i < 10; i++)
   s3.add(i);
  Selector selector = s3.selector();
  while(!selector.end()) {
   System.out.print(selector.current() + " ");
   selector.next();
  }
  s3.add(10);
  s3.add(11);
  s3.add(12);
  s3.add(13);
  s3.add(13);
  s3.add("good bye");
  while(!selector.end()) {
   System.out.print(selector.current() + " ");
   selector.next();
  }
 }
}

 


// holding/Ex4.java
// TIJ4 Chapter Holding, Exercise 4, page 401
/* 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.*;

class Generator {
 int key = 0;
 public String next() {
  switch(key) {
   default:
   case 0 : key++; return "Snow White";
   case 1 : key++; return "Bashful";
   case 2 : key++; return "Doc";
   case 3 : key++; return "Dopey";
   case 4 : key++; return "Grumpy";
   case 5 : key++; return "Happy";
   case 6 : key++; return "Sleepy";
   case 7 : key = 0; return "Sneezy";   
  }
 }
 public void fillA(String[] a) {
  for(int i = 0; i < a.length; i++)
   a[i] = next();
 }
 public Collection fill(Collection<String> c, int n) {
  for(int i = 0; i < n; i++) c.add(next());
  return c;
 }
}

public class Ex4 {
 public static void main(String[] args) {
  Generator gen = new Generator();  
  String[] a = new String[10];
  gen.fillA(a);
  for(String s : a) System.out.print(s + ", ");
  System.out.println(); 
  System.out.println(gen.fill(new ArrayList<String>(), 10));
  System.out.println(gen.fill(new LinkedList<String>(), 10));
  System.out.println(gen.fill(new HashSet<String>(), 10));
  System.out.println(gen.fill(new LinkedHashSet<String>(), 10));
  System.out.println(gen.fill(new TreeSet<String>(), 10));    
 }
}

 

// holding/Ex5.java
// TIJ4 Chapter Holding, Exercise 5, page 406
/* Modify ListFeatures.java so that it uses Integers (remember
* autoboxing!) instead of Pets, and explain any difference in
* results.
*/
import java.util.*;
import static net.mindview.util.Print.*;

public class Ex5 {
 // method to make a List<Integer> with random values < n:
 public static List<Integer> listOfRandInteger(int length, int n) {
  Random rand = new Random();
  List<Integer> li = new ArrayList<Integer>();
  for(int i = 0; i < length; i++)
   li.add(rand.nextInt(n));   
  return li; 
 }
 public static void main(String[] args) {
  Random rand = new Random();
  List<Integer> li = listOfRandInteger(7, 10);
  print("1: " + li);
  Integer h = new Integer(rand.nextInt(10));
  li.add(h);
  print("2: " + li);
  print("3: " + li.contains(h));
  // removes the first instance equivalent to Integer h:
  li.remove(h);
  print("3.5: " + li);
  Integer p = li.get(2);
  print("4: " + p + " " +  li.indexOf(p));
  Integer cy = new Integer(rand.nextInt(10));
  print("5: " + cy +" " + li.indexOf(cy));
  print("6: " + li.remove(cy));
  print("7: " + li.remove(p));
  print("8: " + li);
  li.add(3, new Integer(rand.nextInt(10)));
  print("9: " + li);
  List<Integer> sub = li.subList(1, 4);
  print("sublist: " + sub);
  print("10: " + li.containsAll(sub));
  // will also sort sub elements within li:
  Collections.sort(sub);
  print("sorted sublist: " + sub);
  print("11: " + li.containsAll(sub));
  print("11.25: " + li);
  // will also shuffle sub elements within li:
  Collections.shuffle(sub, rand);
  print("11.5: " + li);
  print("shuffled sublist: " + sub);
  print("12: " + li.containsAll(sub));
  List<Integer> copy = new ArrayList<Integer>(li);
  print("12.5: " + li);
  sub = Arrays.asList(li.get(1), li.get(4));
  print("sub: " + sub); 
  copy.retainAll(sub);
  print("13: " + copy);
  copy = new ArrayList<Integer>(li);
  copy.remove(2);
  print("14: " + copy);
  copy.removeAll(sub);
  print("15: " + copy);
  if(copy.size() > 1) // to avoid out of bounds exception
   copy.set(1, 8); // autoboxing int -> Integer
  print("16: " + copy);
  if(copy.size() > 2)
   copy.addAll(2, sub);
  print("17: " + copy);
  print("18: " + li.isEmpty());
  li.clear();
  print("19: " + li);
  print("20: " + li.isEmpty());
  li.addAll(listOfRandInteger(4, 10));
  print("21: " + li);
  Object[] o = li.toArray();
  print("22: " + o[3]);
  Integer[] ia = li.toArray(new Integer[0]);
  print("23: " + ia[3]);
 }
}

 


// holding/Ex6.java
// TIJ4 Chapter Holding, Exercise 6, page 406
/* Modify listFeatures.java so that it uses String instead of Pets,
* and explain any difference in results.
*/
import java.util.*;
import static net.mindview.util.Print.*;

public class Ex6 {
 public static void main(String[] args) {
  Random rand = new Random();
  List<String> ls = new ArrayList<String>();
  print("0: " + ls);
  Collections.addAll(ls, "oh", "what", "a", "beautiful", "Manila", "Monday", "morning");
  print("1: " + ls);
  String h = new String("hi");
  ls.add(h);
  print("2: " + ls);
  print("3: " + ls.contains(h));
  // removes the first instance equivalent to String h:
  ls.remove(h);
  print("3.5: " + ls);
  String p = ls.size() > 2 ? ls.get(2) : null;
  print("4: " + p + " " +  ls.indexOf(p));
  String cy = new String("cy");
  print("5: " + cy +" " + ls.indexOf(cy));
  print("6: " + ls.remove(cy));
  print("7: " + ls.remove(p));
  print("8: " + ls);
  if(ls.size() > 3)
   ls.add(3, "wonderful");
  print("9: " + ls);
  if(ls.size() < 4) {
   List<String> s =
      Arrays.asList("let's", "jump", "in", "here");
   ls.addAll(0, s);
  }
  List<String> sub = ls.subList(1, 4);
  print("sublist: " + sub);
  print("10: " + ls.containsAll(sub));
  // will also sort sub elements within ls:
  Collections.sort(sub);
  print("sorted sublist: " + sub);
  print("11: " + ls.containsAll(sub));
  print("11.25: " + ls);
  // will also shuffle sub elements within ls:
  Collections.shuffle(sub, rand);
  print("11.5: " + ls);
  print("shuffled sublist: " + sub);
  print("12: " + ls.containsAll(sub));
  List<String> copy = new ArrayList<String>(ls);
  print("12.5: " + ls);
  if(ls.size() < 5) {
   ls.add("two");
   ls.add("more");
  }
  sub = Arrays.asList(ls.get(1), ls.get(4));
  print("sub: " + sub); 
  copy.retainAll(sub);
  print("13: " + copy);
  copy = new ArrayList<String>(ls);
  copy.remove(2);
  print("14: " + copy);
  copy.removeAll(sub);
  print("15: " + copy);
  if(copy.size() > 1) // to avoid out of bounds exception
   copy.set(1, "excellent");
  print("16: " + copy);
  if(copy.size() > 2)
   copy.addAll(2, sub);
  print("17: " + copy);
  print("18: " + ls.isEmpty());
  ls.clear();
  print("19: " + ls);
  print("20: " + ls.isEmpty());
  ls.addAll(0, sub);
  ls.addAll(2, sub);
  print("21: " + ls);
  Object[] o = ls.toArray();
  print("22: " + o[3]);
  String[] sa = ls.toArray(new String[0]);
  print("23: " + sa[3]);
 }
}

 


// holding/Ex7.java
// TIJ4 Chapter Holding, Exercise 7, page 406
/* 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 Tester {
 public static int counter = 0;
 private int id = counter++;
 public String toString() { return String.valueOf(id); } 
}

public class Ex7 {
 public static void main(String[] args) {  
  Tester[] t = new Tester[10];
  for(int i = 0; i < t.length; i++)
   t[i] = new Tester();
  List<Tester> lt = new ArrayList<Tester>();
  for(Tester x : t) lt.add(x);
  print("list of Tester: " + lt);
  List<Tester> sub = lt.subList(2, 6);
  print("subList: " + sub);
  // produces run time ConcurrentModificationException:
  // lt.removeAll(sub);
  // so, first make copy, remove sub, re-assign lt:
  List<Tester> copy = new ArrayList<Tester>(lt);
  copy.removeAll(sub);
  print("copy: " + copy);
  lt = copy;
  print("list of Tester: " + lt);
 }
}

 


// holding/Ex8.java
// TIJ4 Chapter Holding, Exercise 8, page 409
// Modify Exercise 1 so it uses an Iterator to move through the List while
// calling hop().
import java.util.*;

class Gerbil {
 private int gerbilNumber;
 public Gerbil(int i) {
  gerbilNumber = i;
 }
 public void hop() {
  System.out.println("Gerbil " + gerbilNumber + " hops");
 }
}

public class Ex8 {
 public static void main(String[] args) {
  ArrayList<Gerbil> gerbils = new ArrayList<Gerbil>();
  for(int i = 0; i < 10; i++)
   gerbils.add(new Gerbil(i));
  Iterator<Gerbil> it = gerbils.iterator();
  while(it.hasNext())
   it.next().hop();
 }
}

 


// holding/Sequence9.java
// TIJ4 Chapter Holding, Exercise 9, page 409
// Modify innerclasses/Sequence.java so that Sequence works with an Iterator
// instead of a Selector.
import java.util.*;

public class Sequence9 {
 private ArrayList<Object> items = new ArrayList<Object>();
 public void add(Object x) {
  items.add(x);
 }
 public Iterator iterator() {
  return items.iterator();
 }
 public static void main(String[] args) {
  Sequence9 sequence = new Sequence9();
  for(int i = 0; i < 10; i++)
   sequence.add(Integer.toString(i));
  Iterator it = sequence.iterator();
  while(it.hasNext()) {         System.out.print(it.next() + " ");
  }
 }
}

 


// holding/Rodent10.java
// TIJ4 Chapter Holding, Exercise 10, page 409
/* 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 java.util.*;
import static org.greggordon.tools.Print.*;

class RandomRodentGenerator {
 private Random rand = new Random();
 public Rodent next() {
  switch(rand.nextInt(3)) {
   default:
   case 0: return new Mouse();
   case 1: return new Rat();
   case 2: return new Squirrel();   
  }
 }
}

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

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

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

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

public class Rodent10 {
 private static RandomRodentGenerator gen =
  new RandomRodentGenerator();
 public static void main(String[] args) {
  List<Rodent> rodentList = new ArrayList<Rodent>();
  for(int i = 0; i < 10; i++)
   rodentList.add(gen.next());
  Iterator<Rodent> it = rodentList.iterator();
  while(it.hasNext()) {
   Rodent r = it.next();
   print(r + ": ");
   r.eat();
   r.run();
   r.sleep();
  }
 }
}

 


// holding/Ex11.java
// TIJ4 Chapter Holding, Exercise 11, page 409
/* 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 java.util.*;
import static org.greggordon.tools.Print.*;

public class Ex11 {
 public static void printAny(Collection c) {
  Iterator it = c.iterator();
  while(it.hasNext())
   print(it.next() + " ");
  println();
 }
 public static void main(String[] args) {
  ArrayList<Integer> al =
   new ArrayList<Integer>(Arrays.asList(1, 2, 3));
  LinkedList<Character> ll =
   new LinkedList<Character>(Arrays.asList('a', 'b', 'c')); 
  HashSet<Float> hs =
   new HashSet<Float>(Arrays.asList(1.1f, 2.2f, 3.3f));
  TreeSet<Double> ts =
   new TreeSet<Double>(Arrays.asList(1.11, 2.22, 3.33));
  LinkedHashSet<Integer> lhs =
   new LinkedHashSet<Integer>(Arrays.asList(11, 22, 33));
  printAny(al);
  printAny(ll);
  printAny(hs);
  printAny(ts);
  printAny(lhs);
 }
}

 


// holding/Ex12.java
// TIJ4 Chapter Holding, Exercise 12, page 410
/* 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 java.util.*;
import static org.greggordon.tools.Print.*;

public class Ex12 {
 public static void main(String[] args) {
  List<Integer> li1 =
   new ArrayList<Integer>(Arrays.asList(0, 1, 2, 3, 4));
  List<Integer> li2 =
   new ArrayList<Integer>(Arrays.asList(5, 6, 7, 8, 9));
  ListIterator<Integer> it1 = li1.listIterator();
  ListIterator<Integer> it2 = li2.listIterator();
  println("li1: " + li1);
  println("li2: " + li2);
  // move it1 to end:
  while(it1.hasNext())
   it1.next();
  // now use it2 to re-set li2:
  while(it2.hasNext()) { 
   it2.next();  
   it2.set(it1.previous());
  }
  println("li1: " + li1);
  println("li2: " + li2);
  
 }
}

 


// holding/Ex12a.java
// TIJ4 Chapter Holding, Exercise 12, page 410
/* 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 java.util.*;
import static org.greggordon.tools.Print.*;

public class Ex12a {
 public static void main(String[] args) {
  List<Integer> li1 =
   new ArrayList<Integer>(Arrays.asList(0, 1, 2, 3, 4));
  List<Integer> li2 =
   new ArrayList<Integer>(Arrays.asList(5, 6, 7, 8, 9));
  // start it1 at the end:
  ListIterator<Integer> it1 = li1.listIterator(5);
  ListIterator<Integer> it2 = li2.listIterator();
  println("li1: " + li1);
  println("li2: " + li2);
  // now use it2 to re-set li2
  while(it2.hasNext()) { 
   it2.next();  
   it2.set(it1.previous());
  }
  println("li1: " + li1);
  println("li2: " + li2);
  
 }
}

 


// holding/Controller13.java
// TIJ4 Chapter Holding, Exercise 13, page 412
/* In the innerclasses/GreenhouseController.java example, the class
* Controller uses an ArrayList. Change the code to use a LinkedList
* instead, and use an Iterator to cycle through the set of events.
*/
import java.util.*;

public class Controller13 {
 // A class from java.util to hold Event objects:
 private LinkedList<Event> eventList = new LinkedList<Event>();
 public void addEvent(Event c) { eventList.add(c); }  
 public void run() {  
  LinkedList<Event> eventListCopy =
   new LinkedList<Event>(eventList);
  ListIterator<Event> it
   = eventListCopy.listIterator();
  while(it.hasNext()) { 
   it.next().action();
   it.previous();  
   System.out.println(it.next());  
  }
 } 
}

 


// holding/Ex14.java
// TIJ4 Chapter Holding, Exercise 14, page 412
/* 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.*;

public class Ex14 {
 static void addMiddle(LinkedList<Integer> l, Integer[] ia) {
  
  for(Integer i : ia) {
   ListIterator<Integer> it =
    l.listIterator((l.size())/2);
   it.add(i);
   System.out.println(l);
  }
 }
 public static void main(String[] args) {
  LinkedList<Integer> li = new LinkedList<Integer>();
  Integer[] x = {0, 1, 2, 3, 4, 5, 6, 7};
  Ex14.addMiddle(li, x);
 } 
}

 


// holding/Ex15.java
// TIJ4 Chapter Holding, Exercise 15, page 415
/* 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.*;

public class Ex15 {
 public static void main(String[] args) {
  Stack<Character> sc = new Stack<Character>();
  sc.push('U');
  sc.push('n');
  sc.push('c');
  System.out.print(sc.pop());
  System.out.print(sc.pop());
  System.out.print(sc.pop());
  sc.push('e');
  sc.push('r');
  sc.push('t');
  System.out.print(sc.pop());
  System.out.print(sc.pop());
  System.out.print(sc.pop());
  sc.push('a');
  sc.push('i');
  sc.push('n');
  sc.push('t');
  System.out.print(sc.pop());
  System.out.print(sc.pop());
  System.out.print(sc.pop());
  sc.push(' ');
  System.out.print(sc.pop());
  sc.push('r');
  sc.push('u');
  System.out.print(sc.pop());
  System.out.print(sc.pop());
  sc.push('l');
  sc.push('e');
  sc.push('s');
  System.out.print(sc.pop());
  System.out.print(sc.pop());
  System.out.print(sc.pop());  
 }  
}

 


// holding/Vowels16.java
// TIJ4 Chapter Holding, Exercise 16, page 419
/* 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 net.mindview.util.*;

public class Vowels16 {
 static void vowelCounter(Set<String> st) {
  Set<Character> vowels = new TreeSet<Character>();
  Collections.addAll(vowels,
   'A', 'E', 'I', 'O', 'U', 'a', 'e', 'i', 'o', 'u');
  int allVowels = 0;
  for(String s : st) {
   int count = 0;
   for(Character v : s.toCharArray()) {  
    if(vowels.contains(v)) {
     count++;
     allVowels++;
    }
   }
   System.out.print(s + ": " + count + ", ");  
  }
  System.out.println(); 
  System.out.print("Total vowels: " + allVowels);
 }
 public static void main(String[] args) {
  Set<String> words = new TreeSet<String>(
   new TextFile("SetOperations.java", "\\W+"));
  System.out.println(words);
  System.out.println();
  vowelCounter(words);  
 }  
}

 


// holding/Gerbils17.java
// TIJ4 Chapter Holding, Exercise 17, page 422
/* Take the Gerbil class in Exercise 1 and put it into a Map instead,
* associating each Gerbil's name (e.g. "Fuzzy" or "Spot") as a String (the
* key) for each Gerbil (the value) you put in the table. Get an Iterator for
* the keySet() and use it to move through the Map, looking up the Gerbil for
* each key and printing out the key and telling the Gerbil to hop().
*/
import java.util.*;

class Gerbil {
 private int gerbilNumber;
 public Gerbil(int i) {
  gerbilNumber = i;
 }
 public void hop() {
  System.out.println("gerbil " + gerbilNumber + " hops");
 }
}

public class Gerbils17 {
 public static void main(String[] args) {
  Map<String, Gerbil> gerbils = new HashMap<String, Gerbil>();
  gerbils.put("Fuzzy", new Gerbil(0));
  gerbils.put("Spot", new Gerbil(1));
  gerbils.put("Speedy", new Gerbil(2));
  gerbils.put("Dopey", new Gerbil(3));
  gerbils.put("Sleepy", new Gerbil(4));
  gerbils.put("Happy", new Gerbil(5));
  Iterator<String> it = gerbils.keySet().iterator();
  while(it.hasNext()) {
   String s = it.next();
   System.out.print(s + ": ");
   gerbils.get(s).hop();
  } 
 }
}

 


// holding/Ex18.java
// TIJ4 Chapter Holding, Exercise 18, page 422
/* 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.*;

class Gerbil {
 private int gerbilNumber;
 public Gerbil(int i) {
  gerbilNumber = i;
 }
 public void hop() {
  System.out.println("gerbil " + gerbilNumber + " hops");
 }
}

public class Ex18 {
 public static void main(String[] args) {
  Map<String, Gerbil> gerbils = new HashMap<String, Gerbil>();
  gerbils.put("Fuzzy", new Gerbil(0));
  gerbils.put("Spot", new Gerbil(1));
  gerbils.put("Speedy", new Gerbil(2));
  gerbils.put("Dopey", new Gerbil(3));
  gerbils.put("Sleepy", new Gerbil(4));
  gerbils.put("Happy", new Gerbil(5));
  gerbils.put("Funny", new Gerbil(6));
  gerbils.put("Silly", new Gerbil(7));
  gerbils.put("Goofy", new Gerbil(8));
  gerbils.put("Wowee", new Gerbil(9));
  System.out.println(gerbils);
  System.out.println();
  Set<String> sortedKeys =
   new TreeSet<String>(gerbils.keySet());
  System.out.println(sortedKeys);
  System.out.println();
  Map<String, Gerbil> sortedGerbils =
   new LinkedHashMap<String, Gerbil>();
  for(String s : sortedKeys) {
   System.out.print("Adding " + s + ", ");
   sortedGerbils.put(s, gerbils.get(s));   
  }
  System.out.println();
  System.out.println();
  System.out.println(sortedGerbils);
  System.out.println();
  // or, just:
  Map<String, Gerbil> sortedGerbils2 =
   new TreeMap<String, Gerbil>(gerbils);
  System.out.println(sortedGerbils2);  
 }
}

 


// holding/Ex19.java
// TIJ4 Chapter Holding, Exercise 19, page 422
// Repeat the previous exercise with a HashSet and a LinkedHashSet.
import java.util.*;

class Gerbil {
 private int gerbilNumber;
 public Gerbil(int i) {
  gerbilNumber = i;
 }
 public void hop() {
  System.out.println("gerbil " + gerbilNumber + " hops");
 }
}

public class Ex19 {
 public static void main(String[] args) {
  Map<String, Gerbil> gerbils = new HashMap<String, Gerbil>();
  gerbils.put("Fuzzy", new Gerbil(0));
  gerbils.put("Spot", new Gerbil(1));
  gerbils.put("Speedy", new Gerbil(2));
  gerbils.put("Dopey", new Gerbil(3));
  gerbils.put("Sleepy", new Gerbil(4));
  gerbils.put("Happy", new Gerbil(5));
  gerbils.put("Funny", new Gerbil(6));
  gerbils.put("Silly", new Gerbil(7));
  gerbils.put("Goofy", new Gerbil(8));
  gerbils.put("Wowee", new Gerbil(9));
  System.out.println(gerbils);
  System.out.println();
  Set<String> hashedKeys =
   new HashSet<String>(gerbils.keySet());
  System.out.println("HashSet: " + hashedKeys);
  System.out.println();
  Map<String, Gerbil> hashedGerbils =
   new LinkedHashMap<String, Gerbil>();
  for(String s : hashedKeys) {
   System.out.print("Adding " + s + ", ");   
   hashedGerbils.put(s, gerbils.get(s));
  }
  System.out.println();
  System.out.println();
  System.out.println("From HashSet: " + hashedGerbils);
  
  System.out.println();
  Set<String> linkedHashedKeys =
   new LinkedHashSet<String>(gerbils.keySet());
  System.out.println("LinkedHashSet: " + linkedHashedKeys);
  System.out.println();
  Map<String, Gerbil> linkedHashedGerbils =
   new LinkedHashMap<String, Gerbil>();
  for(String s : linkedHashedKeys) {
   System.out.print("Adding " + s + ", ");   
   linkedHashedGerbils.put(s, gerbils.get(s));
  }
  System.out.println();
  System.out.println();
  System.out.println("From LinkedHashSet: "
   + linkedHashedGerbils);
  }
}

 


// holding/Vowels20.java
// TIJ4 Chapter Holding, Exercise 20, page 422
// Modify Exercise 16 so that you keep a count of the occurence of each vowel.
import java.util.*;
import net.mindview.util.*;

public class Vowels20 {
 static void vowelCounter20(Set<String> st) {  
  Set<Character> vowels = new TreeSet<Character>();
  Collections.addAll(vowels,
   'A', 'E', 'I', 'O', 'U', 'a', 'e', 'i', 'o', 'u');
  int allVowels = 0;
  Map<Character,Integer> vowelMap =
   new TreeMap<Character,Integer>();
  for(String s : st) {
   for(Character v : s.toCharArray()) {  
    if(vowels.contains(v)) {
     Integer count = vowelMap.get(v);
     vowelMap.put(v,
      count == null ? 1 : count + 1);
     allVowels++;
    }
   }
  }
  System.out.println("Vowels: " + vowelMap); 
  System.out.println("Total vowels: " + allVowels);
 }
 public static void main(String[] args) {
  Set<String> words = new TreeSet<String>(
   new TextFile("SetOperations.java", "\\W+"));
  System.out.println(words);
  System.out.println();
  vowelCounter20(words);  
 }  
}

 


// holding/UniqueWords21.java
// TIJ4 Chapter Holding, Exercise 21, page422
/* 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 net.mindview.util.*;

public class UniqueWords21 {
 public static void main(String[] args) {
  List<String> words = new ArrayList<String>(
   new TextFile("SetOperations.java", "\\W+"));
  System.out.println("Words to count: " + words);
  Collections.sort(words, String.CASE_INSENSITIVE_ORDER);
  Map<String,Integer> wordCount =
   new LinkedHashMap<String,Integer>();
  Iterator it = words.iterator();
  int totalWords = 0;
  while(it.hasNext()) {
   String s = (String)it.next();
   if(words.contains(s)) {
    Integer count = wordCount.get(s);
    wordCount.put(s,
     count == null ? 1 : count + 1);
    totalWords++;
   }
  }
  System.out.println();
  System.out.println("Word count: " + wordCount);
  System.out.println();
  System.out.println("Total words: " + totalWords);  
 }  
}

 


// holding/UniqueWords22.java
// TIJ4 Chapter Holding, Exercise 22, page422
/* 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 net.mindview.util.*;

class Word {
 static int totalWords = 0; 
 String s; 
 int count;
 Word(String s, int count) {
  this.s = s;
  this.count = count;
  totalWords++;
 }
 public String toString() { return s + ": " + count; }
}

public class UniqueWords22 {
 public static void main(String[] args) {
  List<String> words = new ArrayList<String>(
   new TextFile("SetOperations.java", "\\W+"));  
  Collections.sort(words, String.CASE_INSENSITIVE_ORDER);
  System.out.println("Words to count, sorted: " + words);
  Set<Word> wordObjects = new HashSet<Word>();
  Iterator it = words.iterator(); 
  while(it.hasNext()) {
   String s = (String)it.next();
   int count = 0;   
   for(int i = 0; i < words.size(); i++) {
    if(s.equals(words.get(i))) count++;
   }
   Word w = new Word(s, count);
   wordObjects.add(w);
  }  
  System.out.println("Word count: " + wordObjects);
  System.out.println("Total words: " + Word.totalWords);  
 }  
}

 


// holding/Statistics23.java
// TIJ4 Chapter Holding, Exercise 23, page 423
/* Starting with Statistics.java, create a program that runs the test repeatedly
* and looks to see if any one number tends to appear more than the others in the
* results.
*/
import java.util.*;


public class Statistics23 {
 private static int getBestInt20(int n) {
  Random rand = new Random();
  Map<Integer, Integer> m =
   new TreeMap<Integer, Integer>();
  for(int i = 0; i < 10000; i++) {
   // Produce a number between 0 and 20:
   int r = rand.nextInt(20);
   Integer freq = m.get(r);
   m.put(r, freq == null ? 1 : freq + 1);
  }
  int max = 0;
  for(int i = 0; i < m.keySet().size(); i++) {
   max = max < m.get(i) ? m.get(i) : max;
  }
  Set<Map.Entry<Integer,Integer>> me = new
   LinkedHashSet<Map.Entry<Integer,Integer>>(m.entrySet());
  int maxKey = 0;
  Iterator<Map.Entry<Integer,Integer>> it = me.iterator();
  while(it.hasNext()) {
   Map.Entry<Integer,Integer> findMax = it.next();
   if(findMax.getValue() == max)
   maxKey = findMax.getKey();
  }
  return maxKey;   
 }
 public static void main(String[] args) {
  Map<Integer,Integer> m20 =  
   new TreeMap<Integer,Integer>();
  for(int i = 0; i < 2000; i++) {
   int x = getBestInt20(10000);
   Integer freq = m20.get(x);
   m20.put(x, freq == null ? 1 : freq + 1);
  }
  System.out.println("Most often picked ints, 0 - 19, in 2000 tests of 10,000 random picks: " + m20);
 }

 


// holding/Ex24.java
// TIJ4 Chapter Holding, Exercise 24, page 423
/* 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.
*/
// see also solution - holding/Ex24b.java
import java.util.*;
import static org.greggordon.tools.Print.*;

public class Ex24{ 
 public static void main(String[] args) {
  Map<String,Integer> m =
   new LinkedHashMap<String,Integer>();
  m.put("ten", 10);
  m.put("nine", 9);
  m.put("eight", 8);
  m.put("seven", 7);
  m.put("six", 6);
  m.put("five", 5);
  m.put("four", 4);
  m.put("three", 3);
  m.put("two", 2);
  m.put("one", 1);
  m.put("zero", 0);
  println("Map to sort: " + m);
  // temporary map to hold entrys:
  Map<String,Integer> mTemp =
   new LinkedHashMap<String,Integer>();
  // use TreeSet to sort the keySet():
  Set<String> ss = new TreeSet<String>(m.keySet());
  // mover sorted keys to temp map:
  Iterator<String> itss = ss.iterator();
  while(itss.hasNext()) {
   String s = (String)itss.next();
   Integer i = m.get(s);
   m.remove(s);
   mTemp.put(s, i);
  }
  // get sorted list of temp keys:
  Set<String> ssTemp =
   new TreeSet<String>(mTemp.keySet());
  // move sorted entrys back to map:
  Iterator<String> itssTemp = ssTemp.iterator();
  while(itssTemp.hasNext()) {
   String s = (String)itssTemp.next();
   Integer i = mTemp.get(s);
   mTemp.remove(s);
   m.put(s, i);
  }
  // done with temp:
  mTemp.clear();
  println("Sorted map: " + m);
 }

 


// holding/Ex24b.java
// TIJ4 Chapter Holding, Exercise 24, page 423
/* 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.
*/
// (see also solution - holding/Ex24.java)
import java.util.*;
import static org.greggordon.tools.Print.*;

public class Ex24b{ 
 public static void main(String[] args) {
  Map<String,Integer> m =
   new LinkedHashMap<String,Integer>();
  m.put("ten", 10);
  m.put("nine", 9);
  m.put("eight", 8);
  m.put("seven", 7);
  m.put("six", 6);
  m.put("five", 5);
  m.put("four", 4);
  m.put("three", 3);
  m.put("two", 2);
  m.put("one", 1);
  m.put("zero", 0);
  println("Map to sort: " + m);
  // temp map to hold entrys:
  Map<String,Integer> mTemp =
   new LinkedHashMap<String,Integer>();
  // to sort the keySet():
  // convert Set to List:
  List<String> ss2List =
   new LinkedList<String>(m.keySet());
  // sort List:
  Collections.sort(ss2List);
  // move entrys in sorted order from m to mTemp:
  Iterator<String> itss2List = ss2List.iterator();
  while(itss2List.hasNext()) {
   String s = (String)itss2List.next();
   Integer i = m.get(s);
   m.remove(s);
   mTemp.put(s, i);
  }
  // get list of temp keys:
  List<String> ssTemp =
   new LinkedList<String>(mTemp.keySet());
  // move sorted entrys back from mTemp to m:
  Iterator<String> itssTemp = ssTemp.iterator();
  while(itssTemp.hasNext()) {
   String s = (String)itssTemp.next();
   Integer i = mTemp.get(s);
   mTemp.remove(s);
   m.put(s, i);
  }
  // done with temp:
  mTemp.clear();
  println("Sorted map: " + m);  
 }

 


// holding/Ex25.java
// TIJ4 Chapter Holding, Exercise 25, page 423
/* 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 net.mindview.util.*;

public class Ex25 {
 public static void main(String[] args) {
  Map<String,ArrayList<Integer>> m =
   new LinkedHashMap<String,ArrayList<Integer>>();
  List<String> words = new LinkedList<String>();
  words.addAll(new TextFile("SetOperations.java", "\\W+"));
  System.out.println("Words in file: " + words);
  Iterator itWords = words.iterator();
  int count = 0;
  while(itWords.hasNext()) {
   String s = (String)itWords.next();
   count++;   
   if(!m.keySet().contains(s)) { 
    ArrayList<Integer> ai =
     new ArrayList<Integer>();  
    ai.add(0, count);
    m.put(s, ai);
   }
   else {
    m.get(s).add(count);
    m.put(s, m.get(s));   
   }
  }
  System.out.println("Map of word locations: " + m);   
 } 
}

 


// holding/Ex26.java
// TIJ4 Chapter Holding, Exercise 26, page 423
/* 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 net.mindview.util.*;

public class Ex26 {
 public static void main(String[] args) {
  Map<String,ArrayList<Integer>> m =
   new LinkedHashMap<String,ArrayList<Integer>>();
  List<String> words = new LinkedList<String>();
  words.addAll(new TextFile("SetOperations.java", "\\W+"));
  System.out.println("Words in file: " + words);
  Iterator itWords = words.iterator();
  int count = 0;
  while(itWords.hasNext()) {
   String s = (String)itWords.next();
   count++;   
   if(!m.keySet().contains(s)) { 
    ArrayList<Integer> ai =
     new ArrayList<Integer>();  
    ai.add(0, count);
    m.put(s, ai);
   }
   else {
    m.get(s).add(count);
    m.put(s, m.get(s));   
   }
  }
  System.out.println();
  System.out.println("Map of word locations: " + m);
  // New Map to hold sorted words, keyed by location:
  Map<Integer,String> replay = new TreeMap<Integer,String>();
  Iterator<Map.Entry<String,ArrayList<Integer>>> it =
   m.entrySet().iterator();
  while(it.hasNext()) {
   Map.Entry<String,ArrayList<Integer>> me = it.next();
   for(int i = 0; i < me.getValue().size(); i++)
    replay.put(me.getValue().get(i),
     me.getKey());
  }
  System.out.println();
  System.out.println("TreeMap of ordered locations, words: " + replay);
  System.out.println();
  // Display words in order as TreeMap values():
  System.out.println("Words in original order: " +
   replay.values());
 } 
}

 


// holding/Queue27.java
// TIJ4 Chapter Holding, Exercise 27, page 424
/* 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.*;

class Command {
 String s;
 Command(String s) { this.s = s; }
 void operation() { System.out.print(s); }
}

class Build { 
 Queue<Command> makeQ() {
  Queue<Command> q = new LinkedList<Command>();
  for(int i = 0; i < 10; i++)
   q.offer(new Command(i + " "));
  return q;
 }
}

public class Queue27 {
 public static void commandEater(Queue<Command> qc) {
  while(qc.peek() != null)
   qc.poll().operation();
 }
 public static void main(String[] args) {
  Build b = new Build();
  commandEater(b.makeQ()); 
 }
}

 


// holding/Ex28.java
// TIJ4 Chapter Holding, Exercise 28, page 427
/* 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.*;

public class Ex28 {
 public static void main(String[] args) {
  Random rand = new Random();
  PriorityQueue<Double> d = new PriorityQueue<Double>();
  for(int i = 0; i < 10; i++)
   d.offer(rand.nextDouble() * i);
  while(d.peek() != null)
   System.out.print(d.poll() + " ");
 }
}

 


// holding/Ex29.java
// TIJ4 Chapter Holding, Exercise 29, page 427
/* 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.*;

class Simple extends Object {}

public class Ex29 {
 public static void main(String[] args) {  
  PriorityQueue<Simple> s = new PriorityQueue<Simple>();
  // OK to add one Simple:
  s.offer(new Simple());
  // but no more allowed; get runtime exception:
  // Simple cannot be cast to Comparable:
  s.offer(new Simple());
 }
}

 


// holding/CollectionSequence30.java
import typeinfo.pets.*;
import java.util.*;

public class CollectionSequence30 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 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 addAll(Collection<? extends Pet> 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 boolean add(Pet p) {
  throw new UnsupportedOperationException();
 }
 public Object[] toArray() {
  return pets;
 }
 public <T> T[] toArray(T[] a) {
            throw new UnsupportedOperationException();
       }
 public static void main(String[] args) {
  CollectionSequence30 c = new CollectionSequence30();
  InterfaceVsIterator.display(c);
  InterfaceVsIterator.display(c.iterator());
 }
}

 


// holding/shape/RcdandomShapeGenerator31.java
// TIJ4 Chapter Holding, Exercise 31, page 434
/* 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.
*/
/* Solution includes, in same package:
* public class Shape {
* public void draw() {}
* public void erase() {}
* public void amend() { System.out.println("Shape.amend()"); }
* @Override public String toString() { return "Shape"; }
* }
* public class Circle extends Shape {
* @Override public void draw() { print("Circle.draw()"); }
* @Override public void erase() { print("Circle.erase()"); }
* @Override public void amend() { print("Circle.amend()"); }
* @Override public String toString() { return "Circle"; }
* }
* public class Square extends Shape {
* @Override public void draw() { print("Square.draw()"); }
* @Override public void erase() { print("Square.erase()"); }
* @Override public void amend() { print("Square.amend()"); }
* @Override public String toString() { return "Square"; }
* }
* public class Triangle extends Shape {
* @Override public void draw() { print("Triangle.draw()"); }
* @Override public void erase() { print("Triangle.erase()"); }
* @Override public void amend() { print("Triangle.amend()"); }
* @Override public String toString() { return "Triangle"; }
* }
*/
package holding.shape;
import java.util.*;

public class RandomShapeGenerator31 implements Iterable<Shape> {
 private Random rand = new Random();
 public Shape make() {  
  switch(rand.nextInt(3)) {
   default:
   case 0: return new Circle();
   case 1: return new Square();
   case 2: return new Triangle();
  }
 }
 private Shape[] shapes;
 RandomShapeGenerator31(int n) {
  shapes = new Shape[n];
  for(int i = 0; i < n; i++)
   shapes[i] = make();
    
 }
 public Iterator<Shape> iterator() {
  return new Iterator<Shape>() {
   private int index = 0;
   public boolean hasNext() {
    return index < shapes.length;
   }
   public Shape next() {
    return shapes[index++];
   }
   public void remove() {
    throw new UnsupportedOperationException();
   }   
  };
 }
 public static void main(String[] args) {
  RandomShapeGenerator31 rsg = new RandomShapeGenerator31(20);
  for(Shape s : rsg)
   System.out.println(s);
 }
}

 


// holding/NonCollectionSequence32.java
// TIJ4 Chapter Holding, Exercise 32, page 437
/* 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 typeinfo.pets.*;
import java.util.*;
import static org.greggordon.tools.Print.*;

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

public class NonCollectionSequence32
 extends PetSequence implements Iterable {
 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() {
    throw new UnsupportedOperationException();
   }
  };
 }
 public Iterable<Pet> reversed() {
  return new Iterable<Pet>() {
   public Iterator<Pet> iterator() {
    return new Iterator<Pet>() {
     int current = pets.length - 1;
     public boolean hasNext() {
      return current > -1;
     }
     public Pet next() {
      return pets[current--];
     }
     public void remove() {
      throw new
      UnsupportedOperationException();
     }
    };
   }
  };
 }
 public Iterable<Pet> randomized() {
  return new Iterable<Pet>() {
   public Iterator<Pet> iterator() {
    List<Pet> shuffled = new
       ArrayList<Pet>(Arrays.asList(pets));
    Collections.shuffle(shuffled, new Random());
    return shuffled.iterator();
   }
  };
 }
 public static void main(String[] args) {
  NonCollectionSequence32 nc = new NonCollectionSequence32();
  print("pets: ");
  for(Pet p : nc.pets)
   print(p + " ");
  println();
  print("reversed: ");
  for(Pet p : nc.reversed())
   print(p + " ");
  println();
  print("randomized: ");
  for(Pet p : nc.randomized())
   print(p + " ");
 }
}

你可能感兴趣的:(think in java)