一、简介
Java集合框架位于java.util包中
Collection是Set和List的父类,Colections是工具类,提供了对集合进行排序、遍历等多种算法的实现。
ArrayList: 有序(放进去顺序和拿出来顺序一致),可重复
HashSet: 无序(放进去顺序和拿出来顺序不一定一致),不可重复
Student[] student = new Student[3];
ArrayList<Student> list = new ArrayList<>();
Student student1 = new Student();
Student student2 = new Student();
Student student3 = new Student();
Student student4 = new Student();
Student student5 = new Student();
list.add(student1);
list.add(student2);
list.add(student3);
list.add(student4);
list.add(student5);
//有序可重复
//有序:放进去的顺序和拿出来的顺序一致
List<String> list1 = new ArrayList<>();
list1.add("Java");
list1.add("UI");
list1.add("H5");
list1.add("H5");
list1.add("aa");
for (String str : list1) {
System.out.println(str);
}
System.out.println("-----------------------------");
//无序不重复
//HashSet<String> set = new HashSet<>();
Set<String> set = new HashSet<>();
set.add("Java");
set.add("UI");
set.add("H5");
set.add("H5");
set.add("aa");
for (String str : set) {
System.out.println(str);
}
二、ArrayList和LinkedList区别
ArrayList和LinkedList的大致区别如下:
1.ArrayList是实现了基于动态数组的数据结构,LinkedList基于链表的数据结构,
2.对于随机访问get和set,ArrayList觉得优于LinkedList,因为LinkedList要移动指针
3.对于新增和删除操作add和remove,LinedList比较占优势,因为ArrayList要移动数据
三、队列
Queue先进先出 FIFO Firt In First Out
客服电话、12306排队买票、滴滴打车
LinkedList linkedList = new LinkedList();
linkedList.addLast("A");
linkedList.addLast("B");
linkedList.addLast("c");
linkedList.removeFirst():
四、Map
1、Map
Map key ,value
Collection中的集合,元素是孤立存在的(理解为单身),向集合中存储元素采用一个个元素的方式存储。
Map中的集合,元素是成对存在的(理解为夫妻)。每个元素由键与值两部分组成,通过键可以找对所对应的值
Collection中的集合称为单列集合,Map中的集合称为双列集合
需要注意的是,Map中的集合不能包含重复的键,值可以重复;每个键只能对应一个值。
Map中常用的集合为HashMap集合、LinkedHashMap集合.
2.Map遍历查找值(两种方式)
引用map中的mp.entrySet,将每一条信息封装成一个entry,然后现在成了一条一条的,
引用map中的mp.get(key),将每一条信息的健封装成一条,然后通过健查找对应值,
public void test2() {
//map.put("cn","中国");
// map.put("us","美国");
// map.put("uk","英国");
Map<String,String> map = new HashMap<>();
//collection只有一个存储时使用,map存储key和value两个值
map.put("cn","中国");
map.put("us","美国");
map.put("uk","英国");
//这一步操作引用map中的mp.entrySet,将每一条信息封装成一个entry,然后现在成了一条一条的,
// 由于输出的信息每一条不会重复所以使用hashset集合
Set<Map.Entry<String,String>> set = map.entrySet();
for (Map.Entry<String, String> entries : set) {
System.out.println(entries.getKey() + " : " + entries.getValue());
}
System.out.println("------------------------------------");
//因为key是关键词所以不会重复,接下来只需要遍历key组成的set集合就能遍历出所有的值
Set<String> set1 = map.keySet();
for (String key : set1) {
System.out.println(key + " : " + map.get(key));//map.get(key)根据key拿到对应的值
}
String remove = map.remove("us");
System.out.println(remove);
}