ArrayList<type parameters>names=new ArrayList<type parameters>();
可以在ArrayList中添加他的子类型
import java.util.*;
class Apple1 extends Apple {}
class Apple2 extends Apple {}
class Apple3 extends Apple {}
class Apple4 extends Apple {}
public class GenericsAndUpcasting {
public static void main(String[] args) {
ArrayList<Apple> apples = new ArrayList<Apple>();
apples.add(new Apple1());
apples.add(new Apple2());
apples.add(new Apple3());
apples.add(new Apple4());
for (Apple c : apples) {
System.out.println(c);
}
}
}
输出
Apple1@659e0bfd
Apple2@2a139a55
Apple3@15db9742
Apple4@6d06d69c
container:
Upcast
List <Apple> apples=new LinkedList <Apple> ();
Collection <Integer> i=new ArrayList <Integer> ();
Collection.addAll方法
import java.util.*;
public class AddingGroups {
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 };
Collections.addAll(collection, 11, 12, 13, 14, 15);
Collections.addAll(collection, moreInts);
List<Integer> list = Arrays.asList(16, 17, 18, 19, 20);
list.set(1, 99);
}
}
asList()方法将一组方法或一个数组转换成List对象。
Collection.addAll()只接受另一个Collection对象作为参数。
不如Arrays.asList()和Collections.addAll()灵活。
import java.util.*;
public class PrintingGontainers {
static Collection fill(Collection<String>collection){
collection.add("rat");
collection.add("cat");
collection.add("dog");
collection.add("dog");
return collection;
}
static Map fill(Map<String,String>map){
map.put("rat", "Fuzzy");
map.put("cat", "Rags");
map.put("dog", "Bosco");
map.put("dog", "Sopt");
return map;
}
public static void main(String[] args) {
System.out.println(fill(new ArrayList<String>()));
System.out.println(fill(new LinkedList<String>()));
System.out.println(fill(new HashSet<String>()));
System.out.println(fill(new TreeSet<String>()));
System.out.println(fill(new LinkedHashSet<String>()));
System.out.println(fill(new HashMap<String,String>()));
System.out.println(fill(new TreeMap<String,String>()));
System.out.println(fill(new LinkedHashMap<String,String>()));
}
}
输出
[rat, cat, dog, dog]
[rat, cat, dog, dog]
[rat, cat, dog]
[cat, dog, rat]
[rat, cat, dog]
{rat=Fuzzy, cat=Rags, dog=Sopt}
{cat=Rags, dog=Sopt, rat=Fuzzy}
{rat=Fuzzy, cat=Rags, dog=Sopt}
Collection每个位置只有一项,
Map每个位置有两项,一个key和一个与之关联的value。
由输出可以看出它们的默认打印方式(即由容器的toString()方法决定的):
Map允许使用一个key来寻找一个相关联的对象
Map自动调整大小。
Map元素的存储顺序不是插入顺序。