目录
集合框架
Collection 接口
Map接口
小结
Collection接口常用方法说明
代码示例:
public static void main(String[] args) {
Collection collection=new ArrayList<>();//尖括号里面放个E代表这个集合里面放的是泛型,
// 里面的类型可以根据自己想要用的去给,但一定要是复杂数据类型(类类型),面向对象的那种
collection.add("abc");//将元素放入集合中
collection.add("def");
collection.add("ghi");
System.out.println(collection);
Object[] objects=collection.toArray();//返回一个装有所有集合元素的数组
System.out.println(Arrays.toString(objects));
collection.remove("abc");//删除元素
System.out.println(collection);
collection.clear();//清除集合中所有元素
System.out.println(collection);
System.out.println(collection.isEmpty());//判断集合是否为空
System.out.println("================");
Collection collection1=new ArrayList<>();
collection1.add(1);
collection1.add(2);
System.out.println(collection1);
collection1.remove(1);
System.out.println(collection1);
System.out.println(collection1.isEmpty());
System.out.println(collection1.size());
}
Map接口常用方法说明
代码示例:
public static void main(String[] args) {
Map map=new HashMap<>();//
//Map map1=new TreeMap<>();//这两种都可
map.put("a","hello");//放入元素
map.put("b","oh");
System.out.println(map);
String str=map.get("a");//查找元素并返回
System.out.println(str);
String str1=map.getOrDefault("b","heihei");//查找元素并返回,如果没找到,则返回默认值
String str2=map.getOrDefault("a","wow");
System.out.println(str1);
System.out.println(str2);
System.out.println(map.containsKey("a"));//判断是否包含key
System.out.println(map.containsValue("hello"));//判断是否包含val
Set> entrySet=map.entrySet();//将所有键值返回
for (Map.Entry entry:entrySet) {
System.out.println("key: "+entry.getKey()+" value:"+entry.getValue());
}
System.out.println(map.size());//返回键值对数量
System.out.println(map.isEmpty());//判断是否为空
System.out.println("==============");
Map map1=new TreeMap<>();
map1.put(1,"hello1");
map1.put(2,"hello2");
System.out.println(map1);
}
HashMap和TreeMap均可实现Map接口。
以上就是今天的内容了,有什么问题都可以在评论区留言✌✌✌!