package Exer_11;
import java.util.*;
/**
* 练习2:修改SimpleCollection.java,使用Set来表示c。
* @author lzcysd
*
*/
public class Exer_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 + ", ");
}
}
/*运行结果
* 2, 4, 9, 8, 6, 1, 3, 7, 5, 0,
* ???
*/
-------------------------------------------------------------------------------------------------------------------------------
package Exer_11;
/**
* 练习3:修改innerclasses/Sequence.java,使你可以向其中添加任意数量的元素
* @author lzcysd
*
*/
import java.util.*;
interface Selector {
boolean end();
Object current();
void next();
}
public class Exer_11_3 {
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) {
Exer_11_3 s3 = new Exer_11_3();
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();
}
}
}
/*运行结果
* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 13 good bye
*/
-------------------------------------------------------------------------------------------------------------------------------
package Exer_11;
import java.util.*;
/**
* @author lzcysd
*
*/
public class AddingGroups {
/**
* @param args
*/
public static void main(String[] args) {
Collection<Integer> collection =
new ArrayList<Integer>(Arrays.asList(1,2,3,4,5));
Integer[] moreInts = {6,7,8,9,10};
collection.addAll(Arrays.asList(moreInts));
Collections.addAll(collection, 11,12,13,14,15);
//采用这种方法好
Collections.addAll(collection,moreInts);
List<Integer> list = Arrays.asList(16,17,18,19,20);
//其底层表示的是数组,不能使用add()和delete()方法
list.set(1,99); //改变下标为1对应的元素的值
//list.add(21); 错误
ArrayList<Integer> aList = new ArrayList<Integer>();
aList.add(0);
aList.add(1);
aList.add(2);
aList.add(3);
aList.add(2, 222);
List<Integer> aList1 = list.subList(1, 4); //返回包括1不包括4的,返回类型为List
System.out.println(collection);
System.out.println(list);
System.out.println(aList);
System.out.println(aList1);
collection.retainAll(aList); //求collection集合和aList集合的交集
System.out.println(collection);
}
}
/* 运行结果
* [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 6, 7, 8, 9, 10]
* [16, 99, 18, 19, 20]
* [0, 1, 222, 2, 3]
* [99, 18, 19]
* [1, 2, 3]
*/