第十一章 练习题

练习一:

class Gerbil {
	int gerbilNumber;
	public Gerbil(int i) {
		gerbilNumber = i;
	}
	public void hop() {
		print("Gerbil" + gerbilNumber + "hops");
	}
}

public class Ex11_1 {
	public static void main(String[] args) {
		ArrayList<Gerbil> gb = new ArrayList<Gerbil>();
		for(int i = 0; i < 10; i++) {
			gb.add(new Gerbil(i));
		}
		for(int i = 0; i < 10; i++) {
			gb.get(i).hop();
		}
		for(Gerbil g : gb) {
			g.hop();
		}
	}
}

练习二: 

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

练习四:

package com.tutorialspoit;

import java.util.Connection;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.TreeSet;

import static com.tutorialspoit.Print.*;

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 Ex11_4 {
	public static void main(String[] args) {
		Generator gen = new Generator();
		String[] a = new String[10];
		gen.fillA(a);
		for(String s : a) print(s + " ");
		print();
		print(gen.fill(new ArrayList<String>(),10));
		print(gen.fill(new LinkedList<String>(),10));
		print(gen.fill(new HashSet<String>(),10));
		print(gen.fill(new LinkedHashSet<String>(),10));
		print(gen.fill(new TreeSet<String>(),10));
	}
}

练习五:

发布了59 篇原创文章 · 获赞 16 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/hou_shiyu/article/details/98073542