目录
1.集合
一、概念:
对象的容器,定义了对多个对象进行操作的常用方法。可实现数组的功能。
二、和数组的区别:
(1)数组长度固定,集合长度不固定
(2)数组可以存储基本类型和引用类型,集合只能存储引用类型
三、Collection体系集合
1.特点:
是该体系结构的根接口,代表一组任意类型的对象,无序、无下标、不能重复
2.List接口的特点:
有序、有下标、元素可重复
3.Set接口的特点:
无序、无下标、元素不能重复
4.方法
方法名 | 注释 |
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) | 在此集合中移除o对象 |
int size() | 返回此集合中的元素个数 |
Object[ ] toArray() | 将此集合转换成数组 |
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
/**
* collection接口的使用
* (1)添加元素
* (2)删除元素
* (3)遍历元素
* (4)判断
*/
public class Demo01 {
public static void main(String[] args) {
//创建集合
Collection collection=new ArrayList<>();
//(1)添加元素
collection.add("苹果");
collection.add("香蕉");
collection.add("西瓜");
collection.add("芒果");
System.out.println("元素个数:"+collection.size());
System.out.println(collection);
//(2)删除元素
collection.remove("苹果");
System.out.println("删掉后的元素个数:"+collection.size());
System.out.println("删掉后的数组为:"+collection);
//collection.clear(); 清空数组
//(3)遍历元素【重点】
//**3.1 使用增强for
System.out.println("======3.1使用增强for=====");
for(Object object :collection){
System.out.println(object);
}
//**3.2 使用迭代器(迭代器专门用来遍历集合的一种方式)
//*** hasNext();有没有下一个元素
//*** next();获取下一个元素
//*** remove();删除当前元素
System.out.println("======3.2 使用迭代器=====");
Iterator it = collection.iterator();
while(it.hasNext()){
String s =(String)it.next();
System.out.println(s);
//collection.remove(s); (不允许使用collection方法来删除,会报并发修改的错误)
//it.remove(); 但可以使用自身的删除方法
}
//System.out.println("删掉后的元素个数:"+collection.size());
//(4)判断
System.out.println(collection.contains("西瓜"));//判断是否含有
System.out.println(collection.isEmpty());//判断是否为空
}
}
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
/**
* Collection的使用:保存学生的信息
*/
public class Demo02 {
public static void main(String[] args) {
//新建Collection对象
Collection collection = new ArrayList();
Student s1 = new Student("张三",20);
Student s2 = new Student("张无忌",56);
Student s3 = new Student("李彤",23);
//1.添加数据 (可以重复添加)
collection.add(s1);
collection.add(s2);
collection.add(s3);
System.out.println("元素个数:"+collection.size());
System.out.println(collection.toString());
//2.删除
collection.remove(s1);//可行
//collection.remove(new Student(""张三",20)); 不可行
//collection.clear();//清空
System.out.println("删除后的元素个数:"+collection.size());
System.out.println(collection.toString());
//3.遍历
//3.1 增强for
System.out.println("======3.1使用增强for=====");
for(Object object : collection){
Student s=(Student)object;
System.out.println(s.toString());
}
//3.2迭代器: hasNext() next() remove() 迭代过程中不能使用collection的删除方法
System.out.println("======3.2迭代器=====");
Iterator it = collection.iterator();
while(it.hasNext()){
Student s= (Student) it.next();
System.out.println(s.toString());
}
//4.判断
System.out.println(collection.contains(s1));//判断是否含有
System.out.println(collection.isEmpty());//判断是否为空
}
}
//学生类
class Student{
private String name ;
private int age;
public Student(String name, int age) {
super();
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 + '}';
}
}
四、List集合
1、List接口的特点:
有序、有下标、元素可重复。
2、方法
方法名 | 注释 |
void add(int index ,Object o) | 在index位置插入对象o |
boolean addAll(int index, Collection c) | 将一个集合中的元素添加到此集合中的index位置 |
Object get (int index) | 返回集合中指定位置的元素 |
List subList(int fromIndex,int toIndex) | 返回fromIndex和toIndex之间的集合元素 |
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
//List 子接口的使用
//特点:1.有序、有下标 2.可重复
public class List_01 {
public static void main(String[] args) {
//先创建集合对象
List list =new ArrayList<>();
//1.添加元素
list.add("西瓜");
list.add("苹果");
list.add(0,"芒果");
list.add("香蕉");
list.add("葡萄");
list.add("桑葚");
list.add("树莓");
System.out.println("元素个数:" + list.size());
System.out.println(list.toString());
//2.删除元素
//list.remove("苹果");
list.remove(2);
System.out.println("删除过后的元素个数为:" + list.size());
System.out.println(list.toString());
//3.遍历
//3.1使用for遍历
System.out.println("========3.1使用for遍历=========");
for(int i=0;i<list.size();i++){
System.out.println(list.get(i)); //根据角标打印对应元素
}
//3.2使用增强for遍历
System.out.println("========3.2使用增强for遍历=========");
for(Object object:list){
System.out.println(object);
}
//3.3使用迭代器
System.out.println("========3.3使用迭代器=========");
Iterator it = list.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
//3.4使用列表迭代器,和Iterator的区别:listIterator可以向前或向后遍历,增加、删除、修改元素
ListIterator a=list.listIterator();
System.out.println("========3.4.1使用列表迭代器从前往后=========");
while(a.hasNext()){
System.out.println(a.nextIndex()+":"+a.next());
}
System.out.println("========3.4.2使用列表迭代器从后往前=========");
while(a.hasPrevious()){
System.out.println(a.previousIndex()+":"+a.previous());
}
//4.判断
System.out.println(list.contains("西瓜"));
System.out.println(list.isEmpty());
//5.获取位置
System.out.println(list.indexOf("芒果"));
//6.补充方法subList,返回子集合 含头不含尾
List subList =list.subList(1,4);
System.out.println(subList.toString());
}
}
2.List实现类
(1)ArrayList 【重点】
- 数组结构实现,查询快、增删慢;
- JDK1.2版本,运行效率快、线程不安全。
import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;
//ArrayList的使用
//存储结构:数组,查询号遍历速度快,增删慢
//特点:有序、有下标、可重复
public class demo03 {
public static void main(String[] args) {
//创建集合
ArrayList arrayList=new ArrayList<>();
//1.添加元素
Student s1=new Student("amber",20);
Student s2=new Student("krystal",16);
Student s3=new Student("luna",18);
Student s4=new Student("宋茜",24);
Student s5=new Student("沙河",56);
arrayList.add(s1);
arrayList.add(s2);
arrayList.add(s3);
arrayList.add(s4);
arrayList.add(s5);
System.out.println("元素个数:" + arrayList.size());
System.out.println(arrayList.toString());
//2.删除元素
//arrayList.remove(s5);
arrayList.remove(new Student("沙河",56));//不可以直接用,需要在Student类中使用equals方法重写
System.out.println("删掉后的元素个数:" + arrayList.size());
System.out.println(arrayList.toString());
//3.遍历元素【重点】
//3.1使用for遍历
System.out.println("========3.1使用for遍历=========");
for(int i=0;i<arrayList.size();i++){
System.out.println(arrayList.get(i)); //根据角标打印对应元素
}
//3.2使用增强for遍历
System.out.println("========3.2使用增强for遍历=========");
for(Object object:arrayList){
System.out.println(object);
}
//3.3使用迭代器
System.out.println("========3.3使用迭代器=========");
Iterator it = arrayList.iterator();
while(it.hasNext()){
Student s=(Student)it.next();
System.out.println(s.toString());
}
//3.4使用列表迭代器,和Iterator的区别:listIterator可以向前或向后遍历,增加、删除、修改元素
ListIterator b=arrayList.listIterator();
System.out.println("========3.4.1使用列表迭代器从前往后=========");
while(b.hasNext()){
System.out.println(b.nextIndex()+":"+b.next());
}
System.out.println("========3.4.2使用列表迭代器从后往前=========");
while(b.hasPrevious()){
System.out.println(b.previousIndex()+":"+b.previous());
}
//4.判断
System.out.println(arrayList.contains(s1));
System.out.println(arrayList.contains(new Student("krystal",16))); //因为重写了方法,所以现在可以使用
System.out.println(arrayList.isEmpty());
//5.查找
System.out.println(arrayList.indexOf(new Student("krystal",16)));
}
}
class Student {
private String name ;
private int age;
public Student(String name, int age) {
super();
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) {
//1.判断是不是同一个对象
if(this==obj){
return true;
}
//2.判断是否为空
if(obj==null){
return false;
}
//3.判断是否是Student类型
if(obj instanceof Student){
Student s=(Student)obj;
//4.比较属性
if(this.name.equals(s.getName())&&this.age==s.getAge()){
return true;
}
}
//5.不满足条件返回false
return false;
}
}
(2)Vector:
- 数组结构实现,查询快、增删慢;
- JDK1.0版本,运行效率慢、线程安全
import java.util.Enumeration;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.Vector;
//Vector集合的使用
//存储结构:数组
public class demo04 {
public static void main(String[] args) {
//创建集合
Vector vector =new Vector<>();
//1.添加元素
vector.add("草莓");
vector.add("西瓜");
vector.add("蓝莓");
vector.add("芒果");
vector.add("苹果");
System.out.println("元素个数:" + vector.size());
System.out.println(vector.toString());
//2.删除
vector.remove(0);//可行
//vector.remove("苹果"); 不可行
//vector.clear();//清空
//System.out.println("删除后的元素个数:"+vector.size());
//System.out.println(vector.toString());
//3.遍历元素【重点】
//3.1使用for遍历
System.out.println("========3.1使用for遍历=========");
for(int i=0;i<vector.size();i++){
System.out.println(vector.get(i)); //根据角标打印对应元素
}
//3.2使用增强for遍历
System.out.println("========3.2使用增强for遍历=========");
for(Object object:vector){
System.out.println(object);
}
//3.3使用迭代器
System.out.println("========3.3使用迭代器=========");
Iterator it = vector.iterator();
while(it.hasNext()){
Student s=(Student)it.next();
System.out.println(s.toString());
}
//3.4使用列表迭代器,和Iterator的区别:listIterator可以向前或向后遍历,增加、删除、修改元素
ListIterator b=vector.listIterator();
System.out.println("========3.4.1使用列表迭代器从前往后=========");
while(b.hasNext()){
System.out.println(b.nextIndex()+":"+b.next());
}
System.out.println("========3.4.2使用列表迭代器从后往前=========");
while(b.hasPrevious()){
System.out.println(b.previousIndex()+":"+b.previous());
}
//3.5使用枚举器
Enumeration en =vector.elements();
while (en.hasMoreElements()){
String o = (String)en.nextElement();
System.out.println(o);
}
//4.判断
System.out.println(vector.contains("西瓜"));
System.out.println(vector.isEmpty());
//5.vector的其他的方法
//firstElement\lastElement\elementAt();
}
}
(3)LinkedList:
- 链表结构实现,增删快,查询慢
import java.sql.SQLOutput;
import java.util.*;
//LinkedList的使用
//存储结构:双向链表
public class demo05 {
public static void main(String[] args) {
//创建集合
LinkedList linkedList =new LinkedList<>();
//1.添加元素
Student s1=new Student("amber",20);
Student s2=new Student("krystal",16);
Student s3=new Student("luna",18);
Student s4=new Student("宋茜",24);
Student s5=new Student("沙河",56);
linkedList.add(s1);
linkedList.add(s2);
linkedList.add(s3);
linkedList.add(s4);
linkedList.add(s5);
System.out.println("元素个数:" + linkedList.size());
System.out.println(linkedList.toString());
//2.删除
linkedList.remove(4);//可行
//linkedList.remove("沙河",56); 不可行,但重写了equals方法,则可以
//linkedList.clear();//清空
//System.out.println("删除后的元素个数:"+linkedList.size());
//System.out.println(linkedList.toString());
//3.遍历元素【重点】
//3.1使用for遍历
System.out.println("========3.1使用for遍历=========");
for(int i=0;i<linkedList.size();i++){
System.out.println(linkedList.get(i)); //根据角标打印对应元素
}
//3.2使用增强for遍历
System.out.println("========3.2使用增强for遍历=========");
for(Object object:linkedList){
System.out.println(object);
}
//3.3使用迭代器
System.out.println("========3.3使用迭代器=========");
Iterator it = linkedList.iterator();
while(it.hasNext()){
Student s=(Student)it.next();
System.out.println(s.toString());
}
//3.4使用列表迭代器,和Iterator的区别:listIterator可以向前或向后遍历,增加、删除、修改元素
ListIterator b=linkedList.listIterator();
System.out.println("========3.4.1使用列表迭代器从前往后=========");
while(b.hasNext()){
System.out.println(b.nextIndex()+":"+b.next());
}
System.out.println("========3.4.2使用列表迭代器从后往前=========");
while(b.hasPrevious()){
System.out.println(b.previousIndex()+":"+b.previous());
}
//4.判断
System.out.println(linkedList.contains(new Student("krystal",16)));
System.out.println(linkedList.contains(s3));
System.out.println(linkedList.isEmpty());
//5.获取
System.out.println(linkedList.indexOf(s1));
}
}
(4)ArrayList和LinkedList区别
- ArrayList:必须要开辟连续空间,查询快,增删慢
- LinkedList: 无需开辟连续空间,查询慢,增删快。
3.Set集合
(1)Set子接口
- 特点:无序、无下标、元素不可重复
- 方法:全部继承自Collection中的方法
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/**
* 测试Set接口的使用
*/
public class Set_01 {
public static void main(String[] args) {
//创建集合
Set<String> set = new HashSet<>();
//(1)添加元素
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.size());
System.out.println("删掉后的数组为:" + set.toString());
//collection.clear(); 清空数组
//(3)遍历元素【重点】
//**3.1 使用增强for
System.out.println("======3.1使用增强for=====");
for (Object object : set) {
System.out.println(object);
}
//**3.2 使用迭代器(迭代器专门用来遍历集合的一种方式)
//*** hasNext();有没有下一个元素
//*** next();获取下一个元素
//*** remove();删除当前元素
System.out.println("======3.2 使用迭代器=====");
Iterator it = set.iterator();
while (it.hasNext()) {
String s = (String) it.next();
System.out.println(s);
//collection.remove(s); (不允许使用collection方法来删除,会报并发修改的错误)
//it.remove(); 但可以使用自身的删除方法
}
//System.out.println("删掉后的元素个数:"+collection.size());
//(4)判断
System.out.println(set.contains("西瓜"));//判断是否含有
System.out.println(set.isEmpty());//判断是否为空
}
}
(2)HashSet 【重点】
- 基于HashCode计算元素存放位置
- 当存入元素的哈希码相同时,会调用equals进行确认,如结果为true,则拒绝后者存入。
import java.util.HashSet;
import java.util.Iterator;
/**
* HashSet集合的使用
* 存储结构:哈希表(数组+链表+红黑树)
*
*/
public class HashSet_01 {
public static void main(String[] args) {
//新建集合
HashSet<String> h1=new HashSet<String>();
//1.添加元素,重复添加相同数不会添加到集合中
h1.add("张俪");
h1.add("郑秀妍");
h1.add("于文文");
h1.add("刘恋");
h1.add("赵梦");
h1.add("张天爱");
h1.add("张三");
System.out.println("======1原集合======");
System.out.println("元素个数:" + h1.size());
System.out.println(h1.toString());
//2.删除
System.out.println("======2删除======");
h1.remove("张三");
//h1.clear();清空
System.out.println("删除后的元素个数:" + h1.size());
System.out.println(h1.toString());
//3.遍历元素
//3.1增强for
System.out.println("======3.1增强for======");
for(String string:h1){
System.out.println(string);
}
//3.2迭代器
System.out.println("======3.2迭代器======");
Iterator<String> it= h1.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
//4.判断
System.out.println("======4判断======");
System.out.println(h1.contains("于文文"));
System.out.println(h1.isEmpty());
}
}
import Oop.Static.Person;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Objects;
/**
* HashSet的使用
* 存储结构:哈希表(数组+链表+红黑树)
* 存储过程
* (1)根据hashcode,计算保存的位置,如果此位置为空,则直接保存,如果不为空,则执行第二步
* (2)再执行equals方法,如果equals方法为true,则认为是重复的,否则,形成链表
*/
public class HashSet_02 {
public static void main(String[] args) {
//创建集合
HashSet<Student> student=new HashSet<>();
//1.添加数据
Student p1=new Student("郑秀晶",22);
Student p2=new Student("郑秀妍",33);
Student p3=new Student("赵梦",34);
Student p4=new Student("张三",52);
student.add(p1);
student.add(p2);
student.add(p3);
student.add(p4);
student.add(new Student("郑秀晶",22));//重写了hashcode和equals方法,不能再添加重复的
System.out.println("======1原集合======");
System.out.println("元素个数:" + student.size());
System.out.println(student.toString());
//2.删除
System.out.println("======2删除======");
student.remove(p4);
//student.clear();清空
System.out.println("删除后的元素个数:" + student.size());
System.out.println(student.toString());
//3.遍历元素
//3.1增强for
System.out.println("======3.1增强for======");
for(Object object:student){
System.out.println(object);
}
//3.2迭代器
System.out.println("======3.2迭代器======");
Iterator<Student> it= student.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
//4.判断
System.out.println("======4判断======");
System.out.println(student.contains(new Student("郑秀妍",33)));
System.out.println(student.isEmpty());
}
}
//学生类
class Student {
private String name ;
private int age;
public Student(String name, int age) {
super();
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) {
//1.判断是不是同一个对象
if(this==obj){
return true;
}
//2.判断是否为空
if(obj==null){
return false;
}
//3.判断是否是Student类型
if(obj instanceof Student){
Student s=(Student)obj;
//4.比较属性
if(this.name.equals(s.getName())&&this.age==s.getAge()){
return true;
}
}
//5.不满足条件返回false
return false;
}
@Override
public int hashCode() {
int n1=this.name.hashCode();
int n2=this.age;
return n1+n2;
}
}
(3)TreeSet:
- 基于排列顺序实现元素不重复
- 实现了SortedSet接口,对集合元素自动排序
- 元素对象的类型必须实现Comparable接口,指定排序规则
- 通过CompareTo方法确定是否为重复元素
import java.util.Iterator;
import java.util.TreeSet;
/**
* TreeSet的使用
* 存储结构:红黑树
*/
public class TreeSet_01 {
public static void main(String[] args) {
//创建集合
TreeSet<String> ts=new TreeSet<>();
//1.添加元素,重复添加相同数不会添加到集合中
ts.add("张俪");
ts.add("郑秀妍");
ts.add("于文文");
ts.add("刘恋");
ts.add("赵梦");
ts.add("张天爱");
ts.add("张三");
System.out.println("======1原集合======");
System.out.println("元素个数:" + ts.size());
System.out.println(ts.toString());
//2.删除
System.out.println("======2删除======");
ts.remove("张三");
//h1.clear();清空
System.out.println("删除后的元素个数:" + ts.size());
System.out.println(ts.toString());
//3.遍历元素
//3.1增强for
System.out.println("======3.1增强for======");
for(String string:ts){
System.out.println(string);
}
//3.2迭代器
System.out.println("======3.2迭代器======");
Iterator<String> it= ts.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
//4.判断
System.out.println("======4判断======");
System.out.println(ts.contains("于文文"));
System.out.println(ts.isEmpty());
}
}
import java.util.Iterator;
import java.util.TreeSet;
import java.util.Objects;
/**
* 使用TreeSet保存数据
* 存储结构:红黑树
* 要求:元素必须要实现Comparable接口,CompareTo()方法返回值为0,认为是重复元素
*/
public class TreeSet_02 {
public static void main(String[] args) {
//创建集合
TreeSet<Student> student =new TreeSet<>();
//1.添加元素
Student p1=new Student("郑秀晶",22);
Student p2=new Student("郑秀妍",33);
Student p3=new Student("赵梦",34);
Student p4=new Student("张三",52);
student.add(p1);
student.add(p2);
student.add(p3);
student.add(p4);
System.out.println("======1原集合======");
System.out.println("元素个数:" + student.size());
System.out.println(student.toString());
//2.删除
System.out.println("======2删除======");
student.remove(p4);
//student.clear();清空
System.out.println("删除后的元素个数:" + student.size());
System.out.println(student.toString());
//3.遍历元素
//3.1增强for
System.out.println("======3.1增强for======");
for(Object object:student){
System.out.println(object);
}
//3.2迭代器
System.out.println("======3.2迭代器======");
Iterator<Student> it= student.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
//4.判断
System.out.println("======4判断======");
System.out.println(student.contains(new Student("郑秀妍",33)));
System.out.println(student.isEmpty());
}
}
class Student implements Comparable<Student >{
private String name ;
private int age;
public Student(String name, int age) {
super();
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 int compareTo(Student o) {
int n1=this.getName().compareTo(o.getName());
int n2=this.age-o.getAge();
return n1==0?n2:n1;
}
}
import java.util.Comparator;
import java.util.TreeSet;
/**
* TreeSet集合的使用
* Comparator:实现定制比较(比较器)
* Comparable:可比较的
*/
public class TreeSet_03 {
public static void main(String[] args) {
//创建集合,并指定比较规则
TreeSet<Student> student =new TreeSet<>(new Comparator<Student>(){
@Override
public int compare(Student o1, Student o2) {
int n1= o1.getAge()-o2.getAge();
int n2=o1.getName().compareTo(o2.getName());
return n1==0?n2:n1;
}
});
//1.添加元素
Student p1=new Student("郑秀晶",22);
Student p2=new Student("郑秀妍",33);
Student p3=new Student("赵梦",34);
Student p4=new Student("张三",52);
student.add(p1);
student.add(p2);
student.add(p3);
student.add(p4);
System.out.println("======1原集合======");
System.out.println("元素个数:" + student.size());
System.out.println(student.toString());
}
}
class Student implements Comparable<Student >{
private String name ;
private int age;
public Student(String name, int age) {
super();
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 int compareTo(Student o) {
int n1=this.getName().compareTo(o.getName());
int n2=this.age-o.getAge();
return n1==0?n2:n1;
}
}
import java.util.Comparator;
import java.util.TreeSet;
/**
* 要求:使用TreeSet集合实现字符串按照字符串长度进行排序
* helloworld zhang lisi wangwu beijing xian nanjing chongqing
* 使用Comparator接口实现定制比较
*
**/
public class TreeSet_04 {
public static void main(String[] args) {
//创建集合,并设定规则
TreeSet<String> ts =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;
}
});
//添加数据
ts.add("helloworld");
ts.add("zhang");
ts.add("lisi");
ts.add("wangwu");
ts.add("beijing");
ts.add("xian");
ts.add("nanjing");
ts.add("chongqing");
System.out.println(ts.size());
System.out.println(ts.toString());
}
}
4.泛型
(1)定义与规则
- Java泛型是JDK1.5中引入的一个新特性,其本质是参数化类型,把类型作为参数传递。
- 常见形式有泛型类、泛型接口、泛型方法。
- 语法:<T, . . .> T称为类型占位符,表示一种引用类型。
- 好处: 1)提高代码的重用性 2)防止类型转换异常,提高代码的安全性
(2)泛型类:
语法:类名<T> T是类型占位符,表示一种引用类型,如果编写多个使用逗号隔开
使用泛型类创建对象注意:
1、泛型只能使用引用类型
2、不同泛型类型对象之间不能相互赋值
/*
泛型类
语法:类名<T>
T是类型占位符,表示一种引用类型,如果编写多个使用逗号隔开
*/
public class demo01<T> {
public static void main(String[] args) {
//使用泛型类创建对象
//注意:1、泛型只能使用引用类型,2.不同泛型类型对象之间不能相互赋值
demo01<String> d1=new demo01<String>();
d1.t="hello";
d1.show("大家好,加油");
String string =d1.getT();
demo01<Integer> d2 =new demo01<Integer>();
d2.t=100;
d2.show(200);
Integer integer=d2.getT();
}
//使用泛型T
//1、创建变量
T t;
//2、泛型作为方法的参数
public void show(T t){
//T t1=new T(); 注意 :泛型不能实例化,不能new
System.out.println(t);
}
//3、泛型作为方法的返回值
public T getT() {
return t;
}
}
(3)泛型接口
/**
* 泛型接口
* 语法:接口名<T>
* 注意:不能泛型静态常量
*/
public interface demo02<T> {
public static void main(String[] args) {
Imp1 imp1=new Imp1();
imp1.server("sdfgh");
Imp2 imp2=new Imp2();
imp2.server("dfghj");
}
String name="张三";
public T server(T t);
}
class Imp1 implements demo02<String>{
@Override
public String server(String s) {
System.out.println(s);
return s;
}
}
class Imp2<T> implements demo02<T> {
@Override
public T server(T t) {
System.out.println(t);
return t;
}
}
(4)泛型方法
/*
泛型方法
语法:<T> 返回值类型
*/
public class demo03 {
//泛型方法
public <T> T show(T t){
System.out.println("泛型方法"+t);
return t ;
}
public static void main(String[] args) {
demo03 d3=new demo03();
d3.show("中国加油");
d3.show(200);
d3.show(3.14);
}
}
(5)泛型集合
概念:
参数化类型、类型安全的集合,强制集合元素的类型必须一致。
特点:
(1)编译时即可检查,而非运行时抛出异常
(2)访问是,不必类型转换(拆箱)
(3)不同泛型之间引用不能相互赋值,泛型不存在多态
import java.util.ArrayList;
public class demo04 {
public static void main(String[] args) {
ArrayList arrayList =new ArrayList<>();
arrayList.add("xxx");
arrayList.add("bbb");
arrayList.add(123);
arrayList.add(456);
for(Object object:arrayList){
System.out.println(object);
}
}
}
5.Map集合
(1)结构:
(2)Map接口的特点:
(1)用于存储任意键值对
(2)键:无序、无下标、不允许重复(唯一)
(3)值:无序、无下标、允许重复
(3)方法
方法名 | 注释 |
V put(K key, V value) | 将对象存入到集合中,关联键值。key重复则覆盖原值。 |
Object get(Object key) | 根据键获取对应的值。 |
keySet<K> | 返回所有key。 |
Collection<V> values() | 返回包含所有值的Collection集合 |
Set<Map.Entry<K,V>> | 键值匹配的Set集合 |
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* Map接口的使用
* 特点:(1)存储键值对(2)键不能重复,值可以重复(3)无序
*/
public class map_01 {
public static void main(String[] args) {
//创建Map集合
Map<String,String> map=new HashMap<>();
//1.增加元素
//map.put(K,V) 当添加重复的K时,后添加的V,会覆盖之前的V
map.put("krystal","郑秀晶");
map.put("amber","刘逸云");
map.put("jessica","郑秀妍");
map.put("kelly","于文文");
map.put("asd","是大海");
System.out.println("======1原集合======");
System.out.println("元素个数:" + map.size());
System.out.println(map.toString());
//2.删除
System.out.println("======2删除======");
map.remove("asd");
//student.clear();清空
System.out.println("删除后的元素个数:" + map.size());
System.out.println(map.toString());
//3.遍历元素【重点】
//3.1使用keySet()【key】
System.out.println("======3.1使用keySet()======");
Set<String> keyset=map.keySet();
for (String key:keyset){
System.out.println(key+"----"+map.get(key));
}
//3.2使用entrySet() 【映射对】
//【entrySet效率要高于keySet】
System.out.println("======3.2使用entrySet()======");
Set<Map.Entry<String,String>> entries = map.entrySet();
for(Map.Entry<String,String> entry : entries){
System.out.println(entry.getKey()+"----"+entry.getValue());
}
//4.判断
System.out.println("======4判断======");
System.out.println(map.containsKey("krystal"));
System.out.println(map.isEmpty());
}
}
(4)HashMap【重点】
- JDK1.2版本,线程不安全,运行效率快;允许用null作为key或是value。
- 构造一个具有默认初始容量(16)和默认加载因子(0.75)的空HashMap。
- 当元素个数大于阈值(16*0.75=12)时,会进行扩容,扩容后的大小为原来的两倍,目的是减少调整元素的个数。
- jdk1.8 当每个链表长度大于8,并且元素个数大于等于64时,会调整为红黑树,目的是提高执行效率
- jdk1.8 当链表长度小于6时,调整成链表
- jdk1.8 以前,链表是头插入;jdk1.8以后是尾插入
import java.util.Objects;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* HashMap集合的使用
* 存储结构:哈希表(数组+链表+红黑树)
* 使用 key 可以 hashcode 和 equals作为重复
*/
public class HashMap_01 {
public static void main(String[] args) {
//创建集合
HashMap<Student,String> student=new HashMap<Student,String>();
//1.添加元素【不能重复添加】
Student p1=new Student("郑秀晶",22);
Student p2=new Student("郑秀妍",33);
Student p3=new Student("赵梦",34);
Student p4=new Student("张三",52);
student.put(p1,"洛杉矶");
student.put(p2,"韩国");
student.put(p3,"山东");
student.put(p4,"中国");
System.out.println("======1原集合======");
System.out.println("元素个数:" + student.size());
System.out.println(student.toString());
//2.删除
System.out.println("======2删除======");
student.remove(p4);
//student.clear();清空
System.out.println("删除后的元素个数:" + student.size());
System.out.println(student.toString());
//3.遍历元素【重点】
//3.1使用keySet()【key】
System.out.println("======3.1使用keySet()======");
for (Student key:student.keySet()){
System.out.println(key.toString()+"----"+student.get(key));
}
//3.2使用entrySet() 【映射对】
//【entrySet效率要高于keySet】
System.out.println("======3.2使用entrySet()======");
for(Map.Entry<Student,String> entry : student.entrySet()){
System.out.println(entry.getKey()+"----"+entry.getValue());
}
//4.判断
System.out.println("======4判断======");
System.out.println(student.containsKey(p2));
System.out.println(student.containsKey(new Student("郑秀妍",33)));
System.out.println(student.containsValue("北京"));
System.out.println(student.isEmpty());
}
}
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 o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return age == student.age && name.equals(student.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
}
(5)Hashtable和Properties
1)Hashtable:
- jdk1.0版本,线程安全,运行效率慢,不允许null作为key或是value。
2)Properties:
- Hashtable的子类,要求key和value都是String。通常用于配置文件的读取。
(6)TreeMap:
- 实现了SortedMap接口(是Map的子接口),可以对key自动排序
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
/**
* TreeMap的使用
* 存储结构:红黑树
*/
public class TreeMap_01 {
public static void main(String[] args) {
//新建集合
TreeMap<Student,String> treeMap=new TreeMap<Student,String>();
//1.添加元素
Student p1=new Student("郑秀晶",22);
Student p2=new Student("郑秀妍",33);
Student p3=new Student("赵梦",34);
Student p4=new Student("张三",52);
treeMap.put(p1,"洛杉矶");
treeMap.put(p2,"韩国");
treeMap.put(p3,"山东");
treeMap.put(p4,"中国");
System.out.println("======1原集合======");
System.out.println("元素个数:" + treeMap.size());
System.out.println(treeMap.toString());
//2.删除
System.out.println("======2删除======");
treeMap.remove(p4);
//student.clear();清空
System.out.println("删除后的元素个数:" + treeMap.size());
System.out.println(treeMap.toString());
//3.1使用keySet()【key】
System.out.println("======3.1使用keySet()======");
for (Student key:treeMap.keySet()){
System.out.println(key.toString()+"----"+treeMap.get(key));
}
//3.2使用entrySet() 【映射对】
//【entrySet效率要高于keySet】
System.out.println("======3.2使用entrySet()======");
for(Map.Entry<Student,String> entry : treeMap.entrySet()){
System.out.println(entry.getKey()+"----"+entry.getValue());
}
//4.判断
System.out.println("======4判断======");
System.out.println(treeMap.containsKey(p2));
System.out.println(treeMap.containsKey(new Student("郑秀妍",33)));
System.out.println(treeMap.containsValue("北京"));
System.out.println(treeMap.isEmpty());
}
}
6.Colletions工具类
(1)概念:
集合工具类,定义了除了存取以外的集合常用方法。
(2)方法:
方法名 | 解释 |
public static void reverse(List<?> list) | 反转集合中元素的顺序 |
public static void shuffle(List<?> list) | 随机重置集合元素的顺序 |
public static void sort(List<T> list) | 升序排序(元素类型必须实现Comparable接口) |
import java.util.*;
/**
* 演示Collections工具类的使用
*/
public class demo01 {
public static void main(String[] args) {
List<Integer> list=new ArrayList<>();
list.add(29);
list.add(2);
list.add(4);
list.add(56);
list.add(37);
list.add(18);
list.add(35);
//sort排序
System.out.println("排序之前:"+list.toString());
Collections.sort(list);
System.out.println("排序之后:"+list.toString());
//binarySearch 二分查找
int i=Collections.binarySearch(list,18);
System.out.println(i);
//copy 复制
List<Integer> dest =new ArrayList<>();
for(int k=0;k<list.size();k++){
dest.add(0);
}
Collections.copy(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));
//数组转为集合
String[] names={"张三","李四","王五"};
//集合是一个受限集合,不能添加和删除
List<String > list2=Arrays.asList(names);
//list2.add("赵六");
//list2.remove(0);
System.out.println(list2);
//把基本类型数组转成集合时,需要修改为包装类型
Integer[] nums={100,200,300,400,500};
List<Integer> list3=Arrays.asList(nums);
System.out.println(list3);
}
}