ArrayList
- Add to
- insert
- access
- modify
- delete
- Traverse
package com.itheima;
import java.util.ArrayList;
import java.util.Iterator;
public class Main {
public static void main(String[] args) {
ArrayList<String> c1 = new ArrayList<>();
c1.add("Red");
c1.add("Green");
c1.add("Black");
c1.add("White");
c1.add("Pink");//添加
System.out.println(c1);
//一、遍历
for(int i=0;i<c1.size();i++){
System.out.println(c1.get(i)); // 访问
}
//二、强循环遍历
for(String str:c1)
System.out.println(str);
//迭代器遍历
Iterator<String> iterator = c1.iterator();
while (iterator.hasNext())
System.out.println(iterator.next());
}
}
Copy an array list to another array list: Collections.copy(List1, List2);
Array list swaps two elements: Collections.swap(c1, 0, 2);
Connect two array lists: c2.addAll(c1);
Clone an array list to another array list: ArrayList newc1 = (ArrayList)c1.clone();
Clear the array list: c1.removeAll(c1);
Extract part of the array list: List sub_List = list_Strings.subList(0, 3);
HashMap
- Add to
- access
- modify
- delete
- Traverse
package com.itheima;
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
HashMap<Integer, String> map = new HashMap<>();
map.put(1,"Red");
map.put(2,"Green");
map.put(3,"Black");
map.put(4,"White");
map.put(5,"Blue"); // 添加
for(Integer i:map.keySet()){
//遍历键集合
System.out.print("键:"+i + ",");
System.out.println("值:" + map.get(i)); //通过键访问值
}
for(String str:map.values()){
//遍历值集合
System.out.println("值:" + str);
}
for(Map.Entry x : map.entrySet()){
System.out.println("键:"+x.getKey() +" 值:" + x.getValue() );
}
}
}
Copy all maps from the specified map to another map: hash_map2.putAll(hash_map1);
Delete all mappings in the mapping: hash_map.clear();
Get a shallow copy of the HashMap instance: new_hash_map = (HashMap)hash_map.clone();
HashSet
- Add to
- delete
- Traverse
- contain
package com.itheima;
import java.util.HashSet;
import java.util.Iterator;
public class Main {
public static void main(String[] args) {
HashSet<String> set = new HashSet<>();
set.add("Red");
set.add("Green");
set.add("Black");
set.add("White");
set.add("Pink");
set.add("Yellow"); // 添加
System.out.println(set);
for (String str : set){
System.out.println(str);
}
Iterator<String> iterator = set.iterator();
while (iterator.hasNext())
System.out.println(iterator.next());
System.out.println(set.contains("Pink")); //判断集合是否存在该元素
}
}