目录
🥬集合框架
Java
集合框架
Java Collection Framework
,又被称为容器
container
,是定义在
java.util
包下的一组接口
interfaces
和其实现类
classes
。
其主要表现为将多个元素
element
置于一个单元中,用于对这些元素进行快速、便捷的存储
store
、检索retrieve
、管理
manipulate
,即平时我们俗称的增删查改
CRUD
。
例如,一副扑克牌
(
一组牌的集合
)
、一个邮箱
(
一组邮件的集合
)
、一个通讯录
(
一组姓名和电话的映射关系
)
等等。
类和接口总览:
Java 集合框架的优点及作用 :
使用成熟的集合框架,有助于我们便捷、快速的写出高效、稳定的代码
。学习背后的数据结构知识,有助于我们理解各个集合的优缺点及使用场景。
🥬Collection 接口
Collection接口常用方法说明
代码示例:
public static void main(String[] args) {
Collection<String> collection=new ArrayList<>();//<E>尖括号里面放个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<Integer> 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接口
Map接口常用方法说明
代码示例:
public static void main(String[] args) {
Map<String,String> map=new HashMap<>();//
//Map<String,String> 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<Map.Entry<String,String>> entrySet=map.entrySet();//将所有键值返回
for (Map.Entry<String,String> 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<Integer,String> map1=new TreeMap<>();
map1.put(1,"hello1");
map1.put(2,"hello2");
System.out.println(map1);
}
HashMap和TreeMap均可实现Map接口。
🥬小结
以上就是今天的内容了,有什么问题都可以在评论区留言✌✌✌!