读书人

Thinking in java 11章 课后练习题

发布时间: 2012-12-26 14:39:29 作者: rapoo

Thinking in java 11章 课后习题

第11章 持有对象

练习1:

/*** 创建一个新类Gerbil(沙鼠),包含int gerbilNumber,* 在构造器中初始化它。添加一个方法hop(),用以打印沙鼠的号码以及他* 正在跳跃的信息。创建一个ArrayList,并向其中添加一串Gerbil对象。* 使用get()遍历List,并且对每个Gerbil调用hop()*/import java.util.ArrayList;public class Gerbil {private static int counter;private int gerbilNumber;private String hopInfo;public Gerbil(){}public Gerbil(String hl){gerbilNumber = ++counter;hopInfo = hl;}void hop(){System.out.println("沙鼠的号码为:" + gerbilNumber + "跳跃的信息为:" + hopInfo);}public static void main(String[] args) {ArrayList<Gerbil> gerbils = new ArrayList<Gerbil>();gerbils.add(new Gerbil("25"));gerbils.add(new Gerbil("26"));gerbils.add(new Gerbil("24"));gerbils.add(new Gerbil("25"));for(Gerbil g: gerbils){g.hop();}}}

??练习2:

/*** 修改SimpleCollection.java,* 使用Set来表示c。*/import java.util.HashSet;import java.util.Set;public class Exam_11_2 {public static void main(String[] args) {Set<Integer> c = new HashSet<Integer>();for(int i = 0;i <10;i++)c.add(i);for(Integer i : c)System.out.print(i + ", ");}}

?练习4

//创建一个生成器类,它可以在每次调用其next()方法时,产生你由你最喜欢的电影//(你可以使用Snow White或Star Wars)的字符构成的名字(作为String对象)。对字符列表中的电影名//用完之后,循环到这个字符列表的开始处。使用这个生成器来填充数组、ArrayList、LinkedList、HashSet//LinkedHashSet和TreeSet,然后打印每一个容器。import java.util.ArrayList;import java.util.Collection;import java.util.HashSet;import java.util.LinkedHashSet;import java.util.LinkedList;import java.util.TreeSet;class Generator {int key = 0;public String next() {switch (key) {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";default:case 7:key++;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.println(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));}}

?练习5

//修改ListFeatures.java,让它使用Integer(记住自动包装机制!)而不是Pet,并解释在结果上有何不同。import java.util.ArrayList;import java.util.Arrays;import java.util.Collections;import java.util.List;import java.util.Random;public class Ex5 {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);System.out.println("1: " + li);Integer h= new Integer(rand.nextInt(10));li.add(h);System.out.println("2: " + li);System.out.println("3: " + li.contains(h));//removes the first instance equivalent to Integer h:li.remove(h);System.out.println("3.5 " + li);Integer p = li.get(2);System.out.println("4: " + p + " " + li.indexOf(p));Integer cy = new Integer(rand.nextInt(10));System.out.println("5: " + cy + " " + li.indexOf(cy));System.out.println("6: " + li.remove(cy));System.out.println("7: " + li.remove(p));System.out.println("8: " + li);li.add(3, new Integer(rand.nextInt(10)));System.out.println("9: " + li);List<Integer> sub = li.subList(1, 4);System.out.println("sublist: " + sub);System.out.println("10: " + li.containsAll(sub));Collections.sort(sub);System.out.println("sorted sublist: " + sub);System.out.println("11: " + li.containsAll(sub));System.out.println("11.25: " + li);Collections.shuffle(sub,rand);System.out.println("11.5: " + li);System.out.println("shuffled sublist: " + sub);System.out.println("12: " + li.containsAll(sub));List<Integer> copy = new ArrayList<Integer>(li);System.out.println("12.5 " + li);sub = Arrays.asList(li.get(1),li.get(4));System.out.println("sub: " + sub);copy.retainAll(sub);System.out.println("13: " + copy);copy = new ArrayList<Integer>(li);copy.remove(2);System.out.println("14: " +copy);copy.removeAll(sub);System.out.println("15: " +copy);if(copy.size() > 1)copy.set(1,8);System.out.println("16: " +copy);if(copy.size() > 2)copy.addAll(2, sub);System.out.println("17: " + copy);System.out.println("18: " + li.isEmpty());li.clear();System.out.println("19: " + li);System.out.println("20: " + li.isEmpty());li.addAll(listofRandInteger(4,10));System.out.println("21: " + li);Object[] o = li.toArray();System.out.println("22: " + o[3]);Integer[] ia = li.toArray(new Integer[0]);System.out.println("23: " + ia[3]);}}

?练习8

import java.util.ArrayList;import java.util.Iterator;//修改练习1,以便调用hop()时使用Iterator遍历Listclass Gerbil2 {private static int counter;private int gerbilNumber;public Gerbil2(){gerbilNumber = ++counter;}public Gerbil2(String hl){gerbilNumber = ++counter;}void hop(){System.out.println("沙鼠的号码为:" + gerbilNumber );}}public class Ex8 {public static void main(String[] args) {ArrayList<Gerbil2> gerbils = new ArrayList<Gerbil2>();for(int i=0;i<10;i++){gerbils.add(new Gerbil2());}Iterator<Gerbil2> it = gerbils.iterator();while(it.hasNext())it.next().hop();    }}

?练习11

//写一个方法,使用Iterator遍历Collection,并打印容器中每个对象的toString().//填充各种类型的Collection然后对其使用此方法import java.util.ArrayList;import java.util.Arrays;import java.util.Collection;import java.util.HashSet;import java.util.Iterator;import java.util.LinkedHashSet;import java.util.LinkedList;import java.util.TreeSet;public class Ex11 {    public static void printAny(Collection c){Iterator it = c.iterator();while(it.hasNext())System.out.print(it.next()+ " ");System.out.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);    }}

?练习12

import java.util.ArrayList;import java.util.Arrays;import java.util.List;import java.util.ListIterator;//创建并组装一个List<Integer>,然后创建第二个具有相同尺寸的List<Integer>,并使用ListIterator读取//第一个List中的元素,然后再将它们以反序插入到第二个列表中(你可能想探索该问题的各种解决之道)public class Ex12 {public static void main(String[] args) {List<Integer> list1 = new ArrayList<Integer>(Arrays.asList(0,1,2,3,4));List<Integer> list2 = new ArrayList<Integer>(Arrays.asList(5,6,7,8,9));ListIterator<Integer> it1 = list1.listIterator();ListIterator<Integer> it2 = list2.listIterator();for(Integer x : list2)System.out.print(x+" ");System.out.println();while(it1.hasNext()){it1.next();}while(it2.hasNext()){it2.next();it2.set(it1.previous());}for(Integer x : list2)System.out.print(x+" ");}}

?练习14

import java.util.LinkedList;import java.util.ListIterator;//创建一个空的LinkedList<Integer>,通过使用ListIterator,将若干个Integer插入这个List中,插入时,//总是将它们插入到List的中间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);}}

?练习17

/*使用练习1中的Gerbill类,将其放入Map中,将每个Gerbil的名字(例如Fuzzy或Spot)String(键)与每个Gerbil(值)关联起来。为KeySet()获取Iterator,使用它遍历Map,针对每个"键"查询 Gerbil,然后打印出 "键",并让gerbil执行hop()*/package com.evelen;import java.util.HashMap;import java.util.Iterator;import java.util.Map;class Gerbil3 {private int gerbilNumber;public Gerbil3(int i){gerbilNumber = i;}public void hop() {System.out.println("gerbil " + gerbilNumber + " hops");}}public class Gerbils17 {public static void main(String[] args) {Map<String,Gerbil3> gerbils = new HashMap<String,Gerbil3>();gerbils.put("Fuzzy", new Gerbil3(0));gerbils.put("Spot", new Gerbil3(1));gerbils.put("Speedy", new Gerbil3(2));gerbils.put("Dopey", new Gerbil3(3));gerbils.put("Sleepy", new Gerbil3(4));gerbils.put("Happy", new Gerbil3(5));Iterator<String> it = gerbils.keySet().iterator();while(it.hasNext()) {String s = it.next();System.out.print(s + ": ");gerbils.get(s).hop();}}}

?练习18

package com.evelen;// 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.*;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("1"+gerbils);System.out.println();Set<String> sortedKeys = new TreeSet<String>(gerbils.keySet());System.out.println("2"+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("3"+sortedGerbils);System.out.println();// or, just:Map<String, Gerbil> sortedGerbils2 =new TreeMap<String, Gerbil>(gerbils);System.out.println("4"+sortedGerbils2);}}

?练习27

package com.evelen;// 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 Ex27 {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());}}

??练习28

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

?练习29

package com.evelen;// 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());}}

?

读书人网 >编程

热点推荐