练习题:
exercise1:
package Chapter11;
import java.util.ArrayList;
public class Gerbil {
private int gerbilNumber;
public Gerbil(int gerbilNumber) {
this.gerbilNumber = gerbilNumber;
}
void hop() {
System.out.println("Gerbil "+gerbilNumber+" is jumping");
}
public static void main(String[] args) {
ArrayList<Gerbil> gerbils = new ArrayList<Gerbil>();
for(int i=0;i<20;i++) {
gerbils.add(new Gerbil(i));
}
for(int i =0;i<gerbils.size();i++) {
gerbils.get(i).hop();
}
}
}
exercise2:
package Chapter11;
import java.util.HashSet;
import java.util.Set;
public class Exercise2 {
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+",");
}
}
}
exercise3:
package Chapter11;
import java.util.ArrayList;
interface Selector{
boolean end();
Object current();
void next();
}
public class Sequence {
private ArrayList<Object> items = new ArrayList<Object>();
private int next = 0;
public void add(Object o) {
items.add(o);
}
public Selector selector() {
return new SequenceSelector();
}
private class SequenceSelector implements Selector {
public Sequence getSequence() { //外部类名字.this
return Sequence.this;
}
public boolean end() {
return items.isEmpty();
}
public Object current() {
return items.get(next);
}
public void next() {
items.remove(items.get(next));
}
}
public static void main(String[] args) {
Sequence s = new Sequence();
for(int i=0;i<10;i++) {
s.add(Integer.toString(i));
}
Selector ss = s.selector();
while(!ss.end()) {
System.out.print(ss.current()+" ");
ss.next();
}
}
}
exercise4:
package Chapter11;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.TreeSet;
public class Generator {
private int next=0;
public String next() {
String[] a = {"Snow","White","Wars" };
return a[(next++)%a.length];
}
public static void main(String[] args) {
ArrayList<String> a = new ArrayList<String>();
LinkedList<String> l = new LinkedList<String>();
HashSet<String> h = new HashSet<String>();
LinkedHashSet<String> lh = new LinkedHashSet<String>();
TreeSet<String> ts = new TreeSet<String>();
Generator g = new Generator();
for(int i=0;i<100;i++) {
a.add(g.next());
l.add(g.next());
h.add(g.next());
lh.add(g.next());
ts.add(g.next());
}
System.out.println(a);
System.out.println(l);
System.out.println(h);
System.out.println(lh);
System.out.println(ts);
}
}
exercise5:
代码来自http://dsr-22.iteye.com/blog/997476,实在是太多了,懒得打了。区别在5和6哪里,由于使用的是equals方法,所以对int 和对象的判断会不一样,对象需要是同一个才会返回true,int就不需要了。
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;
public class Exercise5 {
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]);
}
}
exercise6:
修改上一题的代码,不同处依然是5和6,equals 对于引用和String int 等类型的表现是不一样的。
package Chapter11;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;
public class Exercise6 {
public static List<String> listofRandInteger(int length, int n)
{
Random rand = new Random();
List<String> li = new ArrayList<String>();
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<String> li = listofRandInteger(7,10);
System.out.println("1: " + li);
String 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);
String p = li.get(2);
System.out.println("4: " + p + " " + li.indexOf(p));
String cy = new String(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<String> 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<String> copy = new ArrayList<String>(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<String>(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]);
String[] ia = li.toArray(new String[0]);
System.out.println("23: " + ia[3]);
}
}
exercise7:
发现题意理解错了。。。 题意是建立自己创建的类的List,我这边使用的是Integer的List.
Arrays.asList()方法无法将int数组转换成List, 解决方式是将数组改用Integer数组。
参考:http://blog.csdn.net/hehexiaoyou/article/details/23340239
package Chapter11;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Exercise7 {
Integer[] a;
public static void main(String[] args) {
Exercise7 e7 = new Exercise7();
e7.a = new Integer[10];
for(int i=0;i<e7.a.length;i++) {
e7.a[i]=i;
}
List<Integer> l = Arrays.asList(e7.a);
System.out.println(l);
List l1 = l.subList(0, 3);
List<Integer> copy = new ArrayList<Integer>(l);
copy.removeAll(l1);
l=copy;
//l.removeAll(l1); 不能这样操作。。。
//l = l.subList(l1.size(), l.size());
System.out.println(l);
}
}
exercise8:
package Chapter11;
import java.util.ArrayList;
import java.util.Iterator;
public class Gerbil {
private int gerbilNumber;
public Gerbil(int gerbilNumber) {
this.gerbilNumber = gerbilNumber;
}
void hop() {
System.out.println("Gerbil "+gerbilNumber+" is jumping");
}
public static void main(String[] args) {
ArrayList<Gerbil> gerbils = new ArrayList<Gerbil>();
for(int i=0;i<20;i++) {
gerbils.add(new Gerbil(i));
}
Iterator<Gerbil> it = gerbils.iterator();
while(it.hasNext())
it.next().hop();
}
}
exercise9:
package Chapter11;
import java.util.ArrayList;
import java.util.Iterator;
interface Selector{
boolean end();
Object current();
void next();
}
public class Sequence {
private ArrayList<Object> items = new ArrayList<Object>();
private int next = 0;
public void add(Object o) {
items.add(o);
}
public Selector selector() {
return new SequenceSelector();
}
// public Selector reverseselector() {
// class reverseSelector implements Selector{
//
// public Sequence getSequence() { //外部类名字.this
// return Sequence.this;
// }
//
// public boolean end() {
// return items.isEmpty();
// }
//
// public Object current() {
// return items.get(next);
// }
//
// public void next() {
// next++;
// }
//
// }
// return new reverseSelector();
// }
private class SequenceSelector implements Selector {
public Sequence getSequence() { //外部类名字.this
return Sequence.this;
}
public boolean end() {
return items.isEmpty();
}
public Object current() {
return items.get(next);
}
public void next() {
items.remove(items.get(next));
}
}
public static void main(String[] args) {
Sequence s = new Sequence();
for(int i=0;i<10;i++) {
s.add(Integer.toString(i));
}
// Selector ss = s.selector();
// //Selector rs = s.reverseselector();
// while(!ss.end()) {
// System.out.print(ss.current()+" ");
// ss.next();
// }
while(!rs.end()) {
System.out.print(rs.current()+" ");
rs.next();
}
Iterator<Object> it= s.items.iterator();
while(it.hasNext())
System.out.print(it.next()+" ");
}
}
exercise10:
package Chapter8;
import java.util.ArrayList;
import java.util.Iterator;
public class RodentTest {
public static void main(String[] args) {
// Rodent[] rodent =new Rodent[2];
// rodent[0]= new Hamster();
// rodent[1]= new Mouse();
// for(int i=0;i<2;i++) {
// rodent[i].Bite();
// }
ArrayList<Rodent> r = new ArrayList<Rodent>();
r.add(new Hamster());
r.add(new Mouse());
Iterator<Rodent> it = r.iterator();
while(it.hasNext())
it.next().Bite();
}
}
class Rodent{
void Bite() {
System.out.println("Rodent Bite");
}
String what() {
return "Rodent";
}
}
class Mouse extends Rodent{
void Bite() {
System.out.println("Mouse Bite");
}
String what() {
return "Mouse";
}
}
class Hamster extends Rodent{
void Bite() {
System.out.println("Hamster Bite");
}
String what() {
return "Hamster";
}
}
exercise11:
package Chapter11;
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 Exercise11 {
public static void PrintAll(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));
PrintAll(al);
PrintAll(ll);
PrintAll(hs);
PrintAll(ts);
PrintAll(lhs);
}
}
exercise12:
给的参考答案是反向替代了list2的元素,感觉和题目不大对,这里贴上我自己的代码。
package Chapter11;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.ListIterator;
public class Exercise12 {
public static void main(String[] args) {
List<Integer> list1 = new ArrayList<Integer>(Arrays.asList(1,2,3,4,5));
List<Integer> list2 = new ArrayList<Integer>(Arrays.asList(6,7,8,9,10));
ListIterator<Integer> li = list1.listIterator();
while(li.hasNext())
li.next();
while(li.hasPrevious()) {
list2.add(li.previous());
}
ListIterator<Integer> li2 = list2.listIterator();
while(li2.hasNext())
System.out.print(li2.next()+" ");
}
}
exercise13:
原程序是个无限循环的程序,而修改过后只执行了所有事件一次,应该是必须用copy代替eventlist的缘故。
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());
}
}
}
exercise14:
previous()在空的时候不能使用,会报错。。。
package Chapter11;
import java.util.LinkedList;
import java.util.ListIterator;
public class Exercise14 {
public LinkedList<Integer> ll = new LinkedList<Integer>();
public void insertMid(Integer a) {
ListIterator<Integer> it = ll.listIterator();
int first = it.nextIndex()-1;
while(it.hasNext())
it.next();
int last = it.previousIndex()+1;
int mid = (first+last)/2;
if(!it.hasPrevious())
it.add(a);
else {
while(it.previousIndex()!=mid) {
it.previous();
}
it.add(a);
}
}
public static void main(String[] args) {
Exercise14 e = new Exercise14();
e.insertMid(1);
e.insertMid(2);
e.insertMid(3);
e.insertMid(4);
e.insertMid(5);
e.insertMid(6);
System.out.println(e.ll);
}
}
exercise15:
来自Thinking in java 的答案。
// 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());
}
}
exercise16:
判断元音部分可以用正则表达式简化? 暂时不会。。
package Chapter11;
import net.mindview.util.*;
import java.util.*;
public class VowelWords {
public static int hasVowel(String s) {
int count=0;
for(int i=0;i<s.length();i++)
if(s.charAt(i)=='A'||s.charAt(i)=='E'||s.charAt(i)=='I'||s.charAt(i)=='O'||s.charAt(i)=='U'||s.charAt(i)=='a'||s.charAt(i)=='e'||s.charAt(i)=='i'||s.charAt(i)=='o'||s.charAt(i)=='u')
count++;
return count;
}
public static void main(String[] args) {
Set<String> vowelWords = new TreeSet<String>(new TextFile("UniqueWord.java", "\\W+"));
int sum=0;
System.out.println(vowelWords);
Set<String> copy = vowelWords;
Iterator<String> it = copy.iterator();
while(it.hasNext()) {
String s = it.next();
sum +=hasVowel(s);
System.out.println(s+"的元音字母数:"+hasVowel(s));
}
System.out.println("一共有"+sum+"个元音字母。");
}
}
exercise17:
package Chapter11;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class Exercise17 {
public static void main(String[] args) {
Map<String, Gerbil> m = new HashMap<String,Gerbil>();
m.put("Fuzzy", new Gerbil(1));
m.put("Spot", new Gerbil(2));
Iterator<String> it = m.keySet().iterator();
while(it.hasNext()){
String s = it.next();
System.out.print(s+":");
m.get(s).hop();
}
}
}
exercise18:
package Chapter11;
import java.util.*;
public class Exercise18 {
public static void main(String[] args) {
Map<String, String> m = new HashMap<String,String>();
m.put("adada", "1");
m.put("ASkajfgk", "2");
m.put("51456fsfh", "3");
m.put("uiret", "5");
System.out.println(m);
Set<String> sortedKeys = new TreeSet<String>(m.keySet());
System.out.println(sortedKeys);
Map<String, String> sortedMap = new LinkedHashMap<String,String>();
for(String s :sortedKeys) {
sortedMap.put(s,m.get(s));
}
System.out.println(sortedMap);
}
}
exercise19:
按照要求替换即可。
exercise20:
答案来自该书官方文档,思路超级清晰,比我的强数强多了。。希望以后能记住这个做法。
package Chapter11;
import java.util.*;
import net.mindview.util.*;
public class Exercise20 {
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);//v在该字符中 则count+1 存入Map中
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("UniqueWord.java", "\\W+"));
System.out.println(words);
System.out.println();
vowelCounter20(words);
}
}
exercise21:
Arrays.sort(arrayList, String.CASE_INSENSITIVE_ORDER); 大小写不敏感, 严格按照a-z排序;
package Chapter11;
import java.util.*;
import net.mindview.util.TextFile;
public class UniqueWord21 {
public static void main(String[] args) {
List<String> words = new ArrayList<String>(new TextFile("UniqueWord.java","\\W+"));
Collections.sort(words, String.CASE_INSENSITIVE_ORDER);
System.out.println(words);
Map<String,Integer> wordCount = new HashMap<String,Integer>();
int totalWords = 0;
for(String s : words) {
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(totalWords);
}
}
exercise22
package Chapter11;
import java.util.*;
import net.mindview.util.TextFile;
class Word{
String s;
int count;
public Word(String s,int count) {
this.s =s;
this.count = count;
}
public String toString() {
return s+":"+count;
}
}
public class UniqueWord22 {
public static void main(String[] args) {
List<String> words = new ArrayList<String>(new TextFile("UniqueWord.java","\\W+"));
Collections.sort(words, String.CASE_INSENSITIVE_ORDER);
System.out.println(words);
Set<Word> word = new HashSet<Word>();
int totalWords = 0;
for(String s : words) {
int count=0;
for(int i=0;i<words.size();i++) {
if(s.equals(words.get(i))) {
count++;
}
}
Word w = new Word(s, count);
totalWords++;
word.add(w);
}
System.out.println();
System.out.println("Word count: " + word);
System.out.println();
System.out.println("Total words: " + totalWords);
}
}
exercise23:
package Chapter11;
import java.util.*;
class findMAX{
int findMax(){
Random rand = new Random();
Map<Integer,Integer> m = new HashMap<Integer,Integer>();
for(int i=0;i<10000;i++) {
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.size();i++) {
if(m.get((Integer)i)>max)
max = m.get((Integer)i);
}
int maxkey = 0;
for(int i=0;i<m.size();i++) {
if(m.get((Integer)i)==max)
maxkey = i;
}
return maxkey;
}
}
public class Statistics23 {
public static void main(String[] args) {
findMAX fm = new findMAX();
Map<Integer,Integer> m20 =
new TreeMap<Integer,Integer>();
for(int i = 0; i < 2000; i++) {
int x = fm.findMax();
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);
}
}
exercise24:
package Chapter11;
import java.util.*;
public class Exercise24 {
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);
Map<String,Integer> mTemp = new LinkedHashMap<String,Integer>();
System.out.println(m);
Set<String> s = new TreeSet<String>(m.keySet());
Iterator<String> it = s.iterator();
while(it.hasNext()) {
String s1 = it.next();
Integer i = m.get(s1);
m.remove(s1);
mTemp.put(s1, i);
}
Iterator<String> itTemp =mTemp.keySet().iterator();
while(itTemp.hasNext()) {
String st =itTemp.next();
m.put(st, mTemp.get(st));
}
System.out.println(m);
}
}
exercise25:
package Chapter11;
import java.util.*;
import net.mindview.util.TextFile;
public class UniqueWord25 {
public static void main(String[] args) {
List<String> words = new ArrayList<String>(new TextFile("UniqueWord.java","\\W+"));
Map<String,ArrayList<Integer>> wordCount = new HashMap<String,ArrayList<Integer>>();
Iterator<String> it = words.iterator();
int count=0;
while(it.hasNext()) {
String s = it.next();
if(wordCount.keySet().contains(s)) {
wordCount.get(s).add(count);
}else {
ArrayList<Integer> location = new ArrayList<Integer>();
location.add(count);
wordCount.put(s, location);
}
count++;
}
System.out.println(wordCount);
}
}
exercise26:
package Chapter11;
//import java.util.*;
//import net.mindview.util.*;
//
//public class UniqueWord26 {
// 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());
// }
//}
import java.util.*;
import net.mindview.util.TextFile;
public class UniqueWord26 {
public static void main(String[] args) {
List<String> words = new ArrayList<String>(new TextFile("UniqueWord.java","\\W+"));
Map<String,ArrayList<Integer>> wordCount = new HashMap<String,ArrayList<Integer>>();
Iterator<String> it = words.iterator();
int count=0;
while(it.hasNext()) {
String s = it.next();
if(wordCount.keySet().contains(s)) {
wordCount.get(s).add(count);
}else {
ArrayList<Integer> location = new ArrayList<Integer>();
location.add(count);
wordCount.put(s, location);
}
count++;
}
System.out.println(wordCount);
List<String> wordCountSort = new LinkedList<String>();
for(int i=0;i<wordCount.size();i++) {
Iterator<ArrayList<Integer>> its = wordCount.values().iterator();
int count1=0;
while(its.hasNext()){
ArrayList<Integer> temp = its.next();
int j=0;
while(j<temp.size()) {
if(i==temp.get(j)) {
wordCountSort.add((String) wordCount.keySet().toArray()[count1]);
}
j++;
}
count1++;
}
}
System.out.println(wordCountSort);
}
}
exercise27:
package Chapter11;
import java.util.*;
class Command{
String s;
public Command(String s) {
this.s = s;
}
void operation(){
System.out.println(s);
}
}
class fillQueue{
Queue<Command> q =new LinkedList<Command>() ;
void fill() {
q.offer(new Command("Command"));
}
}
public class Exercise27 {
fillQueue fq;
public Exercise27(fillQueue fq) {
this.fq =fq;
fq.q.peek().operation();
fq.q.remove();
}
public static void main(String[] args) {
fillQueue fq = new fillQueue();
fq.fill();
Exercise27 e27 = new Exercise27(fq);
}
}
Exercise28:
package Chapter11;
import java.util.*;
public class Exercise28 {
public static void main(String[] args) {
PriorityQueue<Double> priorityQueue = new PriorityQueue<Double>();
Random rand=new Random(47);
for(int i=0;i<10;i++) {
priorityQueue.offer(rand.nextDouble());
}
while(priorityQueue.peek()!=null) {
System.out.println(priorityQueue.peek());
priorityQueue.poll();
}
}
}
exercise29:
示例来自原书提供文档。
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());
}
}