3月20号
HashMap:
创建:
HashMap<String,Integer> map=new HashMap<>();
添加元素:
map.put("apple",10);
map.put("banana",20);
map.put("apple",15);//会覆盖之前的10
取值:
int value=map.get("apple");//返回15
int value1=map.getOrDefault("apple",0);//若键不存在,返回0
判断键/值是否存在:
boolean hasKey=map.containsKey("apple");//返回true
boolean hasValue=map.containsValue("20");//返回true
删除:
map.remove("banana");
map.remove("apple",15);//只有apple对应15时删除
遍历:
//键值对
for(Map.Entry<String,Integer>entry:map.entrySet()){
String Key=entry.getKey();
int Value=entry.getValue();
System.out.println(key+":"+Value);
}
//键
for(String Key:map.KeySet()){
System.out.println(Key);
}
//值
for(int Value:map.Value()){
System.out.println(Value);
}
清空与大小:
map.clear();
int size=map.size();
boolean isEmpty=map.isEmpty();
ArrayList:
创建:
ArrayList<String> names=new ArrayList<>();
添加:
names.add(0,"Bob");//在第0个位置添加Bob
names.add("Alice");
访问:
String first=names.get(0);//得到第0个位置的元素
修改:
names.set(1,"Charlie");//Charlie代替位置1的元素
删除:
names.remove(0);//删除第0个位置的元素
names.remove("Charlie");