1、Collection是一个接口,他有两个子接口List和Set
1、List实现类===>Arraylist、 LinkedList和Vector //基于数组实现,每次增加1.5倍空间,非线程安全
ArrayList arrayList = new ArrayList();
//基于数组实现,每次增加2倍空间,线程安全
Vector vector = new Vector();
//基于list实现,插入、删除快,查询慢
LinkedList stringLinkedList = new LinkedList<>();
2、Set实现类: new HashSet<>() //这个用的最多 new TreeSet<>()
new SortedSet<>()
new LinkedHashSet<>()
2、Collection 和 Map 的遍历
public class CollectionAndMap {
public static void main(String[] args) {
ArrayList arrayList = new ArrayList();
arrayList.add("name = liufu");
arrayList.add("gender = men");
forEarchList(arrayList);
HashMap hashMap = new HashMap();
hashMap.put("name", "liufu");
hashMap.put("gender", "nan");
iteratorMap(hashMap);
Hashtable map = System.getProperties();
iteratorMap(map);
}
public static void forEarchList(List list){
long startTime = System.currentTimeMillis();
for (String valueString : list){
System.out.println(valueString);
}
System.out.println(System.currentTimeMillis() - startTime);
}
public static void iteratorMap(Map map){
long startTime = System.currentTimeMillis();
//map则需要先将其转化为Set然后再获取Iterator迭代器来变了
Set> set = map.entrySet();
for (Entry entry : set){
System.out.println(entry);
}
System.out.println(System.currentTimeMillis() - startTime);
}
}
3、Collection和array之间的相互转换
LinkedList strings = new LinkedList<>();
strings.add("name");
strings.add("age");
strings.add("addr");
String[] stringArr = (String[]) strings.toArray();
String[] strings = new String[100];
strings[0] = "name";
List stringList = Arrays.asList(strings);
4、map.values使用
注意:如果是hashmap拿出来的顺序和插入进去的顺序不一致,如果想要一致,则使用LinkedHashMap
Map.values返回一个collecton集合
要想把它转化为ArrayList或者LinkedList,不能如下使用(会卡死)
List values = (List) map.values();
而是要
ArrayList arraylist = new ArrayList<>();
arraylist.addAll(map.values());
或者
ArrayList alarmInfos1 = new ArrayList<>(map.values());
如果想要转化为数组
String[] alarmInfos1 = new String[10];
map.values().toArray(alarmInfos1);
5、有顺序的hashmap==> linkedHashMap
LinkedHashMap map = new LinkedHashMap<>();
AlarmInfo alarmInfo = new AlarmInfo();
alarmInfo.setServiceCode("123");
map.put("123", alarmInfo);
AlarmInfo alarmInfo1 = new AlarmInfo();
alarmInfo1.setServiceCode("456");
map.put("456", alarmInfo1);
AlarmInfo alarmInfo2 = new AlarmInfo();
alarmInfo2.setServiceCode("789");
map.put("789", alarmInfo2);
AlarmInfo alarmInfo3 = new AlarmInfo();
alarmInfo3.setServiceCode("xiugai");
map.put("123", alarmInfo3);
for (Map.Entry entry : map.entrySet()){
System.out.println(entry.getKey() + "==>" + entry.getValue().getServiceCode());
}
结果是
6、hashmap的特殊用法
HashMap result = new HashMap(1) {{
put("count", "abc");
if (!containsKey("count")) {
put("count", "bcd");
}
}};
System.out.println(result.get("count"));