Java编程思想课后习题答案

http://greggordon.org/java/tij4/solutions.htm

第十一章 持有对象

练习1:

public class Gerbil {
    private int gerbilNumber;

    public Gerbil(int i) {
        this.gerbilNumber = i;
    }

    public void hop() {
        System.out.println("Gerbil " + gerbilNumber + " hops");
    }

    public static void main(String[] args) {
        List<Gerbil> list = new ArrayList<Gerbil>();
        for (int i = 0; i < 10; i++) {
            list.add(new Gerbil(i));
        }
        for (Gerbil gerbil:list) {
            gerbil.hop();
        }
    }
}

练习2:

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

练习3:

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

练习4:

public class Generator {

    int key = 0;

    public String next() {
        switch (key) {
            default:
            case 0:
                key++;
                return "0000";
            case 1:
                key++;
                return "1111";
            case 2:
                key++;
                return "2222";
            case 3:
                key++;
                return "3333";
            case 4:
                key++;
                return "4444";
            case 5:
                key++;
                return "5555";
            case 6:
                key++;
                return "6666";
            case 7:
                key++;
                return "7777";
            case 8:
                key = 0;
                return "8888";
        }
    }

    public void fill(String[] array) {
        for (int i = 0; i < array.length; i++) {
            array[i] = next();
        }
    }

    public Collection fill(Collection<String> c, int length) {
        for (int i = 0; i < length; i++) {
            c.add(next());
        }
        return c;
    }

    public static void main(String[] args) {
        Generator gen = new Generator();
        String[] a = new String[10];
        gen.fill(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));
    }
}

练习5:

public class ListFeatures {

    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));
        // will also sort sub elements within li:
        Collections.sort(sub);
        System.out.println("sorted sublist: " + sub);
        System.out.println("11: " + li.containsAll(sub));
        System.out.println("11.25: " + li);
        // will also shuffle sub elements within 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) // to avoid out of bounds exception
            copy.set(1, 8); // autoboxing int -> Integer
        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]);
    }
}

练习6:

public class ListFeatures {

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

练习7:

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[] arrayTester = new Tester[10];
        for(int i = 0; i < arrayTester.length; i++)
            arrayTester[i] = new Tester();
        List<Tester> listTester = new ArrayList<Tester>();
        for(Tester x : arrayTester) listTester.add(x);
        System.out.println("list of Tester: " + listTester);
        List<Tester> sub = listTester.subList(2, 6);
        System.out.println("subList: " + sub);
        // 这样删除会报 ConcurrentModificationException,因此拷贝一个list,然后再删除
        // listTester.removeAll(sub);
        List<Tester> copy = new ArrayList<Tester>(listTester);
        copy.removeAll(sub);
        System.out.println("copy: " + copy);
        listTester = copy;
        System.out.println("list of Tester: " + listTester);
    }
}

练习8:

public class Gerbil {
    private int gerbilNumber;

    public Gerbil(int i) {
        this.gerbilNumber = i;
    }

    public void hop() {
        System.out.println("Gerbil " + gerbilNumber + " hops");
    }

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

练习9:

public class Sequence3 {
    private ArrayList<Object> items = new ArrayList<Object>();

    public void add(Object x) {
        items.add(x);
    }

    private Iterator iterator() {
        return items.iterator();
    }

    public static void main(String[] args) {
        Sequence3 s3 = new Sequence3();
        for (int i = 0; i < 10; i++)
            s3.add(i);
        Iterator iterator = s3.iterator();
        while (iterator.hasNext()) {
            System.out.print(iterator.next() + " ");
        }
    }
}

练习10:

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

练习11:

public class Ex11 {
    public static void printCollection(Collection c){
        Iterator iterator = c.iterator();
        while (iterator.hasNext()){
            System.out.print(iterator.next() + " ");
        }
        System.out.println();
    }

    public static void main(String[] args) {
        ArrayList<Integer> arrayList = new ArrayList(Arrays.asList(3,5,7,2));
        LinkedList<Integer> linkedList = new LinkedList(Arrays.asList(3,5,7,2));
        HashSet<Integer> hashSet = new HashSet(Arrays.asList(3,5,7,2));
        TreeSet<Integer> treeSet = new TreeSet<Integer>(Arrays.asList(3,5,7,2));
        LinkedHashSet<Integer> linkedHashSet = new LinkedHashSet<Integer>(Arrays.asList(3,5,7,2));
        printCollection(arrayList);
        printCollection(linkedList);
        printCollection(hashSet);
        printCollection(treeSet);
        printCollection(linkedHashSet);
    }
}

练习12:


public class Ex12 {

    public static void main(String[] args) {
        List<Integer> list1 = new ArrayList<Integer>(Arrays.asList(2, 4, 76, 83, 1));
        List<Integer> list2 = new ArrayList<Integer>(Arrays.asList(5, 3, 6, 8, 652, 4, 0));
        ListIterator<Integer> listIterator1 = list1.listIterator();
        while (listIterator1.hasNext()) {
            System.out.print(listIterator1.next() + " ");
        }
        System.out.println();
        while (listIterator1.hasPrevious()) {
            list2.add(listIterator1.previous());
        }
        System.out.println(list2);
    }
}

练习14:

 public static void main(String[] args) {
        LinkedList<Integer> list = new LinkedList();
        for (int i=0 ; i<10;i++){
            ListIterator<Integer> listIterator = list.listIterator(list.size()/2);
            listIterator.add(i);
        }
        System.out.println(list);
    }

练习15:

    public static void counters(Set<String> set) {
        Set s = new HashSet<Character>(Arrays.asList('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'));
        int total = 0;
        if (set != null && set.size() > 0) {
            for (String ss : set) {
                int count = 0;
                for (Character c : ss.toCharArray()) {
                    if (s.contains(c)) {
                        count++;
                        total++;
                    }
                }
                System.out.println(ss + ":" + count);
            }
            System.out.println("total:" + total);
        }
    }

    public static void main(String[] args) {
        Set<String> set = new HashSet<String>(Arrays.asList("aovowsm","good","dosmv","oasncjv","csfewff"
                ,"aaacccfso","exfvrfvoosdu","fonsjkvd"));
        counters(set);
    }

猜你喜欢

转载自blog.csdn.net/weixin_44331516/article/details/88840741