导读
1.集合简介
2.List
3.Set
4.Map
5.范型
集合简介
⚠️集合是导入java.util这个包,其他不说明的则是java.lang这个包,java.lang包不需要手动导入,会自动导入
Collection: 用于存储类的对象
Map: 以键值对的形式存储信息
-> HashMap: 哈希表
List: 表示序列,有序可重复
->ArrayList:相当于一个动态数组
Queue: 表示队列,有序可重复
->LinkList: 相当于c语言中的链表
Set: 表示集,无序不可重复
->HashSet: 哈希集
总结
add=addFirst
remove=removeLast
pop=removeFirst
poll=pollLast
peek=peekLast
first是右边的进口,last是左边的出口
TreeMap特有方法
//得到TreeMap中第一个键的值
map.fistKey()
List
ArrayList
ArrayList中的元素类型只能是引用类型
ArrayList一次性传入多个值:
package com.hala.set;
import java.util.ArrayList;
import java.util.List;
public class ListDemo {
public static void main(String[] args) {
// ArrayList方法:
//add(),size(),get(),remove()
List list=new ArrayList();
list.add("Java");
list.add("C");
list.add("C++");
list.add("Go");
list.add("swift");
System.out.println("列表中元素的个数:"+list.size());
//遍历列表中的元素
for(int i=0;i<list.size();i++){
System.out.print(list.get(i)+",");
}
System.out.println();
//删除元素
list.remove(2);
list.remove("C");
for(int i=0;i<list.size();i++){
System.out.print(list.get(i)+",");
}
}
}
输出结果
列表中元素的个数:5
Java,C,C++,Go,swift,
Java,Go,swift,
Notice类
package com.hala.set;
import java.util.Date;
public class Notice {
private int id;
private String title;
private String creator;
private Date creatTime;
public Notice(int id, String title, String creator, Date creatTime) {
super();
this.setId(id);
this.setTitle(title);
this.setCreator(creator);
this.setCreatTime(creatTime);
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getCreator() {
return creator;
}
public void setCreator(String creator) {
this.creator = creator;
}
public Date getCreatTime() {
return creatTime;
}
public void setCreatTime(Date creatTime) {
this.creatTime = creatTime;
}
}
NoticeTest类
package com.hala.set;
import java.util.ArrayList;
import java.util.Date;
public class NoticeTest {
public static void main(String[] args) {
Notice not1=new Notice(1,"欢迎来到王者荣耀!","官方",new Date());
Notice not2=new Notice(2,"欢迎来到英雄联盟!","官方",new Date());
Notice not3=new Notice(3,"欢迎来到吃鸡游戏!","官方",new Date());
Notice not4=new Notice(4,"欢迎来到网易天堂!","官方",new Date());
Notice not5=new Notice(5,"欢迎来到LOL!","官方",new Date());
ArrayList noticelist=new ArrayList();
noticelist.add(not1);
noticelist.add(not2);
noticelist.add(not3);
//显示公告
System.out.println("公告内容为:");
for(int i=0;i<noticelist.size();i++){
//这里注意 noticelist.get(i) 实际上是Object类型的,需要强制转化后才能调用getTitle()
System.out.println((i+1)+":"+((Notice)(noticelist.get(i))).getTitle());
}
//在第一条公告前添加公告
noticelist.add(0,not4);
System.out.println();
System.out.println("公告内容为:");
for(int i=0;i<noticelist.size();i++){
System.out.println((i+1)+":"+((Notice)(noticelist.get(i))).getTitle());
}
//删除公告
noticelist.remove(0);
noticelist.remove(not3);
System.out.println();
System.out.println("公告内容为:");
for(int i=0;i<noticelist.size();i++){
System.out.println((i+1)+":"+((Notice)(noticelist.get(i))).getTitle());
}
//修改公告
noticelist.set(1, not5);
System.out.println();
System.out.println("公告内容为:");
for(int i=0;i<noticelist.size();i++){
System.out.println((i+1)+":"+((Notice)(noticelist.get(i))).getTitle());
}
}
}
输出结果
公告内容为:
1:欢迎来到王者荣耀!
2:欢迎来到英雄联盟!
3:欢迎来到吃鸡游戏!
公告内容为:
1:欢迎来到网易天堂!
2:欢迎来到王者荣耀!
3:欢迎来到英雄联盟!
4:欢迎来到吃鸡游戏!
公告内容为:
1:欢迎来到王者荣耀!
2:欢迎来到英雄联盟!
公告内容为:
1:欢迎来到王者荣耀!
2:欢迎来到LOL!
ArrayList的常用方法:
->java.util
ArrayList实现了Collection接口,所以Collection有的方法它都有
add(),get(),remove(),size()上边已经介绍,不再赘述
/*
在指定的index位置设置新的值,并返回原来的值
*/
E set(int index, E element)
/*
清除其中的所有元素
*/
void clear()
遍历ArrayList的方法:
方法三:
ArrayList排序的方法:
方法一:自己写循环排序
方法二:
Comparable接口与Collections类sort()方法结合
方法三:
因为这里MyComparator的对象只是用一次,所以可以用匿名内部类来写
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/a47fd6d24d7973f2ba5282a076cadda1.png)
LinkList<>
LinkList实际上是一个堆栈的模式
poll是队列数据结构实现类的方法,从队首获取元素,同时获取的这个元素将从原队列删除;pop是栈结构的实现类的方法,表示返回栈顶的元素,同时该元素从栈中删除,当栈中没有元素时,调用该方法会发生异常
Set
HashSet的底层实现的是HashMap
package com.hala.set;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class SetDemo {
public static void main(String[] args) {
Set set=new HashSet();
//添加元素
set.add("red");
set.add("yellow");
set.add("blue");
//运用迭代器显示集合的内容
System.out.println("集合中的元素为:");
Iterator it=set.iterator();
while(it.hasNext()){
System.out.print(it.next()+" ");
}
//set如果插入重复1元素,则会插入失败,但不会报错
}
}
输出结果
集合中的元素为:
red blue yellow
Cat类
package com.hala.set;
public class Cat {
private String name;
private int month;
private String species;
public Cat(String name, int month, String species) {
super();
this.setMonth(month);
this.setName(name);
this.setSpecies(species);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getMonth() {
return month;
}
public void setMonth(int month) {
this.month = month;
}
public String getSpecies() {
return species;
}
public void setSpecies(String species) {
this.species = species;
}
//重写toString信息
@Override
public String toString() {
return "Cat [name=" + name + ", month=" + month + ", species=" + species + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + month;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((species == null) ? 0 : species.hashCode());
return result;
}
//重写equals方法
@Override
public boolean equals(Object obj) {
//判断对象是否相等,相等则直接返回true,不用在比较属性了
if (this == obj)
return true;
//如果对象不相等,则看其类别是否一样,属性是否相同
if (obj.getClass() == Cat.class) {
Cat cat = (Cat) obj;
return cat.getName().equals(name) && (cat.getMonth() == month) && (cat.getSpecies().equals(species));
}
return false;
}
}
CatTest类
package com.hala.set;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class CatTest {
public static void main(String[] args) {
Cat cat1 = new Cat("花花", 12, "英国短毛猫");
Cat cat2 = new Cat("小米", 4, "中华田园猫");
Cat cat3 = new Cat("花花",12,"英国短毛猫");
Set set = new HashSet();
//添加
set.add(cat1);
set.add(cat2);
Iterator it = set.iterator();
while (it.hasNext()) {
// 这里无需写toString方法,它会自动调用
System.out.println(it.next());
}
System.out.println();
//添加重复信息
//重写了equals方法后,对于信息相同的元素不会添加到集合中
set.add(cat3);
it=set.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
}
}
输出结果
Cat [name=小米, month=4, species=中华田园猫]
Cat [name=花花, month=12, species=英国短毛猫]
Cat [name=小米, month=4, species=中华田园猫]
Cat [name=花花, month=12, species=英国短毛猫]
对于哈希表,hashCode的作用是判别两个元素在不在一个桶中,equals的作用是判别一个桶中的元素是否相等
⚠️toString, equals, hashCode都是Object类中包含的方法,对于自定义的类需要重写这些方法,重写的快捷方式,
右键->Source->toString或者equals, hashCode
Cat类
package com.hala.set;
public class Cat {
private String name;
private int month;
private String species;
public Cat(String name, int month, String species) {
super();
this.setMonth(month);
this.setName(name);
this.setSpecies(species);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getMonth() {
return month;
}
public void setMonth(int month) {
this.month = month;
}
public String getSpecies() {
return species;
}
public void setSpecies(String species) {
this.species = species;
}
//重写toString信息
@Override
public String toString() {
return "Cat [name=" + name + ", month=" + month + ", species=" + species + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + month;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((species == null) ? 0 : species.hashCode());
return result;
}
//重写equals方法
@Override
public boolean equals(Object obj) {
//判断对象是否相等,相等则直接返回true,不用在比较属性了
if (this == obj)
return true;
//如果对象不相等,则看其类别是否一样,属性是否相同
if (obj.getClass() == Cat.class) {
Cat cat = (Cat) obj;
return cat.getName().equals(name) && (cat.getMonth() == month) && (cat.getSpecies().equals(species));
}
return false;
}
}
CatTest类
package com.hala.set;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class CatTest {
public static void main(String[] args) {
Cat cat1 = new Cat("花花", 12, "英国短毛猫");
Cat cat2 = new Cat("小米", 4, "中华田园猫");
Set set = new HashSet();
//添加
set.add(cat1);
set.add(cat2);
Iterator it = set.iterator();
while (it.hasNext()) {
// 这里无需写toString方法,它会自动调用
System.out.println(it.next());
}
System.out.println();
//使用对象名直接查找
if(set.contains(cat2)){
System.out.println("小米找到了!");
System.out.println(cat2);
}else{
System.out.println("没有这只猫猫。");
}
// 在集合中使用名字查找花花的信息
boolean flag = false;
Cat c = null;
it = set.iterator();
while (it.hasNext()) {
c = (Cat) it.next();
if (c.getName().equals("花花")) {
flag = true;
break;
}
}
if (flag == true) {
System.out.println("花花找到了!");
System.out.println(c);
} else {
System.out.println("花花没找到!");
}
}
}
输出结果
Cat [name=小米, month=4, species=中华田园猫]
Cat [name=花花, month=12, species=英国短毛猫]
小米找到了!
Cat [name=小米, month=4, species=中华田园猫]
花花找到了!
Cat [name=花花, month=12, species=英国短毛猫]
加入范型限制会去掉警告,同时下边的it.next()也不需要强制转换为Cat了
package com.hala.set;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class CatTest {
public static void main(String[] args) {
Cat cat1 = new Cat("花花", 12, "英国短毛猫");
Cat cat2 = new Cat("小米", 4, "中华田园猫");
//使用范型工具
Set<Cat> set = new HashSet<Cat>();
//添加
set.add(cat1);
set.add(cat2);
Iterator<Cat> it = set.iterator();
while (it.hasNext()) {
// 这里无需写toString方法,它会自动调用
System.out.println(it.next());
}
System.out.println();
//删除花花的信息,并输出集合
//增强的for循环,只有在使用了范型后才能用,其本质也是一种迭代器
for(Cat cat:set){
if("花花".equals(cat.getName())){
set.remove(cat);
}
}
System.out.println("删除后的信息为:");
for(Cat cat:set){
System.out.println(cat);
}
//删除集合所有的信息
set.removeAll(set);
if(set.isEmpty()){
System.out.println("猫都不见了!");
}else{
System.out.println("猫还在");
}
}
}
输出结果
Cat [name=小米, month=4, species=中华田园猫]
Cat [name=花花, month=12, species=英国短毛猫]
删除后的信息为:
Cat [name=小米, month=4, species=中华田园猫]
猫都不见了!
package com.hala.set;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class CatTest {
public static void main(String[] args) {
Cat cat1 = new Cat("花花", 12, "英国短毛猫");
Cat cat2 = new Cat("小米", 4, "中华田园猫");
//使用范型工具
Set<Cat> set = new HashSet<Cat>();
//添加
set.add(cat1);
set.add(cat2);
Iterator<Cat> it = set.iterator();
while (it.hasNext()) {
// 这里无需写toString方法,它会自动调用
System.out.println(it.next());
}
System.out.println();
//这里之所以会报错是因为在读取过程中不允许操作
//如果小米恰好是最后一个数据则不会报错,否则会出现图示错误
//解决方法,在remove后加上break;跳出
//如果要删除多条比如年龄在2以上的猫,用如下方法:
//Set<Cat> set1=new hashSet<Cat>();
//for(Cat cat:set){
//if(cat.month()>2){
// set1.add(cat);
// }
//}
//set.removeAll(set1);
for(Cat cat:set){
if("小米".equals(cat.getName())){
set.remove(cat);
}
}
System.out.println("删除后的信息为:");
for(Cat cat:set){
System.out.println(cat);
}
}
}
输出结果
Cat [name=小米, month=4, species=中华田园猫]
Exception in thread “main” Cat [name=花花, month=12, species=英国短毛猫]
java.util.ConcurrentModificationException
at java.util.HashMap
H
a
s
h
I
t
e
r
a
t
o
r
.
n
e
x
t
N
o
d
e
(
H
a
s
h
M
a
p
.
j
a
v
a
:
1437
)
a
t
j
a
v
a
.
u
t
i
l
.
H
a
s
h
M
a
p
HashIterator.nextNode(HashMap.java:1437) at java.util.HashMap
HashIterator.nextNode(HashMap.java:1437)atjava.util.HashMapKeyIterator.next(HashMap.java:1461)
at com.hala.set.CatTest.main(CatTest.java:30)
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/f811689071ca886907cb00c500ef2804.png)
Map
Key不能一对多,Value允许一对多
package com.hala.set;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.Set;
public class DictoryDemo {
public static void main(String[] args) {
Map<String,String> animal=new HashMap<String,String>();
Scanner console=new Scanner(System.in);
for(int i=0;i<3;i++){
System.out.println("请输入Key值:");
String s=console.next();
System.out.println("请输入Value值:");
String t=console.next();
//添加信息
animal.put(s, t);
}
System.out.println("使用迭代器输出所有的Value:");
Iterator<String> it=animal.values().iterator();
while(it.hasNext()){
System.out.print(it.next()+" ");
}
System.out.println();
System.out.println("以Key-Value的形式输出:");
//使用entrySet的方法
Set<Entry<String, String>> entrySet=animal.entrySet();
for(Entry<String, String> entry:entrySet){
System.out.print(entry.getKey()+"-");
System.out.println(entry.getValue());
}
}
}
输出结果
请输入Key值:
cat
请输入Value值:
猫
请输入Key值:
dog
请输入Value值:
狗
请输入Key值:
monkey
请输入Value值:
猴
使用迭代器输出所有的Value:
猴 猫 狗
以Key-Value的形式输出:
monkey-猴
cat-猫
dog-狗
⚠️快捷法写范型右键->下图第一个
package com.hala.set;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.Set;
public class DictoryDemo {
public static void main(String[] args) {
Map<String,String> animal=new HashMap<String,String>();
Scanner console=new Scanner(System.in);
for(int i=0;i<3;i++){
System.out.println("请输入Key值:");
String s=console.next();
System.out.println("请输入Value值:");
String t=console.next();
//添加信息
animal.put(s, t);
}
//通过单词查找注释并输出
//使用keySet方法
System.out.println("请输入要查找的单词:");
String strSearch=console.next();
//第一步:取得keySet
Set<String> keySet=animal.keySet();
//第二步:遍历keySet
for(String key:keySet){
if(key.equals(strSearch)){
System.out.print("找到了!"+"键值对为:"+key+"-"+animal.get(key));
break;
}
}
}
}
输出结果
请输入Key值:
cat
请输入Value值:
猫
请输入Key值:
dog
请输入Value值:
狗
请输入Key值:
monkey
请输入Value值:
猴
请输入要查找的单词:
cat
找到了!键值对为:cat-猫
Goods类
package com.hala.set;
public class Goods {
private String id;
private String name;
private double price;
public Goods(String id, String name, double price) {
super();
this.setId(id);
this.setName(name);
this.setPrice(price);
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
@Override
public String toString() {
return "Goods [id=" + id + ", name=" + name + ", price=" + price + "]";
}
}
goodsTest类
package com.hala.set;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Scanner;
public class goodsTest {
public static void main(String[] args) {
Scanner console=new Scanner(System.in);
Map<String,Goods> goodsMap=new HashMap<String,Goods>();
for (int i = 0; i < 3;) {
System.out.println("请输入第"+(i+1)+"个商品的信息~");
System.out.println("请输入商品编号:");
String goodsId = console.next();
//HashMap不允许相同的key值存在,会使后输入的信息覆盖前边的
if(goodsMap.containsKey(goodsId)){
System.out.println("该商品编号已经存在!请重新输入!");
continue;
}
System.out.println("请输入商品名称:");
String goodsName = console.next();
System.out.println("请输入商品价格:");
double goodsPrice = console.nextDouble();
Goods goods = new Goods(goodsId, goodsName, goodsPrice);
goodsMap.put(goodsId, goods);
i++;
}
//遍历商品信息
System.out.println("商品的全部信息为:");
Iterator<Goods> it=goodsMap.values().iterator();
while(it.hasNext()){
System.out.println(it.next());
}
}
}
输出结果
请输入第1个商品的信息~
请输入商品编号:
s001
请输入商品名称:
电脑
请输入商品价格:
6000
请输入第2个商品的信息~
请输入商品编号:
s001
该商品编号已经存在!请重新输入!
请输入第2个商品的信息~
请输入商品编号:
s002
请输入商品名称:
冰箱
请输入商品价格:
4000
请输入第3个商品的信息~
请输入商品编号:
s003
请输入商品名称:
洗衣机
请输入商品价格:
5000
商品的全部信息为:
Goods [id=s003, name=洗衣机, price=5000.0]
Goods [id=s002, name=冰箱, price=4000.0]
Goods [id=s001, name=电脑, price=6000.0]
范型