学习目标:
Collection接口、Map接口
学习内容:
1.Collection:
Collection的基本方法
public static void main(String[] args) {
//由于Collection是接口不能直接实例化,所以要用类来实现。
//<引用数据类型>:泛型,写一个方法/类,让这个方法和类可以同时支持多种不同类型的数据,泛型参数必须是引用类型。
Collection<引用数据类型> collection = new ArrayList<>();
//1.创建Collection
Collection<String> collection = new ArrayList<>();
//2.size():获取大小
System.out.println(collection.size());
//3.isEmpty():判断是否为空
System.out.println(collection.isEmpty());
//4.使用add():插入元素。
// add中的参数类型必须和泛型参数类型一致。
collection.add("q");
collection.add("q");
collection.add("w");
collection.add("e");
collection.add("r");
collection.add("d");
collection.add("f");
//5.toArray():将Collection转换为数组。
// 得到一个Object类型的数组
Object[] array = collection.toArray();
System.out.println(Arrays.toString(array));
//6.foreach(对象的数据类型 : 所遍历的对象)遍历集合中的元素
for (String s:collection) {
System.out.println(s);
}
//7.contains( ):判定元素是否存在
System.out.println(collection.contains("e"));
//8.remove():删除首次出现的那个元素
collection.remove("q");
for (String s:collection) {
System.out.print(s+" ");
}
//9.clear():清空所有元素
collection.clear();
}
2.Map:
Map的基本方法
Map中存储的是键值对(Key value)
通过key来找到对应的value
public static void main(String[] args) {
//1.创建Mao实例,泛型参数有两个,第一个参数是key的类型,第二个参数是value的类型
//key value这种结构最主要的目的就是根据key找到对应的value
Map<Integer,String> map = new HashMap<>();
//1.size():获取到元素个数(键值对个数)
System.out.println(map.size());
//2.isEmpty():查看是否为空
System.out.println(map.isEmpty());
//3.put():存放键值对
map.put(1,"张三");
map.put(2,"李四");
map.put(3,"王二麻子");
map.put(4,"刘武");
//4.get():根据key来查找对应的value 如果key不存在,则返回null
System.out.println(map.get(1));
System.out.println(map.get(2));
System.out.println(map.get(5));
//5.getDefault():如果key不存在,则返回默认值
System.out.println(map.getOrDefault(5,"大宝"));
//6.通过containsKey()和containsValue判定某个值是否存在
//containsKey执行效率较高,containsValue执行效率较低
map.containsKey(5);
map.containsValue("李四");
//7.foreach(:):遍历Map中的所有键值对
// Entry:表示一个键值对
// map.entrySet():获取到所有的键值对
// Mao中的元素顺序和插入顺序无关,取决于具体实现的方式
for (Map.Entry<Integer,String> entry: map.entrySet()) {
System.out.println(entry.getKey()+":"+entry.getValue());
}
//remove():删除元素
map.remove(5);
//clear():删除所有元素
map.clear();
}