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 + " ");
 }
}

Thinking in Java(中文版)带有课后题答案完整版 同人类任何语言一样,Java为我们提供了一种表达思想的方式。如操作得当,同其他方式相比,随着问题变得愈大和愈复杂,这种表达方式的方便性和灵活性会显露无遗。 不可将Java简单想象成一系列特性的集合;如孤立地看,有些特性是没有任何意义的。只有在考虑“设计”、而非考虑简单的编码时,才可真正体会到Java的强大。为了按这种方式理解Java,首先必须掌握它与编程的一些基本概念。本书讨论了编程问题、它们为何会成为问题以及Java用以解决它们的方法。所以,我对每一章的解释都建立在如何用语言解决一种特定类型的问题基础上。按这种方式,我希望引导您一步一步地进入Java的世界,使其最终成为您最自然的一种语言。 贯穿本书,我试图在您的大脑里建立一个模型——或者说一个“知识结构”。这样可加深对语言的理解。若遇到难解之处,应学会把它填入这个模型的对应地方,然后自行演绎出答案。事实上,学习任何语言时,脑海里有一个现成的知识结构往往会起到事半功倍的效果。 立即下载

相关推荐

Thinking in java 练习题答案

Annotated Solution Guide for TIJ4.pdf。Thinking in java 练习题答案。

《Thinking In Java》---第四版 练习题答案

百度网盘下载:https://pan.baidu.com/share/link?shareid=2111776725&uk=2869544179&app=zd 在线查看:http://greggordon.org/java/tij4/solutions.htm Java学习交流QQ群:603654340我们一起学Java! 转载于:https://www.cnblogs.co...

weixin_30254435的博客 508

thinking in java 原版及其练习答案

本书赢得了全球程序员的广泛赞誉,即使是最晦涩的概念,在Bruce Eckel具有亲和力的文字和小而直接的编程示例面前也会化解于无形。从Java的基础语法到最高级特性(深入的面向对象概念、多线程、自动项目构建、单元测试和调试等),本书都能逐步指导你轻松掌握。最新版本的哦

think in java 第四版

think in java 第四版课后答案 第九章 6 think in java 第四版课后答案 第九章 7 think in java 第四版课后答案 第九章 8 think in java 第四版课后答案 第九章 9 mysql 像Oracle一样 解决方案 Java内存泄漏分析与解决方案 09java10大技术 spring事务属性 你可能不知道的10...

weixin_34221036的博客 230

Thinking in Java 中文第四版+习题答案

写在前面的话 引言 1. 前提 2. Java的学习 3. 目标 4. 联机文档 5. 章节 6. 练习 7. 多媒体 8. 源代码 9. 编码样式 10. Java版本 11. 课程和培训 12. 错误 13. 封面设计 14. 致谢 第1章 对象入门 1.1 抽象的进步 1.2 对象的接口 1.3 实现方案的隐藏 1.4 方案的重复使用 1.5 继承:重新使用接口 1.5.1 改善基础类 1.5.2 等价和类似关系 1.6 多形对象的互换使用 1.6.1 动态绑定 1.6.2 抽象的基础类和接口 1.7 对象的创建和存在时间 1.7.1 集合与继承器 1.7.2 单根结构 1.7.3 集合库与方便使用集合 1.7.4 清除时的困境:由谁负责清除? 1.8 违例控制:解决错误 1.9 多线程 1.10 永久性 1.11 Java和因特网 1.11.1 什么是Web? 1.11.2 客户端编程 1.11.3 服务器端编程 1.11.4 一个独立的领域:应用程序 1.12 分析和设计 1.12.1 不要迷失 1.12.2 阶段0:拟出一个计划 1.12.3 阶段1:要制作什么? 1.12.4 阶段2:开始构建? 1.12.5 阶段3:正式创建 1.12.6 阶段4:校订 1.12.7 计划的回报 1.13 Java还是C++? 第2章 一切都是对象 2.1 用句柄操纵对象 2.2 必须创建所有对象 2.2.1 保存在什么地方 2.2.2 特殊情况:主类型 2.2.3 Java中的数组 2.3 绝对不要清除对象 2.3.1 作用域 2.3.2 对象的作用域 2.4 新建数据类型:类 2.4.1 字段和方法 2.5 方法、自变量和返回值 2.5.1 自变量列表 2.6 构建Java程序 2.6.1 名字的可见性 2.6.2 使用其他组件 2.6.3 static关键字 2.7 我们的第一个Java程序 2.8 注释和嵌入文档 2.8.1 注释文档 2.8.2 具体语法 2.8.3 嵌入 2.8.4 @see:引用其他类 2.8.5 类文档标记 2.8.6 变量文档标记 2.8.7 方法文档标记 2.8.8 文档示例 2.9 编码样式 2.10 总结 2.11 练习 第3章 控制程序流程 3.1 使用Java运算符 3.1.1 优先级 3.1.2 赋值 3.1.3 算术运算符 3.1.4 自动递增和递减 3.1.5 关系运算符 3.1.6 逻辑运算符 3.1.7 按位运算符 3.1.8 移位运算符 3.1.9 三元if-else运算符 3.1.10 逗号运算符 3.1.11 字串运算符 3.1.12 运算符常规操作规则 3.1.13 造型运算符 3.1.14 Java没有“sizeof” 3.1.15 复习计算顺序 3.1.16 运算符总结 3.2 执行控制 3.2.1 真和假 3.2.3 反复 3.2.6 中断和继续 3.2.7 切换 3.3 总结 3.4 练习 第4章 初始化和清除 4.1 由构建器保证初始化 4.2 方法过载 4.2.1 区分过载方法 4.2.2 主类型的过载 4.2.3 返回值过载 4.2.4 默认构建器 4.2.5 this关键字 4.3 清除:收尾和垃圾收集 4.3.1 finalize()用途何在 4.3.2 必须执行清除 4.4 成员初始化 4.4.1 规定初始化 4.4.2 构建器初始化 4.5 数组初始化 4.5.1 多维数组 4.6 总结 4.7 练习 第5章 隐藏实施过程 5.1 包:库单元 5.1.1 创建独一无二的包名 5.1.2 自定义工具库 5.1.3 利用导入改变行为 5.1.4 包的停用 5.2 Java访问指示符 5.2.1 “友好的” 5.2.2 public:接口访问 5.2.3 private:不能接触 5.2.4 protected:“友好的一种” 5.3 接口与实现 5.4 类访问 5.5 总结 5.6 练习 第6章 类再生 6.1 合成的语法 6.2 继承的语法 6.2.1 初始化基础类 6.3 合成与继承的结合 6.3.1 确保正确的清除 6.3.2 名字的隐藏 6.4 到底选择合成还是继承 6.6 递增开发 6.7 上溯造型 6.7.1 何谓“上溯造型”? 6.8 final关键字 6.8.1 final数据 6.8.2 final方法 6.8.3 final类 6.8.4 final的注意事项 6.9 初始化和类装载 6.9.1 继承初始化 6.10 总结 6.11 练习 第7章 多形性 7.1 上溯造型 7.1.1 为什么要上溯造型 7.2 深入理解 7.2.1 方法调用的绑定 7.2.2 产生正确的行为 7.2.3 扩展性 7.3 覆盖与过载 7.4 抽象类和

深入解析Cuk、Zeta和Sepic拓扑:非隔离型开关电源的设计奥秘

本文深入解析了Cuk、Zeta和Sepic三种非隔离型开关电源拓扑的设计奥秘。它们均能实现升降压转换,但特性各异:Cuk拓扑输出反向电压,输入输出纹波极低;Sepic拓扑输出同极性电压,应用广泛;Zeta拓扑输出纹波小,适合精密供电。文章详细对比了其电路结构、工作原理、核心公式及选型指南,帮助工程师根据输入电压范围、输出极性及纹波要求,灵活选择最合适的拓扑方案。

weixin_28308325的博客 477

THINKING IN JAVA(4TH) 答案免費分享 chapter 10 Inner Classes

// innerclasses/Outer1.java// TIJ4 Chapter Innerclasses, Exercise 1, page 347/* Write a class named Outer that contains an inner class named Innet. * Add a method to Outer that returns an object of ty...

286

深入解析ROS 2 Control:从硬件抽象到实时控制的机器人框架实践

本文深入解析了ROS 2 Control机器人控制框架,阐述了其如何通过硬件抽象、控制器管理和实时性保障,解决机器人开发中硬件与软件紧耦合的痛点。文章详细剖析了其三层核心架构与数据流,并通过C++/Python代码示例演示了硬件接口的实现,最后提供了URDF配置、启动文件编写指南以及动态控制器管理、实时优化等高级应用与实战避坑技巧。

mqtt6iot的博客 620

Thinking in java第四版--第2章习题答案--关键字、变量、声明、赋值、初始化、类型转换

Java两大核心机制:     Java虚拟机(Java Virtual Machine):JVM是一个虚拟的计算机,具有指令集并使用不同的存储区域。负责执行指令,管理数据、内存、寄存器。Java虚拟机机制屏蔽了底层运行平台的差别,实现了“一次编译,到处运行”。     垃圾收集机制(Garbage Collection): 垃圾回收:将不再使用的内存空间进行回收。  在 C/C+

xiaowanggedege的专栏 2368

【MNE脑电信号处理学习笔记1】数据的读取、可视化、剪裁、滤波和保存

MNE之读取原始数据、可视化数据、剪裁数据、滤波和保存 Reading & visualizaing raw data, cropping, filtering, and saving 原视频教程:Pybrain: M/EEG analysis with MNE Python 原笔记和材料:pybrain_mne 本文根据视频和个人理解对原笔记进行细微修改。 Import the few packages we’ll need import matplotlib import pathlib i

小白家 4216

从电商平台到微信私域:构建合规跳转链路的技术实现

在互联网营销与用户增长领域,链接跳转是连接不同平台、引导用户流量的基础技术。其核心原理是通过服务器端路由与参数解析,实现用户请求的接收、处理与重定向。这项技术的价值在于能够突破平台间的生态壁垒,实现流量的合规、可控迁移,尤其适用于跨平台营销、私域沉淀等场景。在实际应用中,常需处理微信环境限制、参数传递与动态内容生成等挑战。本文聚焦于电商平台(如淘宝)到微信生态的跳转需求,详细阐述了如何利用Node.js、Express框架及二维码生成技术,构建一个包含环境检测、参数传递与动态落地页的完整跳转系统,以解决微信

weixin_33889665的博客 323

Thinking in java 4th Edition 习题答案全

http://greggordon.org/java/tij4/solutions.htm 向这位外国大哥致敬了!

Bop to the top! 1万+

在没有信用卡的情况下怎么申请谷歌云(Google Cloud)?

这笔额度足够用来跑一台云服务器、部署小型网站,甚至可以尝试 AI、机器学习等项目。但问题来了——想要拿到这 300 美元,你必须先通过支付方式验证。默认选项就是绑定一张国际信用卡(Visa、MasterCard 之类),然而不少人没有信用卡,或者信用卡无法支持国际支付,结果就卡在注册第一步。很多人会疑惑:既然是送额度,为什么还要绑卡?原因其实很简单:谷歌需要确认你是真实用户,而不是批量注册薅羊毛;通过支付验证,后续如果你用完 300 美元额度,可以直接进行付费使用;

m0_74824483的博客 5654

《Thinking in Java 4th》习题答案

《Thinking in Java 4th》习题答案,如题。 这个包里有16个文件夹。

kencool 406

ABAP代码检查(Code Review)

1、SLIN 扩展程序检查 也可通过(SE38工具栏->检查-扩展程序检查) 进入 2、ATC 检查 通过<SE38菜单栏-检查-ABAP测试主控室> 或事物代码SCI, 支持自定义检查变式 SCI可以配置检查变式满足特殊需求,配置对象集用于批量检查 3、通过ABAP测试主控室实现统一管理,定期检查作业和监控功能(事务代码ATC) 参考 SLIN...

u012232542的博客 6068

微店构造订单页面,自动化抢票

之前的文章写过微店抢票如何构造订单页面分析,这篇文章在之前的基础上,进行抢票。

猫敷雪 7202

THINKING IN JAVA(4TH) 答案免費分享 chapter 12 Error Handing With Exceptions

// exceptions/Ex1.java// TIJ4 Chapter Exceptions, Exercise 1, page 452/* Create a class with a main(0 that throws an object of class Exception* inside a try block. Give the constructor for Exception...

348

2023年高教社杯 | 2023年高教社杯全国大学生数学建模思路(A题思路、C题思路)

2023年高教社杯 | 2023年高教社杯全国大学生数学建模思路(A题思路、C题思路)

前程算法屋的博客 624

Thinking in java 4th Edition 习题答案链接

非常感谢http://greggordon.org/java/tij4/solutions.htm

xiaojuliet的专栏 1843

VC中sqlite的使用

在VC中对sqlite的使用,实现数据库大批数据的快速插入,读取数据库中的数据在ListCtrl中显示

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

Thinking in Java 4th(Java编程思想第四版)文档、源码、习题答案

  Thinking in Java 4th 中、英文两版pdf文档,书中源码及课后习题答案。链接:https://pan.baidu.com/s/1BKJdtgJ3s-_rN1OB4rpLTQ 密码:2zc4   http://greggordon.org/java/tij4/solutions.htm 亦为Thinking in Java 4th英文版的课后习题答案。     使用Eclips...

weixin_33915554的博客 724

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

Thinking in Java(4th edition) 书上代码和练习题答案

书上代码 https://github.com/BruceEckel/TIJ4-code 练习题答案 http://greggordon.org/java/tij4/solutions.htm

willwaywang6 1794

THINKING IN JAVA 第四版 及源码和习题答案

这个版本挺不错的 打出来看着很有感觉 比机械出的那本舒服多了

做真正的自己 1143

Thinking In Java 4th Edition

[size=medium][color=indigo]“上帝赋予人类说话的能力,而言语又创造了思想,思想是人类对宇宙的量度。”                   ——摘自《Prometheus Unbound》,Shelley • 人类……极其受那些已经成为社会表达工具的特定语言的支配。想像一下,如果一个人可以不使用语言就能够从本质上适应现实世界,语言仅仅是解决具体的交流和反映问题时...

supercssupercs的博客 171

Thinking in java 4th Edition 读书笔记-Concurrency(1)

1.Without concurrency, the only way to produce a responsive user interface is for all tasks to periodically check for user input. By creating a separate thread of execution to respond to user input, e

Bop to the top! 824

【资源】Thinking in java 4th edition 英文版 高清晰pdf+源代码+练习题答案

  在下面留下您的Email地址,我会把这个资源尽早给您发过去的。  分享快乐!共同进步!   http://blog.youkuaiyun.com/gunner086/

gunner086的专栏 2044
上一篇: THINKING IN JAVA(4TH) 答案免費分享 chapter 10 Inner Classes
下一篇: THINKING IN JAVA(4TH) 答案免費分享 chapter 12 Error Handing With Exceptions
ccfangle
博客等级 码龄20年 1粉丝 75原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值