public static void main(String[] args) {
Collection<Integer> collection=new ArrayList<Integer>(Arrays.asList(1,2,3)) ;
Integer[] moreInts= {6,7,8,9,10};
System.out.println(collection);
collection.addAll(Arrays.asList(moreInts));
System.out.println(collection);
Collections.addAll(collection, 11,22,33);
System.out.println(collection);
Collections.addAll(collection, moreInts);
System.out.println(collection);
List<Integer> list = Arrays.asList(16,12,3,4,1);
System.out.println(list);
list.set(1, 22);
System.out.println(list);
//list.add(22);//list目前是数组,数组不可变
//list.remove(1);
}
public static void main(String[] args) {
List<Snow> snow1=Arrays.asList(
new Crusty(),new Slush(),new Powder()
);
List<Snow> snow2=Arrays.asList(new Light(),new Heavy());//这个 在早期版本应该是不支持多层向上转型 但是我用过的可以
System.out.println(snow2);
List<Snow> snow3=new ArrayList<Snow>();
Collections.addAll(snow3, new Light(),new Heavy());
}
public class PrintingContainers {
static Collection fill(Collection<String> col) {
col.add("rat");
col.add("cat");
col.add("dog");
col.add("dog");
col.add("ssus");
col.add("a2sg");
return col;
}
static Map fill(Map<String, String> map) {
map.put("rat","FUZZY");
map.put("cat","RAGS");
map.put("dog","BOSCO");
map.put("dog","SPOT");
map.put("ssus","SSSSS");
map.put("a2sg","AAAA");
return map;
}
public static void main(String[] args) {
//两种结果相同,但是内部实现不同,按照插入顺序保存元素
System.out.println("arraylist:"+fill(new ArrayList<String>()));
System.out.println("linkedlist:"+fill(new LinkedList<String>()));
//无序,但是快
System.out.println("hashset:"+fill(new HashSet<String>()));
//自动排序
System.out.println("treeset:"+fill(new TreeSet<String>()));
//有序
System.out.println("linkedhashset:"+fill(new LinkedHashSet<String>()));
//key值为对应的set
System.out.println("treemap:"+fill(new TreeMap<String,String>()));
System.out.println("hashmap:"+fill(new HashMap<String,String>()));
System.out.println("linkedhashmap:"+fill(new LinkedHashMap<String,String>()));
}
}
ArrayList:随机访问快 插入慢
LinkedList:插入快,随机访问慢,顺序访问快
迭代器的功能: 迭代器没有size(),没有length 只能next
迭代器统一了容器的访问方式
public static void dispaly(Iterator<Pet> it) {
while(it.hasNext()) {
Pet p = it.next();
System.out.print(p.id()+":"+p+" ");
}
System.out.println();
}
public static void main(String[] args) {
ArrayList<Pet> pets = Pets.arrayList(8);
LinkedList<Pet> petsLL = new LinkedList<Pet>(pets);
HashSet<Pet> hashSet = new HashSet<Pet>(pets);
TreeSet<Pet> treeSet = new TreeSet<Pet>(pets);
dispaly(pets.iterator());
dispaly(petsLL.iterator());
dispaly(hashSet.iterator());
dispaly(treeSet.iterator());
}