一.Collection是所有单列集合的最顶层接口,定义了所有单列集合共性的方法。任意的单列集合都可以使用Collection接口中的方法。
实例:
import java.util.ArrayList;
import java.util.Collection;
public class TestCollection {
public static void main(String[] args) {
//可以使用多态创建集合对象(接口指向实现类)
Collection<String> collection = new ArrayList<>();
/*
添加元素
*/
boolean b = collection.add("小明");//返回的是布尔值
collection.add("小红");
collection.add("小军");
System.out.println(collection);//[小明, 小红, 小军]
/*
删除集合中存在的元素,返回true;
删除集合中不存在的元素,返回false.
*/
System.out.println(collection.remove("小红"));//true
System.out.println(collection.remove("小王"));//false
System.out.println(collection);//[小明, 小军]
/*
判断集合中是否包含指定的元素;包含返回true,不包含返回false。
*/
System.out.println(collection.contains("里斯"));//false
System.out.println(collection.contains("小明"));//true
/*
判断集合是否为空
*/
System.out.println(collection.isEmpty());//false
/*
返回集合中元素的个数
*/
System.out.println(collection.size());//2
/*
把集合中的元素存储到数组中,然后遍历出来
*/
for (Object object : collection.toArray()) {
System.out.println(object);
}
/*
清空集合中所有元素,不删除集合,集合依旧存在
*/
collection.clear();
System.out.println(collection);//[]
}
}
二.Iterator接口(Iterator迭代器)
迭代器用来遍历集合中的所有元素。在取元素之前先要判断集合中是否有元素,如果有,就把这个元素取出来,继续再判断,如果还有就再取出来。一直把集合中的所有元素全部取出来为止。
实例:
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class TestIterator {
public static void main(String[] args) {
Collection<String> collection = new ArrayList<>();
collection.add("葡萄");
collection.add("香蕉");
collection.add("苹果");
collection.add("芒果");
collection.add("西瓜");
/*
注意:集合是什么泛型,迭代器就是什么泛型。
*/
Iterator<String> iterator = collection.iterator();//使用集合中的方法iterator()来获取迭代器的实现类对象,并且会把指针指向集合的-1索引位置
/*
判断集合中还有没有下一个元素,有就返回true,否则返回false。
*/
System.out.println(iterator.hasNext());//true
/*
取出集合中的下一个元素
*/
System.out.println(iterator.next());//葡萄
System.out.println(iterator.next());//香蕉
System.out.println("================");
//System.out.println("删除前大小"+collection.size());//5
/*
遍历取出剩余元素:苹果 芒果 西瓜
*/
while (iterator.hasNext()){
System.out.println(iterator.next());
//iterator.remove();//删除元素(苹果 芒果 西瓜)
}
//System.out.println("删除后大小"+collection.size());//2
System.out.println("========snip=========");
for (String s :
collection) {
System.out.println(s);
}
}
}
三.List接口:有序、有下标、元素可以重复。
实例:
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
public class TestList {
public static void main(String[] args) {
List list = new ArrayList<>();
list.add("dog");
list.add("cat");
list.add("deer");
list.add(0,"bird");//在集合的第一个位置插入元素
System.out.println("size:"+list.size());
System.out.println(list);//[bird, dog, cat]
//list.remove(0);//删除第一个元素
System.out.println("删除过后还有:"+list);
//遍历集合,使用get()方法得到元素
for (int i = 0;i<list.size();i++){
System.out.println(list.get(i));
}
System.out.println("============forEach===========");
for (Object object :
list) {
System.out.println(object);
}
System.out.println("===========迭代器===========");
Iterator iterator = list.iterator();
while (iterator.hasNext()){
System.out.println(iterator.next());
}
System.out.println("===========列表迭代器:从前往后遍历===========");
ListIterator listIterator = list.listIterator();
while (listIterator.hasNext()){
System.out.println(listIterator.nextIndex()+":"+listIterator.next());
}
System.out.println("===========列表迭代器:从后往前遍历===========");
//注意:经过上面的从前往后遍历,现在的指针已经指向末尾,这样才能使用从后往前遍历
while (listIterator.hasPrevious()){
System.out.println(listIterator.previousIndex()+":"+listIterator.previous());
}
//判断操作
System.out.println(list.contains("dog"));//true
System.out.println(list.isEmpty());//false
//获取位置
System.out.println(list.indexOf("cat"));//返回此列表中指定元素的第一次出现的索引:1
System.out.println(list.lastIndexOf("cat"));//返回此列表中指定元素的最后一次出现的索引:1
//截取操作
System.out.println(list.subList(1, 3));//[dog, cat]
}
}
四.ArrayList的使用:
import java.util.ArrayList;
import java.util.Iterator;
public class TestArrayList {
public static void main(String[] args) {
ArrayList arrayList = new ArrayList<>();
Student student1 = new Student("tom",18);
Student student2 = new Student("jerry", 39);
Student student3 = new Student("marry", 22);
//添加元素
arrayList.add(student1);
arrayList.add(student2);
arrayList.add(student3);
arrayList.add(student3);//可以添加重复的元素
System.out.println("元素个数:"+arrayList.size());
System.out.println(arrayList.toString());
//删除元素
//arrayList.remove(student1);
//System.out.println("删除之后的元素:"+arrayList.size());
//遍历元素
System.out.println("使用迭代器===========");
Iterator iterator = arrayList.iterator();
while (iterator.hasNext()){
System.out.println(iterator.next());
}
//判断
System.out.println(arrayList.isEmpty());
}
}
五.Vector的使用:
import java.util.Enumeration;
import java.util.Vector;
/**
*开发不常用,了解即可
*/
public class TestVector {
public static void main(String[] args) {
Vector vector = new Vector<>();
//添加元素
vector.add("dog");
vector.add("cat");
vector.add("pig");
//删除元素
// vector.remove("dog");
// System.out.println(vector);//[cat, pig]
// vector.remove(0);//删除第一个元素
// System.out.println(vector);
// vector.clear();//清空元素
// System.out.println(vector);//[]
//遍历元素
System.out.println("使用枚举器==========");
Enumeration elements = vector.elements();
while (elements.hasMoreElements()){
System.out.println(elements.nextElement());
}
//判断
System.out.println(vector.contains("cat"));//true
System.out.println(vector.isEmpty());//false
//获取元素
System.out.println(vector.firstElement());//第一个元素
System.out.println(vector.lastElement());//最后一个元素
System.out.println(vector.elementAt(0));//第一个元素
}
}
六.LinkedList的使用:
import java.util.Iterator;
import java.util.LinkedList;
import java.util.ListIterator;
public class TestLinkedList {
public static void main(String[] args) {
LinkedList linkedList = new LinkedList<>();
Student student1 = new Student("tom",18);
Student student2 = new Student("jerry", 39);
Student student3 = new Student("marry", 22);
//添加元素
linkedList.add(student1);
linkedList.add(student2);
linkedList.add(student3);
linkedList.add(student3);//可以添加重复的元素
System.out.println("删除元素前个数:"+linkedList.size());//4
System.out.println(linkedList);//[tom,18, jerry,39, marry,22, marry,22]
//删除元素
//linkedList.remove(student1);
//System.out.println("删除元素后个数:"+linkedList.size());//3
//遍历
System.out.println("普通for循环=============");
for (int i =0;i<linkedList.size();i++){
System.out.println(linkedList.get(i));
}
System.out.println("增强for循环==============");
for (Object object:
linkedList) {
System.out.println(object);
}
System.out.println("使用迭代器==============");
Iterator iterator = linkedList.iterator();
while (iterator.hasNext()){
System.out.println(iterator.next());
}
//使用列表迭代器可以向后或者向前遍历
System.out.println("使用列表迭代器向后遍历===============");
ListIterator listIterator = linkedList.listIterator();
while (listIterator.hasNext()){
System.out.println(listIterator.next());
}
//判断
System.out.println(linkedList.contains(student1));//true
System.out.println(linkedList.isEmpty());//false
//获取指定元素的位置
System.out.println(linkedList.indexOf(student1));//0
}
}
七.ArrayList和LinkedList的区别:
ArrayList的实现方式是数组,必须开辟连续空间,查询快,增删慢;
LinkedList的实现方式是双向链表,无需开辟连续空间,查询慢,增删快。
八.使用泛型集合:自定义添加到集合中的数据类型,没有自定义的类型的数据则不能添加到集合中。
实例:
import java.util.ArrayList;
import java.util.Iterator;
public class Test {
public static void main(String[] args) {
/**
* 例1
*/
ArrayList<String> arrayList1 = new ArrayList<>();//自定义只能添加String类型的数据
arrayList1.add("dog");
arrayList1.add("cat");
//arrayList.add(11);//尝试添加int类型的数据,编译报错
//遍历
for (String s:
arrayList1) {
System.out.println(s);
}
/**
* 例2
*/
ArrayList<Student> arrayList2 = new ArrayList<>();//自定义只能添加Student类型的数据
Student student1 = new Student("tom",18);
Student student2 = new Student("jerry", 39);
arrayList2.add(student1);
arrayList2.add(student2);
//arrayList2.add("dog");//尝试添加String类型的数据,编译报错
//使用迭代器遍历
Iterator<Student> iterator = arrayList2.iterator();
while (iterator.hasNext()){
System.out.println(iterator.next());
}
}
}
九.Set接口:无序、无下标、元素不可以重复:
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class TestSet {
public static void main(String[] args) {
Set<String> set = new HashSet<>();
//添加数据
set.add("dog");
set.add("cat");
set.add("pig");
System.out.println("删除前元素个数:"+set.size());//3
System.out.println(set);//无序打印:[cat, dog, pig]
//删除数据
set.remove("cat");
System.out.println("删除后元素个数:"+set.size());//2
System.out.println(set);
//遍历
System.out.println("1.增强for遍历============");
for (String s : set) {
System.out.println(s);
}
System.out.println("2.迭代器遍历============");
Iterator<String> iterator = set.iterator();
while (iterator.hasNext()){
System.out.println(iterator.next());
}
//判断
System.out.println(set.contains("dog"));//true
System.out.println(set.isEmpty());//false
}
}
十.HashSet的使用:
实例1:
import java.util.HashSet;
import java.util.Iterator;
public class TestHashSet {
public static void main(String[] args) {
HashSet<String> strings = new HashSet<>();
//添加元素
strings.add("dog");
strings.add("cat");
strings.add("pig");
System.out.println("删除操作前的元素个数:"+strings.size());//3
System.out.println(strings);//[cat, dog, pig]
//删除数据
strings.remove("cat");
System.out.println("删除操作后的元素个数:"+strings.size());//2
//遍历操作
System.out.println("1.增强for==============");
for (String string : strings) {
System.out.println(string);
}
System.out.println("2.迭代器============");
Iterator<String> iterator = strings.iterator();
while (iterator.hasNext()){
System.out.println(iterator.next());
}
//判断
System.out.println(strings.contains("aa"));//false
System.out.println(strings.isEmpty());//false
}
}
实例2:
import java.util.HashSet;
import java.util.Iterator;
public class TestHashSet {
public static void main(String[] args) {
HashSet<Student> students = new HashSet<>();
Student student1 = new Student("小明",18);
Student student2 = new Student("小五",18);
Student student3 = new Student("小伟",18);
//添加数据
students.add(student1);
students.add(student2);
students.add(student3);
System.out.println("删除前元素个数:"+students.size());//3
System.out.println(students);//[小五,18, 小明,18, 小伟,18]
students.remove(student1);
System.out.println("删除后元素个数:"+students.size());//2
//遍历
System.out.println("1.增强for==============");
for (Student student : students) {
System.out.println(student);
}
System.out.println("2.迭代器===============");
Iterator<Student> iterator = students.iterator();
while (iterator.hasNext()){
System.out.println(iterator.next());
}
//判断
System.out.println(students.contains(student1));//false,已经删除了
System.out.println(students.isEmpty());//false
}
}
十一.TreeSet的使用:基于排列顺序实现元素不重复
实例1:
import java.util.Iterator;
import java.util.TreeSet;
public class TestTreeSet {
public static void main(String[] args) {
/**
* 基于排列顺序实现元素不重复
*/
TreeSet<String> treeSet = new TreeSet<>();
treeSet.add("2");
treeSet.add("1");
treeSet.add("4");
treeSet.add("dd");
treeSet.add("ac");
treeSet.add("cc");
System.out.println("删除元素前大小"+treeSet.size());//6
System.out.println(treeSet);//排序打印:[1, 2, 4, ac, cc, dd]
//删除
treeSet.remove("dd");
System.out.println("删除操作之后:"+treeSet);//[1, 2, 4, ac, cc]
//遍历
System.out.println("增强for===========");
for (String s : treeSet) {
System.out.println(s);
}
System.out.println("迭代器=============");
Iterator<String> iterator = treeSet.iterator();
while (iterator.hasNext()){
System.out.println(iterator.next());
}
//判断
System.out.println(treeSet.contains("cc"));//true
}
}
实例2:
/**
* 实体类Student
*/
public class Student implements Comparable<Student>{
private String userName;
private int age;
public Student(String userName, int age) {
this.userName = userName;
this.age = age;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return userName+","+age;
}
@Override
public int compareTo(Student student) {
/**
* 先按姓名比,再按年龄比
*/
int n1 = this.userName.compareTo(student.userName);
int n2 = this.age-student.getAge();
//n1==00表示姓名相同,姓名相同则比较n2年龄
return n1==0?n2:n1;
}
}
import java.util.Iterator;
import java.util.TreeSet;
/**
* Student类必须实现Comparable接口并且重写compareTo方法来定义比较规则,否则程序会出现类型转换错误
*/
public class TestTreeSet {
public static void main(String[] args) {
TreeSet<Student> treeSet = new TreeSet<>();
Student student1 = new Student("aa",18);
Student student2 = new Student("cc",19);
Student student3 = new Student("bb",20);
//添加元素
treeSet.add(student1);
treeSet.add(student2);
treeSet.add(student3);
System.out.println("删除前元素个数:"+treeSet.size());//3
System.out.println(treeSet);//顺序打印;先按姓名比,姓名相同再按年龄比:[aa,18, bb,20, cc,19]
//删除元素
treeSet.remove(student1);
System.out.println(treeSet);//[bb,20, cc,19]
//遍历
System.out.println("1.增强for============");
for (Student student : treeSet) {
System.out.println(student);
}
System.out.println("2.迭代器=============");
Iterator<Student> iterator = treeSet.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
//判断
System.out.println(treeSet.contains(student2));//true
}
}
实例3:
import java.util.Comparator;
import java.util.TreeSet;
/**
*Comparator接口:使用匿名内部类的方式自定义比较规则;
* 则实体类不用再实现Comparable接口。
*
*/
public class TestCompareTO {
public static void main(String[] args) {
//创建集合,并指定比较规则
TreeSet<Student> treeSet = new TreeSet<>(new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
//先比较年龄,再比较姓名
int n1 = o1.getAge()-o2.getAge();
int n2 = o1.getUserName().compareTo(o2.getUserName());
return n1==0?n2:n1;//如果年龄一样则n1==0,则比较n2
}
});
Student student1 = new Student("aa",18);
Student student2 = new Student("cc",19);
Student student3 = new Student("bb",20);
treeSet.add(student1);
treeSet.add(student2);
treeSet.add(student3);
System.out.println(treeSet);//按年龄顺序排列:[aa,18, cc,19, bb,20]
}
}
实例4:
import java.util.Comparator;
import java.util.TreeSet;
/**
* 功能:使用TreeSet集合实现按字符串长度进行排序
*/
public class TreeSetDemo {
public static void main(String[] args) {
TreeSet<String> treeSet = new TreeSet<>(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
int n1 = o1.length()-o2.length();
int n2 = o1.compareTo(o2);
return n1==0?n2:n1;//如果长度一样,则按照字母顺序排序(默认比较规则),如abc在abd的前面
}
});
treeSet.add("hi");
treeSet.add("aa");
treeSet.add("dddd");
treeSet.add("iidd");
treeSet.add("xiaoming");
treeSet.add("zhangsan");
System.out.println(treeSet);//[aa, hi, dddd, iidd, xiaoming, zhangsan]
}
}
十二.Map集合的使用:用于存储任意键值对;键:无序、无下标、不允许重复(唯一);值:无序、无下标、允许重复。
实例:
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class TestMap {
public static void main(String[] args) {
HashMap<String, String> map = new HashMap<>();
// 添加
map.put("a","1");
map.put("b","2");
map.put("c","3");
map.put("a","22");//因为key不能重复,所以后面相同的key把前面的key替换掉了
System.out.println("删除前元素个数:"+map.size());//3
System.out.println(map);//{a=22, b=2, c=3}
// 删除
map.remove("a");
System.out.println("删除后元素个数:"+map.size());//2
// 遍历
System.out.println("1.使用keySet()================");
// map.keySet()得到key的集合
// map.get(key)通过key来获取value
Set<String> keySet = map.keySet();
for (String key : keySet) {
System.out.println(key+':'+map.get(key));
}
// entrySet()效率高于keySet(),因为entrySet()一次性将key和value全部取出;
// 而keySet()只取出了key,还要去遍历才能得到value
System.out.println("2.使用entrySet()===============");
Set<Map.Entry<String, String>> entries = map.entrySet();
for (Map.Entry<String, String> entry : entries) {
System.out.println(entry.getKey()+","+entry.getValue());
}
// 判断
System.out.println(map.containsKey("b"));// true
System.out.println(map.containsValue("11"));// false
}
}
十三.Map集合的实现类:
HashMap:线程不安全(只能单线程),运行效率快;允许用null作为key或value
import java.util.HashMap;
import java.util.Map;
public class TestHashMap {
public static void main(String[] args) {
HashMap<Student, String> students = new HashMap<>();
Student student1 = new Student("小明",17);
Student student2 = new Student("小龙",27);
Student student3 = new Student("小王",37);
//添加元素
students.put(student1,"北京");
students.put(student2,"天津");
students.put(student3,"武汉");
System.out.println("元素个数:"+students.size());
System.out.println(students.toString());
//删除
students.remove(student1);
System.out.println(students.size()); // 2
//遍历
//1.使用keySet();
for (Student key : students.keySet()) {
System.out.println(key.toString() + "===============" + students.get(key));
}
System.out.println("========分割线===========");
//2.使用entrySet();
for (Map.Entry<Student, String> entry : students.entrySet()) {
System.out.println(entry.getKey().toString() + "======" + entry.getValue());
}
//判断
System.out.println(students.containsKey(student2));// true
System.out.println(students.containsValue("武汉"));// true
}
}
十四.Map集合的实现类:
Hashtable(一般不用了):线程安全,运行效率慢;不允许null作为key或是value。
Properties(Hashtable的子类;常用):要求key和value都是String。通常用于配置文件的读取。
TreeMap:实现了SortedMap接口(是Map的子接口),可以对key自动排序。
TreeMap:
/**
* Student类必须实现Comparable接口并且重写compareTo方法来定义比较规则,否则程序会出现类型转换错误
*/
public class Student implements Comparable<Student>{
private String userName;
private int age;
public Student(String userName, int age) {
this.userName = userName;
this.age = age;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "姓名:"+userName+",年龄:"+age;
}
/**
* 功能:先比较姓名再比较年龄
*
* @param o
* @return
*/
@Override
public int compareTo(Student o) {
int n1 = this.userName.compareTo(o.getUserName());
int n2 = this.age-o.getAge();
return n1==0?n2:n1;
}
}
import java.util.Map;
import java.util.TreeMap;
public class TestHashMap {
public static void main(String[] args) {
TreeMap<Student, String> treeMap = new TreeMap<>();
Student student1 = new Student("小明",17);
Student student2 = new Student("小龙",27);
Student student3 = new Student("小王",37);
//添加元素
treeMap.put(student1,"上海");
treeMap.put(student2,"广州");
treeMap.put(student3,"南京");
System.out.println("元素个数:"+treeMap.size());
System.out.println(treeMap);
//删除元素
treeMap.remove(student1);
System.out.println(treeMap);
//遍历
//1.使用keySet()
for (Student student : treeMap.keySet()) {
System.out.println(student+",地址:"+treeMap.get(student));
}
//2.使用entrySet()
for (Map.Entry<Student, String> entry : treeMap.entrySet()) {
System.out.println(entry.getKey() + ",地址:" + entry.getValue());
}
//判断
System.out.println(treeMap.containsKey(student2)); //true
System.out.println(treeMap.containsValue("广州")); //true
}
}
也可以使用Comparator接口,类似于上面的TreeSet:使用匿名内部类的方式自定义比较规则;则实体类不用再实现Comparable接口。
十五.Collections工具类:集合工具类,定义除了存取以外的集合常用方法。
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class TestCollections {
public static void main(String[] args) {
ArrayList<Integer> arrayList = new ArrayList<>();
arrayList.add(2);
arrayList.add(11);
arrayList.add(23);
arrayList.add(9);
arrayList.add(0);
//排序
System.out.println("排序前:"+arrayList);
Collections.sort(arrayList);
System.out.println("排序后:"+arrayList);
//二分查找
int i = Collections.binarySearch(arrayList,11);
System.out.println(i);//返回元素在列表中的位置
//复制
ArrayList<Integer> newArrayList = new ArrayList<>();
System.out.println("扩容前的大小:"+newArrayList.size());
//newArrayList扩容
for (int j = 0; j < arrayList.size(); j++) {
newArrayList.add(0);
}
Collections.copy(newArrayList,arrayList);
System.out.println(newArrayList);
//反转
Collections.reverse(arrayList);
System.out.println("反转后:"+arrayList);
//打乱(元素不再有序)
Collections.shuffle(arrayList);
System.out.println("元素打乱后:"+arrayList);
//集合转成数组(然后就可以使用数组的方式使用元素)
//new Integer[0]:给定数组size小于集合size,转后的数组大小就是集合大小
Integer[] integers = arrayList.toArray(new Integer[0]);
System.out.println(integers.length);
System.out.println(Arrays.toString(integers));
//数组转成集合(然后就可以使用集合的方式使用元素)
//转成集合后是受限集合(不能添加和删除)
String[] names = {"小明","小王","小军","小红"};
List<String> stringList = Arrays.asList(names);
System.out.println(stringList);
//基本类型数组转成集合时要用包装类
Integer[] nums = {1,3,4,2,1};
List<Integer> integerList = Arrays.asList(nums);
System.out.println(integerList);
}
}
总结:
参考资料:
https://www.bilibili.com/video/BV1zD4y1Q7Fw?p=43