知识点:
容器类主要分为Collection和Map两大类,而Collection又分为Set、List和Queue三大类。三者区别是Set不能有重复元素,List按照插入的顺序保持顺序,Queue按照排队规则确定对象产生顺序,各种Queue以及栈的行为都由LinkedList提供。Map是键值对。
List又分为ArrayList和LinkedList两小类,ArrayList常用于随机访问元素(随机访问速度比较快),但在list中间插入和删除元素较慢。LinkedList随机访问速度较慢,但顺序访问速度较快,插入和删除的代价低(采用链表结构)。
对于Set来说,一般常用HashSet实现,它专门对快速查找进行了优化(使用散列)。TreeSet使用了红黑树数据结构中,保持元素处于排序状态;LinkedHashSet非线性安全,是哈希表和链表的结合,且是双向链表,以插入顺序保存元素。
Map是一种将对象与对象相关联的设计。HashMap设计用来快速访问,而treeMap可以保持“键”始终处于排序状态,所以没有HashMap快。LinkedHashMap保持元素插入顺序,但是也通过散列提供了快速访问的能力
下面是几种常用的方法测试:
public class CollectionTest {
public static void main(String[] args){
Random rand = new Random(100);
//Set
Set<Integer> set = new HashSet<>();
for(int i=0;i<10;i++){
set.add(rand.nextInt(20));
}
set.add(100);
set.add(1000);
Iterator<Integer> iterator = set.iterator();
System.out.println("The content of set is:");
while(iterator.hasNext()){
Integer i = iterator.next();
System.out.print(i+",");
}
System.out.println();
System.out.println("The size of set is:"+set.size());
System.out.println("Is set empty? "+set.isEmpty());
//List
Collection<String> cs = new LinkedList<>();
String str = "Python Java C Ruby";
Collections.addAll(cs,str.split(" "));
for(String s : cs){
System.out.print(s);
}
System.out.println();
System.out.println("The size of cs is:"+cs.size());
cs.remove("C");
System.out.print("The content of cs is:"+cs);
List<String> list = new ArrayList<>();
list.add("lizeyang");
list.addAll(cs);
System.out.println("Is list contains of Java: "+list.contains("Java"));
Iterator<String> it = list.iterator();
System.out.println("The content of list is:");
while(it.hasNext()){
System.out.print(it.next());
}
//Map
Map<Integer,String> map = new HashMap<>();
map.put(1,"python");
map.put(2,"Java");
map.put(3,"C");
map.put(4,"Ruby");
Iterator<Map.Entry<Integer,String>> entries = map.entrySet().iterator(); //第一种遍历方式
while(entries.hasNext()){
Map.Entry<Integer,String> entry = entries.next();
Integer key = entry.getKey();
String value = entry.getValue();
System.out.print(key+":"+value+" ");
}
System.out.print("Is map empty?"+map.isEmpty());
map.remove("C");
for(Integer key : map.keySet()){ //第二种遍历方式(通过键找值进行遍历,效率较低)
String value = map.get(key);
System.out.print(key+":"+value);
}
map.put(5, "Go");
System.out.print("The value of key'5' is: "+map.get(5));
for(Map.Entry<Integer,String> entry : map.entrySet()){ //最常用的循环遍历map方法
Integer key = entry.getKey();
String value = entry.getValue();
System.out.print(key+":"+value+" ");
}
}
}
输出结果:
学习永不止步~