课件下载
概念:对象的容器,定义了对多个对象进行操作的常用方法。可实现数组的功能;
和数组的区别:
位置:java.uti.*
Set接口的特点:无序、无下标、元素不能重复
概念:代表一组任意类型的对象,无序、无下标、不能重复
方法:
boolean add(Object obj)
//添加一个对象boolean addAll(Collection c)
//将一个集合中的所有对象添加到此集合中void clear()
//清空此集合中的所有对象boolean contains(Object o)
//检查此集合中的是否包含o对象boolean equals(Object o)
//比较此集合是否与指定集合相等boolean isEmpty()
//判断此集合是否为空boolean remove(Object o)
//在此集合中移除对象oint size()
//返回此集合中元素的数量Object[] toArray()
//将此集合转换成数组boolean hasNext()
//是否还有下一个元素E next()
//取出当前元素void remove()
//删除当前元素保存元素
//Demo0_1
package Demo0;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
/**
* Collection接口的使用
* (1)添加元素
* (2)删除元素
* (3)遍历元素
* (4)判断
* @author dl
*/
public class Demo0_1 {
public static void main(String[] args) {
//创建集合
Collection collection = new ArrayList();
//增加元素
collection.add("苹果");
collection.add("西瓜");
collection.add("榴莲");
collection.add("香蕉");
// System.out.println("元素个数:" + collection.size());
// System.out.println(collection);
// //删除元素
// collection.remove("西瓜");
// System.out.println(collection);
// collection.clear();
// System.out.println("清空之后:" + collection.size());
//遍历元素*
//遍历使用高级 for
for(Object object : collection) {
System.out.println(object);
}
//使用迭代器(迭代专门用来遍历集合)
Iterator it = collection.iterator();
while(it.hasNext()) {
String op = (String)it.next();
System.out.println(op);
//it.remove();
}
System.out.println(collection.size());
//判断
System.out.println(collection.contains("西瓜"));
System.out.println(collection.contains("土豆"));
System.out.println("是否为空:" + collection.isEmpty());
}
}
/*
苹果
西瓜
榴莲
香蕉
苹果
西瓜
榴莲
香蕉
4
true
false
是否为空:false
*/
保存学生信息
给集合里面添加,其实加的是地址(引用),其实删除的是地址,对象仍在堆里面;
//Student
package Demo0.Demo0_2;
/**
* 学生类
* @author dl
*/
public class Student {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
//Demo0_2
package Demo0.Demo0_2;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
/**
* Collection的使用,保存学生的信息
* @author dl
*/
public class Demo0_2 {
public static void main(String[] args) {
//新建Collection对象
Collection collection = new ArrayList();
Student s1 = new Student("dl", 21);
Student s2 = new Student("cll", 20);
Student s3 = new Student("dc", 10);
//添加数据
collection.add(s1);
collection.add(s2);
collection.add(s3);
collection.add(s1);
System.out.println(collection.size());
System.out.println(collection.toString());
//删除
// collection.remove(s1);
// collection.remove(new Student("dl", 21));
/*这个是新new的 只是和前面的属性相同 和前面的并不是一个东西 并不能删除上面的那一个*/
System.out.println("删除之后:" + collection.size());
//清空
// collection.clear();
/*这里的清空 只是对集合中的清空 原来的对象还是存在的*/
System.out.println("清空之后:" + collection.size());
//判断
System.out.println(collection.contains(s1));
//遍历
//1.增强for
for(Object object : collection) {
Student student = (Student)object;
System.out.println(student.getName() + " " + student.getAge());
}
//2.使用迭代器Iterator
Iterator it = collection.iterator();
while(it.hasNext()) {
Student student = (Student)it.next();
System.out.println(student.getName() + " " + student.getAge());
it.remove();
}
System.out.println("遍历完之后:" + collection.size());
/*在Iterator迭代器遍历的过程中 不能使用collection的remove*/
//判断是否为空
System.out.println(collection.isEmpty());
}
}
/*
4
[Student{name='dl', age=21}, Student{name='cll', age=20}, Student{name='dc', age=10}, Student{name='dl', age=21}]
删除之后:4
清空之后:4
true
dl 21
cll 20
dc 10
dl 21
dl 21
cll 20
dc 10
dl 21
遍历完之后:0
true
*/
List 继承了 Collection父类的所有方法;
特点:有序、有下标、元素可以重复
方法:
void add(int index, Object o)
//在index位置插入元素oboolean addAll(int index, Collection c)
//将一个集合中的元素添加到此集合中的index位置Object get(int index)
//返回集合中指定位置的元素List subList(int fromIndex, int toIndex)
//返回fromIndex和toIndex之间的集合元素//Demo0_3
package Demo0.Demo0_3;
/**
*List子接口的使用
* 特点:有序、有下标、可以重复
* @author dl
*/
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
public class Demo0_3 {
public static void main(String[] args) {
//创建集合
List list = new ArrayList();//实例化它的子类
//添加元素
list.add("手机");
list.add("小米");
list.add("华为");
list.add(0, "苹果");
list.add(2, "大米");//下标从 0 开始 在下标的前面添加
System.out.println("元素的个数:" + list.size());
System.out.println(list.toString());
//删除元素
list.remove(0);
System.out.println("删除之后:" + list.size());
System.out.println(list.toString());
//遍历
//使用for
for(int i = 0; i < list.size(); i ++) {
System.out.println(list.get(i));
}
//使用加强for
for(Object object : list) {
String str = (String)object;
System.out.println(str);
}
//使用迭代器Iterator
Iterator it = list.iterator();
while(it.hasNext()) {
String str = (String)it.next();
System.out.println(str);
// it.remove();
}
//使用列表迭代器listIterator 和Iterator的区别,listIterator可以向前或者向后遍历、添加、删除、修改元素
ListIterator lit = list.listIterator();
//使用列表迭代器从前往后
while(lit.hasNext()) {
System.out.println(lit.nextIndex() + ", " + lit.next());
}
//使用列表迭代器从后往前
while(lit.hasPrevious()) {
System.out.println(lit.previousIndex() + ", " + lit.previous());
}
System.out.println("遍历后的元素个数:" + list.size());
//判断是否存在
System.out.println(list.contains("小米"));
//判断是否为空
System.out.println(list.isEmpty());
//返回下标
System.out.println(list.indexOf("小米"));//下标从 0 开始
//返回元素
System.out.println(list.get(3).toString());
}
}
/*
元素的个数:5
[苹果, 手机, 大米, 小米, 华为]
删除之后:4
[手机, 大米, 小米, 华为]
手机
大米
小米
华为
手机
大米
小米
华为
手机
大米
小米
华为
0, 手机
1, 大米
2, 小米
3, 华为
3, 华为
2, 小米
1, 大米
0, 手机
遍历后的元素个数:4
true
false
2
华为
*/
//Demo0_4
package Demo0.Demo0_4;
import java.util.ArrayList;
import java.util.List;
public class Demo0_4 {
public static void main(String[] args) {
//创建集合
List list = new ArrayList();
//添加数字数据(自动装箱)
list.add(20);
list.add(30);
list.add(40);
list.add(50);
list.add(60);
System.out.println("元素个数:" + list.size());
System.out.println(list.toString());
//删除
// list.remove(0);//根据下标
list.remove(new Integer(20));
/*如果直接写20的话 这里会报错 因为超出下标范围了 所以要将20装箱 这样才能找到从而删除*/
System.out.println("删除后的元素个数:" + list.size());
System.out.println(list.toString());
//补充方法 subList()
List sublist = list.subList(1, 3);
System.out.println(sublist.toString());
}
}
/*
元素个数:5
[20, 30, 40, 50, 60]
删除后的元素个数:4
[30, 40, 50, 60]
[40, 50]
*/
ArrayList【重点】:
源码分析:
默认容量:DEFAULT_CAPACITY = 10,注意,没有向集合中添加任何元素的时候默认是 0 ,添加一个元素之后就变成了 10,超过10每次扩容为原来的1.5倍(15);
存放元素的数组:elementData;
实际的元素:size;
//Student
package Demo0.Demo0_5;
/**
* Student类
*/
public class Student {
private String name;
private int age;
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
@Override
public boolean equals(Object obj) {
if(this == obj) return true;
if(obj == null) return false;
if(obj instanceof Student) {
Student std = (Student) obj;
if(this.getAge() == ((Student) obj).getAge() && this.getName().equals(((Student) obj).getName())) {
return true;
}
}
return false;
}
}
//Demo0_5
package Demo0.Demo0_5;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;
/**
* ArrayList的使用
* 特点:有序、有下标、元素可以重复
* 存储结构:数组、查找遍历速度快,增删速度慢
* @author dl
*/
public class Demo0_5 {
public static void main(String[] args) {
//创建集合
ArrayList arrayList = new ArrayList();
//1.添加元素
Student s1 = new Student("dl", 21);
Student s2 = new Student("cll", 21);
Student s3 = new Student("cd", 10);
arrayList.add(s1);
arrayList.add(s2);
arrayList.add(s3);
System.out.println("添加后的元素数量:" + arrayList.size());
System.out.println(arrayList.toString());
//按照下标添加一个
Student s4 = new Student("ddd", 1);
arrayList.add(1, s4);
System.out.println("添加元素之后:" + arrayList.size());
System.out.println(arrayList.toString());
//2.删除元素
//根据学生类删除
arrayList.remove(s4);
System.out.println("删除之后的个数:" + arrayList.size());
System.out.println(arrayList.toString());
//根据下标删除
arrayList.remove(1);
System.out.println("删除之后的个数:" + arrayList.size());
System.out.println(arrayList.toString());
//特别注意的是下面这种做法 并不能删除元素 默认对比的是地址 当然我们自己可以重写equals 重写之后就可以正常删除了
arrayList.remove(new Student("dl", 21));
System.out.println("删除之后的个数:" + arrayList.size());
System.out.println(arrayList.toString());
arrayList.add(s2);
arrayList.add(s3);
//3.遍历元素
//简单的for遍历
for(int i = 0; i < arrayList.size(); i ++) {
Student ss = (Student) arrayList.get(i);
System.out.println(ss.getName() + ":" + ss.getAge());
}
//高级for遍历
for(Object object : arrayList) {
Student ss = (Student) object;
System.out.println(ss.getName() + ", " + ss.getAge());
}
//使用迭代器
//第一种迭代器Iterator
Iterator it = arrayList.iterator();
while(it.hasNext()) {
Student std = (Student) it.next();
System.out.println(std.getName() + "::" + std.getAge());
}
//第二种迭代器ListIterator
ListIterator lit = arrayList.listIterator();
//从前往后遍历
while(lit.hasNext()) {
Student std = (Student) lit.next();
System.out.println(std.getName() + ",," + std.getAge());
}
//从后往前遍历
while(lit.hasPrevious()) {
Student std = (Student) lit.previous();
System.out.println(std.getName() + " " + std.getAge());
}
//4.判断
System.out.println(arrayList.contains(s3));
System.out.println(arrayList.contains(new Student("cll", 21)));//因为已经改变了原来的equals 所以输出true
System.out.println(arrayList.isEmpty());
//查找
System.out.println(arrayList.get(1).toString());
System.out.println(arrayList.indexOf(s3));
System.out.println(arrayList.indexOf(new Student("cll", 21)));//因为Student类重写了equals方法
}
}
/*
添加后的元素数量:3
[Student{name='dl', age=21}, Student{name='cll', age=21}, Student{name='cd', age=10}]
添加元素之后:4
[Student{name='dl', age=21}, Student{name='ddd', age=1}, Student{name='cll', age=21}, Student{name='cd', age=10}]
删除之后的个数:3
[Student{name='dl', age=21}, Student{name='cll', age=21}, Student{name='cd', age=10}]
删除之后的个数:2
[Student{name='dl', age=21}, Student{name='cd', age=10}]
删除之后的个数:1
[Student{name='cd', age=10}]
cd:10
cll:21
cd:10
cd, 10
cll, 21
cd, 10
cd::10
cll::21
cd::10
cd,,10
cll,,21
cd,,10
cd 10
cll 21
cd 10
true
true
false
Student{name='cll', age=21}
0
1
*/
Vector:
//Demo0_6
package Demo0.Demo0_6;
import java.util.Enumeration;
import java.util.Vector;
/**
* Vector集合的使用
* 存储结构:数组
* @author dl
*/
public class Demo0_6 {
public static void main(String[] args) {
//创建集合
Vector vector = new Vector();
//1.添加元素
vector.add("草莓");
vector.add("苹果");
vector.add("西瓜");
System.out.println("元素个数:" + vector.size());
//2.删除
// vector.remove(1);
// vector.remove("西瓜");
// vector.clear();
//3.遍历
//使用枚举器
Enumeration en = vector.elements();
while(en.hasMoreElements()) {
String s = (String) en.nextElement();
System.out.println(s);
}
//4.判断
System.out.println(vector.contains("西瓜"));
System.out.println(vector.isEmpty());
//5.其他方法
// vector.firstElement();
// vector.lastElement();
// vector.elementAt();
}
}
/*
元素个数:3
草莓
苹果
西瓜
true
false
*/
LinkedList:
//Student
package Demo0.Demo0_7;
/**
* Student学生类
* @author dl
*/
public class Student {
private String name;
private int age;
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
//Demo0_7
package Demo0.Demo0_7;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.ListIterator;
/**
* LinkedList的使用
* 存储结构:双向链表
* @author dl
*/
public class Demo0_7 {
public static void main(String[] args) {
//创建集合
LinkedList linkedList = new LinkedList();
//1.添加元素
Student s1 = new Student("dl", 21);
Student s2 = new Student("cll", 21);
Student s3 = new Student("dc", 10);
linkedList.add(s1);
linkedList.add(s2);
linkedList.add(s3);
System.out.println("元素的个数:" + linkedList.size());
System.out.println(linkedList.toString());
//2.删除
linkedList.remove(s1);
System.out.println("删除之后:" + linkedList.size());
System.out.println(linkedList.toString());
// linkedList.clear();
//3.遍历
//使用for遍历
for(int i = 0; i < linkedList.size(); i ++) {
Student std = (Student) linkedList.get(i);
System.out.println(std.getName() + " , " + std.getAge());
}
//增强for
for(Object object : linkedList) {
Student std = (Student) object;
System.out.println(std.getName() + " , " + std.getAge());
}
//使用迭代器Iterator
Iterator it = linkedList.iterator();
while(it.hasNext()) {
Student std = (Student) it.next();
System.out.println(std.getName() + " , " + std.getAge());
}
//使用列表迭代器ListIterator
ListIterator lit = linkedList.listIterator();
while(lit.hasNext()) {
Student std = (Student) lit.next();
System.out.println(std.getName() + " , " + std.getAge());
}
//4.判断
System.out.println(linkedList.contains(s2));
System.out.println(linkedList.isEmpty());
//5.查询
System.out.println(linkedList.indexOf(s2));
}
}
/*
元素的个数:3
[Student{name='dl', age=21}, Student{name='cll', age=21}, Student{name='dc', age=10}]
删除之后:2
[Student{name='cll', age=21}, Student{name='dc', age=10}]
cll , 21
dc , 10
cll , 21
dc , 10
cll , 21
dc , 10
cll , 21
dc , 10
true
false
0
*/
源码分析:
集合的大小:size;
链表的头结点:Node first;
链表的尾节点:Node last;
ArrayList
必须开辟连续的空间,查询快,增删慢;
LinkedList
无需开辟连续的空间,查询慢,增删快;
Java 泛型是Jdk1.5中引入的一个新的特性,其本质是参数化类型,把类型作为参数传递;
常见的形式:泛型类、泛型接口、泛型方法;
语法:
好处:(1) 提高代码的重用性;(2) 防止类型转换异常,提高代码的安全性;
注意: 泛型只能是引用类型,不同的泛型对象之间不能相互赋值;
//MyGeneric
package Demo0.Demo0_8;
/**
* 泛型类的使用
* 语法:类名
*T是类型占位符 表示一种引用类型 可以写多个 用,隔开
* @author dl
*/
public class MyGeneric<T> {
//使用泛型T
//1.创建变量
T t;
//2.作为方法的参数
public void show(T t) {
System.out.println(t);
}
//3.泛型作为方法的返回值
public T getT() {
return t;
}
}
//TestMyGeneric
package Demo0.Demo0_8;
/**
* 使用泛型类来创建对象
* @author dl
*/
public class TestGeneric {
public static void main(String[] args) {
//使用泛型类来创建对象
MyGeneric<String> stringMyGeneric = new MyGeneric<>();
stringMyGeneric.t = "dl";
stringMyGeneric.show("大家好,加油!");
System.out.println(stringMyGeneric.getT());
MyGeneric<Integer> integerMyGeneric = new MyGeneric<>();
integerMyGeneric.t = 2;
integerMyGeneric.show(2);
System.out.println(integerMyGeneric.getT());
}
}
/*
大家好,加油!
dl
2
2
*/
//MyInterface
package Demo0.Demo0_9;
/**
* 泛型接口
* 语法:接口名
* 注意:不能泛型常量
* @author dl
*/
public interface MyInterface<T> {
String name = "dl";
T server(T t);
}
//MyInterfaceImpl_1
package Demo0.Demo0_9;
public class MyInterfaceImpl_1 implements MyInterface<String> {
@Override
public String server(String s) {
System.out.println(s);
return s;
}
}
//MyInterfaceImpl_2
package Demo0.Demo0_9;
public class MyInterfaceImpl_2 implements MyInterface<Integer>{
@Override
public Integer server(Integer integer) {
System.out.println(integer);
return integer;
}
}
//TestMyInterfaceImpl
package Demo0.Demo0_9;
public class TestMyInterfaceImpl {
public static void main(String[] args) {
MyInterfaceImpl_1 myInterfaceImpl_1 = new MyInterfaceImpl_1();
myInterfaceImpl_1.server("XXX");
MyInterfaceImpl_2 myInterfaceImpl_2 = new MyInterfaceImpl_2();
myInterfaceImpl_2.server(2);
}
}
/*
XXX
2
*/
//MyInterface
package Demo0.Demo0_9;
/**
* 泛型接口
* 语法:接口名
* 注意:不能泛型常量
* @author dl
*/
public interface MyInterface<T> {
String name = "dl";
T server(T t);
}
//MyInterfaceImpl
package Demo0.Demo0_9;
public class MyInterfaceImpl<T> implements MyInterface<T> {
@Override
public T server(T t) {
System.out.println(t);
return t;
}
}
//TestMyInterfaceImpl
package Demo0.Demo0_9;
public class TestMyInterfaceImpl {
public static void main(String[] args) {
MyInterfaceImpl<String> stringMyInterface = new MyInterfaceImpl<>();
stringMyInterface.server("XXX");
MyInterfaceImpl<Integer> integerMyInterface = new MyInterfaceImpl<>();
integerMyInterface.server(1);
}
}
/*
XXX
1
*/
类型是由传递的数据所决定的;
//MyGenericMethod
package Demo0.Demo0_10;
/**
* 泛型方法
* 语法: 返回值类型
* @author dl
*/
public class MyGenericMethod {
//泛型方法
public <T> T show(T t) {
System.out.println("泛型方法:" + t);
return t;
}
public void haha() {
}
}
//TestMyGenericMethod
package Demo0.Demo0_10;
public class TestMyGenericMethod {
public static void main(String[] args) {
MyGenericMethod myGenericMethod = new MyGenericMethod();
myGenericMethod.show("XXX");
myGenericMethod.show(2);
}
}
/*
泛型方法:XXX
泛型方法:2
*/
概念: 参数化类型、类型安全的集合、强制集合元素的类型必须一致;
特点:
//Demo0_11
package Demo0.Demo0_11;
import java.util.ArrayList;
public class Demo0_11 {
public static void main(String[] args) {
ArrayList arrayList = new ArrayList();
arrayList.add("dl");
arrayList.add("cll");
arrayList.add(1);
arrayList.add(2);
for(Object object : arrayList) {
/*不知道集合原来的类型 不能特指*/
String str = (String) object;
System.out.println(str);
}
}
}
采用泛型集合来避免类型转换错误的问题,在创建集合对象的时候,就已经确定了集合中的元素的类型;
//Student
package Demo0.Demo0_11;
public class Student {
private String name;
private int age;
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
//Demo0_11
package Demo0.Demo0_11;
import Demo0.Demo0_2.Student;
import java.util.ArrayList;
import java.util.Iterator;
public class Demo0_11 {
public static void main(String[] args) {
ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add("dl");
arrayList.add("cll");
for(String string : arrayList) {
System.out.println(string);
}
ArrayList<Student> students = new ArrayList<Student>();
Student s1 = new Student("dl", 21);
Student s2 = new Student("cll", 21);
Student s3 = new Student("dc", 21);
students.add(s1);
students.add(s2);
students.add(s3);
Iterator<Student> it = students.iterator();
while(it.hasNext()) {
Student std = it.next();
System.out.println(std.getAge() + " : " + std.getName());
}
}
}
/*
dl
cll
21 : dl
21 : cll
21 : dc
*/
特点: 无序、无下标、元素不可以重复;
方法: 全部继承自 Collection 中的方法;
//Demo1_1
package Demo1.Demo1_1;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/**
* Set接口的使用
* 特点:无序、无下标。不能重复
* @author dl
*/
public class Demo1_1 {
public static void main(String[] args) {
//创建集合
Set<String> set = new HashSet<>();
//1.添加数据
set.add("小米");
set.add("华为");
set.add("苹果");
set.add("香蕉");
set.add("华为");
System.out.println("添加元素的个数:" + set.size());
System.out.println(set.toString());
//2.删除
set.remove("华为");
System.out.println(set.toString());
// set.clear();
//3.遍历
//增强for遍历
for(String string : set) {
System.out.println(string);
}
//使用迭代器Iterator
Iterator<String> it = set.iterator();
while(it.hasNext()) {
System.out.println(it.next());
}
//4.判断
System.out.println(set.contains("华为"));
System.out.println(set.isEmpty());
}
}
/*
添加元素的个数:4
[苹果, 香蕉, 华为, 小米]
[苹果, 香蕉, 小米]
苹果
香蕉
小米
苹果
香蕉
小米
false
false
*/
//Demo1_2_1
package Demo1.Demo1_2;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
/**
* HashSet集合的使用
* 存储结构:哈希表(数组+链表+红黑树)
* @author dl
*/
public class Demo1_2 {
public static void main(String[] args) {
//1.新建集合
HashSet<String> hashSet = new HashSet<>();
//2.添加元素
hashSet.add("小明");
hashSet.add("张三");
hashSet.add("李四");
hashSet.add("XXX");
hashSet.add("XXX");
System.out.println("元素的个数:" + hashSet.size());
System.out.println(hashSet.toString());
//2.删除
hashSet.remove("XXX");
System.out.println("输出后的元素:" + hashSet.size());
System.out.println(hashSet.toString());
// hashSet.clear();
//3.遍历
//增强for
for(String string : hashSet) {
System.out.println(string);
}
//使用迭代器Iterator
Iterator<String> it = hashSet.iterator();
while(it.hasNext()) {
System.out.println(it.next());
}
//4.判断
System.out.println(hashSet.contains("XXX"));
System.out.println(hashSet.isEmpty());
}
}
/*
元素的个数:4
[李四, 张三, 小明, XXX]
输出后的元素:3
[李四, 张三, 小明]
李四
张三
小明
李四
张三
小明
false
false
*/
存储过程:
(1)根据hashcode计算保存的位置,如果此位置为空,那么直接保存,要是此位置不为空,则执行第二步;
(2)再执行equals,如果equals方法为true,则认为是重复,否则,形成链表;
//Person
package Demo1.Demo1_2;
public class Person {
private String name;
private int age;
public Person() {
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
@Override
public int hashCode() {
int num1 = this.name.hashCode();
int num2 = this.age;
return num1 + num2;
}
@Override
public boolean equals(Object obj) {
if(this == obj) return true;
if(obj == null) return false;
if(obj instanceof Person) {
Person p = (Person) obj;
if(this.name.equals(p.name) && this.age == p.age) {
return true;
}
}
return false;
}
}
//Demo1_2_2
package Demo1.Demo1_2;
import java.util.HashSet;
import java.util.Iterator;
/**
* HashSet的使用
* 存储结构:哈希表
* @author dl
*/
public class Demo1_2_2 {
public static void main(String[] args) {
//1.创建集合
HashSet<Person> stringHashSet = new HashSet<>();
//2.添加数据
Person p1 = new Person("小明", 21);
Person p2 = new Person("小丁", 20);
Person p3 = new Person("小柴", 21);
stringHashSet.add(p1);
stringHashSet.add(p2);
stringHashSet.add(p3);
stringHashSet.add(new Person("小丁", 20));
/*这样添加的元素和p2添加的元素都可以添加进去 为了避免这种情况 可以重写 hashcode方法来避免这种情况*/
System.out.println("元素个数:" + stringHashSet.size());
System.out.println(stringHashSet.toString());
//2.删除元素
stringHashSet.remove(p1);
stringHashSet.remove(new Person("小丁", 20));//可以删掉 因为重写了hashcode和equals
System.out.println("删除之后:" + stringHashSet.size());
System.out.println(stringHashSet.toString());
//3.遍历
//增强for遍历
for(Person person : stringHashSet) {
System.out.println(person);
}
//使用迭代器Iterator
Iterator<Person> it = stringHashSet.iterator();
while(it.hasNext()) {
System.out.println(it.next().getName());
}
//4.判断
System.out.println(stringHashSet.contains(new Person("小柴", 21)));//true 因为重写了hashcode和equals
}
}
/*
元素个数:3
[Person{name='小柴', age=21}, Person{name='小丁', age=20}, Person{name='小明', age=21}]
删除之后:1
[Person{name='小柴', age=21}]
Person{name='小柴', age=21}
Person{name='小柴', age=21}
true
*/
重写hashcode和equals的注意点
public static int hashCode(Object a[]) {
if (a == null)
return 0;
int result = 1;
for (Object element : a)
result = 31 * result + (element == null ? 0 : element.hashCode());
return result;
}
这里是31的原因:
(1)31是质数,可以减少散列冲突(使得计算的哈希值尽量不一样);
(2)可以提高执行效率(31*i = (i << 5) - i);
基本操作:
//Demo1_3
package Demo1.Demo1_3;
import java.util.Iterator;
import java.util.TreeSet;
/**
* TreeSet的使用
* 存储结构:红黑树
* @author dl
*/
public class Demo1_3 {
public static void main(String[] args) {
//创建集合
TreeSet<String> treeSet = new TreeSet<>();
//1.添加元素
treeSet.add("aaa");
treeSet.add("fff");
treeSet.add("ccc");
treeSet.add("ccc");
System.out.println("元素的个数:" + treeSet.size());
System.out.println(treeSet.toString());
//2.删除
treeSet.remove("ccc");
System.out.println("删除之后:" + treeSet.size());
System.out.println(treeSet.toString());
//3.遍历
//增强for
for(String string : treeSet) {
System.out.println(string);
}
//使用迭代器
Iterator<String> it = treeSet.iterator();
while(it.hasNext()) {
System.out.println(it.next());
}
//4.判断
System.out.println(treeSet.contains("aaa"));
System.out.println(treeSet.isEmpty());
}
}
/*
元素的个数:3
[aaa, ccc, fff]
删除之后:2
[aaa, fff]
aaa
fff
aaa
fff
true
false
*/
对象是类的操作:
//Person
package Demo1.Demo1_3;
import java.util.Comparator;
public class Person implements Comparable<Person> {
private String name;
private int age;
public Person() {
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
/*先按照姓名来比家 再按照年龄来比较*/
@Override
public int compareTo(Person o) {
int num1 = this.getName().compareTo(o.getName());
int num2 = this.getAge() - o.getAge();
return num1 == 0 ? num2 : num1;
}
}
//Demo1_3_2
package Demo1.Demo1_3;
import java.util.TreeSet;
/**
* TreeSet保存数据
* 存储结构:红黑树
* 元素必须实现Comparable接口 自定义比较方式
* CompareTo方法返回值为 0 则认为是重复元素
* @author dl
*/
public class Demo1_3_2 {
public static void main(String[] args) {
//创建集合
TreeSet<Person> treeSet = new TreeSet<>();
//1.添加元素
Person p1 = new Person("dl", 21);
Person p2 = new Person("dl", 20);
Person p3 = new Person("cll", 21);
Person p4 = new Person("dc", 20);
treeSet.add(p1);
treeSet.add(p2);
treeSet.add(p3);
treeSet.add(p4);
System.out.println("元素的个数:" + treeSet.size());
System.out.println(treeSet.toString());
//2.删除
treeSet.remove(p2);
treeSet.remove(new Person("dl", 21));
/*也可以删除 我们重写的compareTo方法比较的是name和age*/
System.out.println("元素的个数:" + treeSet.size());
System.out.println(treeSet.toString());
//3.遍历
//增强for
//使用迭代器Iterator
//4.判断
}
}
/*
元素的个数:4
[Person{name='cll', age=21}, Person{name='dc', age=20}, Person{name='dl', age=20}, Person{name='dl', age=21}]
元素的个数:2
[Person{name='cll', age=21}, Person{name='dc', age=20}]
*/
Comparator接口:
可以不用实现上述的 Comparator 接口;
//Person
package Demo1.Demo1_4;
public class Person {
private String name;
private int age;
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
public Person() {
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
//Demo1_4
package Demo1.Demo1_4;
import Demo1.Demo1_3.Person;
import java.util.Comparator;
import java.util.TreeSet;
/**
* TreeSet集合的使用
* Comparator:实现定制比较(比较器)
* Comparable:可比较的
* @author dl
*/
public class Demo1_4 {
public static void main(String[] args) {
//创建集合 并指定比较规则
TreeSet<Person> treeSet = new TreeSet<>(new Comparator<Person>() {
@Override
public int compare(Person o1, Person o2) {
int num1 = o1.getAge() - o2.getAge();
int num2 = o1.getName().compareTo(o2.getName());
return num1 == 0 ? num2 : num1;
}
});
//1.添加元素
Person p1 = new Person("dl", 21);
Person p2 = new Person("dl", 20);
Person p3 = new Person("cll", 21);
Person p4 = new Person("dc", 20);
treeSet.add(p1);
treeSet.add(p2);
treeSet.add(p3);
treeSet.add(p4);
System.out.println("元素的个数:" + treeSet.size());
System.out.println(treeSet.toString());
//2.删除
treeSet.remove(p2);
treeSet.remove(new Person("dl", 21));
/*也可以删除 我们重写的compareTo方法比较的是name和age*/
System.out.println("元素的个数:" + treeSet.size());
System.out.println(treeSet.toString());
//3.遍历
//增强for
//使用迭代器Iterator
//4.判断
}
}
/*
元素的个数:4
[Person{name='dc', age=20}, Person{name='dl', age=20}, Person{name='cll', age=21}, Person{name='dl', age=21}]
元素的个数:2
[Person{name='dc', age=20}, Person{name='cll', age=21}]
*/
使用treeSet 实现字符串长度的比较,若字符串的长相同,则按照默认字典排序
//Demo1_5
package Demo1.Demo1_5;
import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;
/**
* treeSet的使用
* comparator自制
* @author dl
*/
public class Demo1_5 {
public static void main(String[] args) {
TreeSet<String> treeSet = new TreeSet<>(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
int num1 = o1.length() - o2.length();
int num2 = o1.compareTo(o2);
return num1 == 0 ? num2 : num1;
}
});
treeSet.add("abcd");
treeSet.add("abc");
treeSet.add("acc");
treeSet.add("ccc");
treeSet.add("cccdddd");
Iterator<String> it = treeSet.iterator();
while(it.hasNext()) {
System.out.println(it.next());
}
}
}
/*
abc
acc
ccc
abcd
cccdddd
*/
特点: 存储一对数据(Key-Value),无序,无下标,键不可以重复,值可以重复;
方法:
V put(K key, V value)
//将对象存入到集合当中,关联键值,key重复则覆盖原值;
Object get(Object key)
//根据键获取对应的值;
Set
//返回所有key;
Collection
//返回包含所有值的Collection集合;
Set
//键值匹配的Set集合;
注意: entrySet 的效率要高于 keySet;
//Demo2_1
package Demo2;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
* Map接口的使用
* 特点:使用的键值对,key 无序、无下标、不可以重复 value 无序、无下标、可以重复 无序
* @author dl
*/
public class Demo2_1 {
public static void main(String[] args) {
//创建Map集合
Map<Integer, String> map = new HashMap<>();
//1.添加元素
map.put(1, "dl");
map.put(2, "cll");
map.put(3, "dc");
map.put(3, "cn");
map.put(4, "dc");
System.out.println("元素个数:" + map.size());
System.out.println(map.toString());
System.out.println("=========");
//2.删除元素
map.remove(3);
System.out.println("删除之后:" + map.size());
System.out.println(map.toString());
System.out.println("=========");
//遍历
//使用keySet
Set<Integer> keyset = map.keySet();
for(Integer integer : keyset) {
System.out.println(integer + " " + map.get(integer));
}
System.out.println("=========");
//使用entrySet()方法
Set<Map.Entry<Integer, String>> entrySet = map.entrySet();
for(Map.Entry<Integer, String> entries : entrySet) {
System.out.println(entries.getKey() + " " + entries.getValue());
}
System.out.println("=========");
//使用迭代器
Iterator<Map.Entry<Integer, String>> it = map.entrySet().iterator();
while(it.hasNext()) {
Map.Entry<Integer, String> str = (Map.Entry<Integer, String >) it.next();
System.out.println(str.getKey() + " " + str.getValue());
}
System.out.println("=========");
//判断
System.out.println(map.containsValue("dl"));
}
}
/*
元素个数:4
{1=dl, 2=cll, 3=cn, 4=dc}
=========
删除之后:3
{1=dl, 2=cll, 4=dc}
=========
1 dl
2 cll
4 dc
=========
1 dl
2 cll
4 dc
=========
1 dl
2 cll
4 dc
=========
true
*/
HashMap【重点】
JDK1.2版本,线程不安全,运效率快,允许用null,作为key或者 是value;
//Student
package Demo2.Demo2_2;
import java.util.Objects;
public class Student {
private String name;
private String iphone;
public Student() {
}
public Student(String name, String iphone) {
this.name = name;
this.iphone = iphone;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIphone() {
return iphone;
}
public void setIphone(String iphone) {
this.iphone = iphone;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return name.equals(student.name) && iphone.equals(student.iphone);
}
@Override
public int hashCode() {
return Objects.hash(name, iphone);
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", iphone='" + iphone + '\'' +
'}';
}
}
//Demo2_2
package Demo2.Demo2_2;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
* HashMap的使用
* 存储结构:哈希表(数组+链表+红黑树)
* @author dl
*/
public class Demo2_2 {
public static void main(String[] args) {
//创建集合
HashMap<Student, String> hashMap = new HashMap<>();
//1.添加元素
Student p1 = new Student("dl", "1934010");
Student p2 = new Student("cll", "2034010");
Student p3 = new Student("dc", "2134010");
hashMap.put(p1, "大三");
hashMap.put(p2, "大二");
hashMap.put(p3, "大一");
hashMap.put(new Student("dl", "1934010"), "大三");
/*为了让这个加不进来,可以重写hashcode和equals方法*/
System.out.println("元素个数:" + hashMap.size());
System.out.println(hashMap.toString());
System.out.println("================");
//2.删除
hashMap.remove(p3);
System.out.println("元素个数:" + hashMap.size());
System.out.println(hashMap.toString());
System.out.println("================");
//3.遍历
//使用keySet
Set<Student> keyset = hashMap.keySet();
for(Student key : keyset) {
System.out.println(key.getName() + " " + key.getIphone());
}
System.out.println("================");
//使用entrySet
Set<Map.Entry<Student, String>> entries = hashMap.entrySet();
for(Map.Entry<Student, String> entryset : entries) {
System.out.println(entryset.getKey().getName() + " " + entryset.getKey().getIphone() + " " + entryset.getValue());
}
System.out.println("================");
//使用迭代器
Iterator<Map.Entry<Student, String>> it = hashMap.entrySet().iterator();
while(it.hasNext()) {
Map.Entry<Student, String> str = (Map.Entry<Student, String>) it.next();
System.out.println(str.getKey().getName() + " " + str.getKey().getIphone() + " " + str.getValue());
}
System.out.println("================");
//判断
System.out.println(hashMap.containsKey(p2));
System.out.println(hashMap.containsKey(new Student("cll", "2034010")));
}
}
/*
元素个数:3
{Student{name='dl', iphone='1934010'}=大三, Student{name='cll', iphone='2034010'}=大二, Student{name='dc', iphone='2134010'}=大一}
================
元素个数:2
{Student{name='dl', iphone='1934010'}=大三, Student{name='cll', iphone='2034010'}=大二}
================
dl 1934010
cll 2034010
================
dl 1934010 大三
cll 2034010 大二
================
dl 1934010 大三
cll 2034010 大二
================
true
true
*/
源码分析:
刚创建hashmap的时候,没有添加任何的元素,table=null,size=0,目的是为了节省空间;
Hashtable
JDK1.0版本,线程安全,运行效率慢,不允许null作为key或是value;
Properties
Hashtable的子类,要求key和value都是String。通常用于配置文件的读取;
TreeMap
实现了SortedMap接口(是Map的子接口),可以对key自动排序;
//Student
package Demo2.Demo2_3;
import java.util.Objects;
public class Student implements Comparable<Student>{
private String name;
private int age;
@Override
public int compareTo(Student o) {
int num1 = this.name.compareTo(o.name);
int num2 = this.age - o.age;
return num2 == 0 ? num1 : num2;
}
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
//Demo2_3_1
package Demo2.Demo2_3;
import java.util.TreeMap;
/**
* TreeMap的使用
* 存储结构:红黑树
* @author dl
*/
public class Demo2_3_1 {
public static void main(String[] args) {
//新建集合
TreeMap<Student, String> treemap = new TreeMap<>();
//1.添加元素
Student p1 = new Student("dl", 1934010);
Student p2 = new Student("cll", 2034010);
Student p3 = new Student("dc", 2134010);
treemap.put(p1, "大三");
treemap.put(p2, "大二");
treemap.put(p3, "大一");
treemap.put(new Student("dc", 2134010), "大一");
System.out.println("元素个数:" + treemap.size());
System.out.println(treemap.toString());
System.out.println("================");
//删除
treemap.remove(p1);
treemap.remove(new Student("cll", 2034010), "大二");
System.out.println("元素个数:" + treemap.size());
System.out.println(treemap.toString());
System.out.println("================");
//遍历
//keySet遍历
//entrySet遍历
//判断
System.out.println(treemap.containsKey(new Student("dc", 2134010)));
}
}
/*
元素个数:3
{Student{name='dl', age=1934010}=大三, Student{name='cll', age=2034010}=大二, Student{name='dc', age=2134010}=大一}
================
元素个数:1
{Student{name='dc', age=2134010}=大一}
================
true
*/
使用自制的comparator作比较;
//Student
package Demo2.Demo2_3;
import java.util.Objects;
public class Student implements Comparable<Student>{
private String name;
private int age;
@Override
public int compareTo(Student o) {
int num1 = this.name.compareTo(o.name);
int num2 = this.age - o.age;
return num2 == 0 ? num1 : num2;
}
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
//Demo2_3_2
package Demo2.Demo2_3;
import javax.swing.text.StyledDocument;
import java.util.Comparator;
import java.util.TreeMap;
/**
* comparator 实现定制比较
*/
public class Demo2_3_2 {
public static void main(String[] args) {
TreeMap<Student, String> treemap = new TreeMap<>(new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
int num1 = o1.getName().compareTo(o2.getName());
int num2 = o1.getAge() - o2.getAge();
return num2 == 0 ? num1 : num2;
}
});
//1.添加元素
Student p1 = new Student("dl", 1934010);
Student p2 = new Student("cll", 2034010);
Student p3 = new Student("dc", 2134010);
treemap.put(p1, "大三");
treemap.put(p2, "大二");
treemap.put(p3, "大一");
treemap.put(new Student("dc", 2134010), "大四");
System.out.println("元素个数:" + treemap.size());
System.out.println(treemap.toString());
System.out.println("================");
//删除
treemap.remove(p1);
treemap.remove(new Student("cll", 2034010), "大二");
System.out.println("元素个数:" + treemap.size());
System.out.println(treemap.toString());
System.out.println("================");
//遍历
//判断
}
}
/*
元素个数:3
{Student{name='dl', age=1934010}=大三, Student{name='cll', age=2034010}=大二, Student{name='dc', age=2134010}=大四}
================
元素个数:1
{Student{name='dc', age=2134010}=大四}
================
*/
概念: 集合工具类,定义了除了存取以外的集合的常用方法;
方法:
public static void reverse(List> list)
//反转集合中元素的顺序public static void shuffle(List> list)
//随机重置集合元素的顺序public static void sort(List list)
//升序排序(元素类型必须实现Comparable接口)重点是把集合转成数组和把数组转成集合;
//Demo2_4
package Demo2.Demo2_4;
import java.util.*;
/**
* Collections 工具类的使用
* @author dl
*/
public class Demo2_4 {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
list.add(20);
list.add(5);
list.add(12);
list.add(30);
list.add(6);
//sort排序
System.out.println(list.toString());
Collections.sort(list);
System.out.println(list.toString());
//binarySearch二分查找
System.out.println(Collections.binarySearch(list, 12));
//copy复制
List<Integer> dest = new ArrayList<>();
for(int i = 0; i < list.size(); i ++) {
dest.add(null);
}
Collections.copy(dest, list);
/*需要注意的是 dest 和 list 大小必须一致 才能复制成功*/
System.out.println(dest .toString());
//reverse实现反转
Collections.reverse(list);
System.out.println(list.toString());
//shuffle 随机打乱
Collections.shuffle(list);
System.out.println(list.toString());
//***补充:list 转成数组
Integer[] arr = list.toArray(new Integer[0]);
System.out.println(arr.length);
System.out.println(Arrays.toString(arr));
//***补充:数组转成集合
Integer[] ar = new Integer[10];
for(int i = 0; i < 10; i ++) {
ar[i] = i;
}
List<Integer> li = Arrays.asList(ar);
/*此时得到的集合是受限制的 不能够进行添加和删除的操作*/
System.out.println(li.toString());
}
}
/*
[20, 5, 12, 30, 6]
[5, 6, 12, 20, 30]
2
[5, 6, 12, 20, 30]
[30, 20, 12, 6, 5]
[20, 6, 30, 12, 5]
5
[20, 6, 30, 12, 5]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
*/