概述:
集合:java中的集合是工具类,可以存储任意数量的具有共同属性的对象
集合的应用场景:
集合框架的体系结构:
List集合:
概念:
ArrayList:
案例:在List中存储并操作字符串信息
测试代码:
package com.imooc.set;
import java.util.ArrayList;
import java.util.List;
public class ListDemoOne {
public static void main(String[] args) {
// 用ArrayList存储编程语言的名称,并输出
List list = new ArrayList();
list.add("Java");
list.add("C");
list.add("C++");
list.add("Go");
list.add("swift");
// 输出元素的个数
System.out.println("列表中元素的个数:" + list.size());
// 遍历输出所有元素
System.out.println("******************");
System.out.println("列表元素为:");
for (int i = 0; i < list.size(); i++) {
System.out.print(list.get(i) + " ");
}
// 移除列表中的C++
// list.remove(2);
list.remove("C++");
System.out.println();
// 遍历输出所有元素
System.out.println("******************");
System.out.println("移除C++后的列表元素为:");
for (int i = 0; i < list.size(); i++) {
System.out.print(list.get(i) + " ");
}
System.out.println();
System.out.println("移除C++后的列表中元素的个数:" + list.size());
}
}
输出结果:
列表中元素的个数:5
******************
列表元素为:
Java C C++ Go swift
******************
移除C++后的列表元素为:
Java C Go swift
移除C++后的列表中元素的个数:4
案例:公告管理
代码如下:
Notices类:
package com.imooc.set;
import java.util.Date;
public class Notices {
private int id;
private String title;
private String creator;
private Date createTime;
//setter getter
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 getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
//无参构造
public Notices() {
super();
}
//多参构造
public Notices(int id, String title, String creator, Date createTime) {
super();
this.id = id;
this.title = title;
this.creator = creator;
this.createTime = createTime;
}
}
NoticeTest类:
package com.imooc.set;
import java.util.ArrayList;
import java.util.Date;
public class NoticesTest {
public static void main(String[] args) {
// 创建Notices的对象,生成三条公告
Notices notice1 = new Notices(1, "欢迎来到慕课网!", "管理员", new Date());
Notices notice2 = new Notices(2, "请同学们按时提交作业!", "老师", new Date());
Notices notice3 = new Notices(3, "考勤通知!", "老师", new Date());
// 添加公告
ArrayList noticeList = new ArrayList();
noticeList.add(notice1);
noticeList.add(notice2);
noticeList.add(notice3);
// 显示公告
System.out.println("公告的内容为:");
for (int i = 0; i < noticeList.size(); i++) {
// noticeList.get(i)返回的是一个Object类的对象,对其进行强制类型转换
System.out.println((i + 1) + ":" + ((Notices) (noticeList.get(i))).getTitle());
}
// 在第一条公告后面添加一条新公告
Notices notice4 = new Notices(4, "在线编辑器可以使用了!", "管理员", new Date());
noticeList.add(1, notice4);
System.out.println("****************************");
// 显示公告
System.out.println("添加完公告的内容为:");
for (int i = 0; i < noticeList.size(); i++) {
// noticeList.get(i)返回的是一个Object类的对象,对其进行强制类型转换
System.out.println((i + 1) + ":" + ((Notices) (noticeList.get(i))).getTitle());
}
// 删除一条公告
noticeList.remove(2);
System.out.println("****************************");
// 显示公告
System.out.println("删除完公告的内容为:");
for (int i = 0; i < noticeList.size(); i++) {
// noticeList.get(i)返回的是一个Object类的对象,对其进行强制类型转换
System.out.println((i + 1) + ":" + ((Notices) (noticeList.get(i))).getTitle());
}
System.out.println("****************************");
// 修改公告:修改第二条公告title的值-->java在线编辑器可以使用了!
notice4.setTitle("java在线编辑器可以使用了!");
noticeList.set(1, notice4);
// 显示公告
System.out.println("修改完公告的内容为:");
for (int i = 0; i < noticeList.size(); i++) {
// noticeList.get(i)返回的是一个Object类的对象,对其进行强制类型转换
System.out.println((i + 1) + ":" + ((Notices) (noticeList.get(i))).getTitle());
}
}
}
输出结果:
公告的内容为:
1:欢迎来到慕课网!
2:请同学们按时提交作业!
3:考勤通知!
****************************
添加完公告的内容为:
1:欢迎来到慕课网!
2:在线编辑器可以使用了!
3:请同学们按时提交作业!
4:考勤通知!
****************************
删除完公告的内容为:
1:欢迎来到慕课网!
2:在线编辑器可以使用了!
3:考勤通知!
****************************
修改完公告的内容为:
1:欢迎来到慕课网!
2:java在线编辑器可以使用了!
3:考勤通知!
编程练习:
Employee类:
package test009;
public class Employee {
// 根据需求完成Employee类的定义
private int id;
private String name;
private double salary;
// setter getter
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
// 无参构造
public Employee() {
super();
}
// 多参构造
public Employee(int id, String name, double salary) {
super();
this.id = id;
this.name = name;
this.salary = salary;
}
}
EmployeeTest类:
package test009;
import java.util.List;
import java.util.ArrayList;
public class EmployeeTest {
public static void main(String[] args) {
//定义ArrayList对象
ArrayList employeeList = new ArrayList();
//创建三个Employee类的对象
Employee one = new Employee(1,"张三",5000);
Employee two = new Employee(2,"李四",5500);
Employee three = new Employee(3,"赵六",4000);
//添加员工信息到ArrayList中
employeeList.add(one);
employeeList.add(two);
employeeList.add(three);
//显示员工的姓名和薪资
System.out.println("员工姓名 员工薪资");
for(int i=0;i<employeeList.size();i++) {
System.out.println(((Employee)(employeeList.get(i))).getName()+" "+((Employee)(employeeList.get(i))).getSalary());
}
}
}
输出结果:
员工姓名 员工薪资
张三 5000.0
李四 5500.0
赵六 4000.0
set集合:元素无须并且不可以重复的集合,被称为集
HashSet:
案例:
Iterator:迭代器
测试代码:
package com.imooc.set;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class WordDemo {
public static void main(String[] args) {
// 将英文单词添加到HashSet中
Set set = new HashSet();
// 向集合中添加元素
set.add("blue");
set.add("red");
set.add("black");
set.add("yellow");
set.add("white");
// 显示集合的元素
System.out.println("集合元素为:");
// 将set中元素转存到迭代器中
Iterator it = set.iterator();
// 遍历迭代器并输出元素
while (it.hasNext()) {
System.out.print(it.next() + " ");
}
// 在集合中插入一个新的元素
set.add("green");
// 插入重复元素试试,插入失败但是并不会报错
set.add("white");
System.out.println();
it = set.iterator();
// 遍历迭代器并输出元素
while (it.hasNext()) {
System.out.print(it.next() + " ");
}
}
}
输出结果:
集合元素为:
red blue white black yellow
red green blue white black yellow
案例:宠物猫信息管理
需求:
属性:
方法:
测试代码:
Cat类:
package com.imooc.pet;
public class Cat {
private String name;
private int month;
private String species;
// setter getter
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;
}
// 无参构造
public Cat() {
super();
}
public Cat(String name, int month, String species) {
this.setName(name);
this.setMonth(month);
this.setSpecies(species);
}
// 重写toString
@Override
public String toString() {
return "Cat [姓名:=" + name + ", 月份=" + month + ", 品种=" + 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;
}
@Override
public boolean equals(Object obj) {
//首先判断对象是否相同
if (this == obj)
return true;
//然后判断obj是否是Cat类的对象
if (obj.getClass() == Cat.class) {
Cat cat = (Cat) obj;
return cat.getName().equals(name)&&cat.getMonth()==month&&cat.getSpecies().equals(species);
}
return true;
}
}
CatTest类:
package com.imooc.pet;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class CatTest {
public static void main(String[] args) {
// 定义宠物猫类对象
Cat huahua = new Cat("花花", 12, "英国短毛猫");
Cat fanfan = new Cat("凡凡", 13, "中华田园猫");
Cat huahua01 = new Cat("花花", 12, "英国短毛猫");
// 将宠物猫类对象放入HashSet中
// 引进泛型概念
Set<Cat> set = new HashSet<Cat>();
set.add(huahua);
set.add(fanfan);
Iterator<Cat> it = set.iterator();
while (it.hasNext()) {
// it.next()返回的是对象在内存中的地址,应该返回对象中的内容
// 故重写toString()方法
System.out.println(it.next());
}
System.out.println("**********************");
// 添加重复数据后的宠物猫信息
set.add(huahua01);
it = set.iterator();
// 自定义类要通过重写hashCode()和equals()来防止加入重复数据
System.out.println("添加重复数据后的宠物猫信息:");
while (it.hasNext()) {
// it.next()返回的是对象在内存中的地址,应该返回对象中的内容
// 故重写toString()方法
System.out.println(it.next());
}
System.out.println("**********************");
// 重新插入一个新宠物猫
Cat huahua02 = new Cat("花花二代", 2, "英国短毛猫");
set.add(huahua02);
it = set.iterator();
System.out.println("添加新数据后的宠物猫信息:");
while (it.hasNext()) {
// it.next()返回的是对象在内存中的地址,应该返回对象中的内容
// 故重写toString()方法
System.out.println(it.next());
}
System.out.println("**********************");
// 在集合中寻找花花的信息并输出
if (set.contains(huahua)) {
System.out.println("花花找到了");
System.out.println(huahua);
} else {
System.out.println("花花未找到");
}
// 在集合中使用名字来查找花花的信息
System.out.println("**********************");
System.out.println("在集合中使用名字来查找花花的信息");
boolean flag = false;
Cat c = null;
it = set.iterator();
while (it.hasNext()) {
c = it.next();
if (c.getName().equals("花花")) {
flag = true;
break;
}
}
if (flag) {
System.out.println("花花找到了");
System.out.println(c);
} else {
System.out.println("花花未找到");
}
//删除花花二代的信息并重新输出
for (Cat cat : set) {
// 在读取数据的时候不允许删除
if ("花花二代".equals(cat.getName()))
set.remove(cat);
}
//删除年龄小于5,可以将满足这些条件的元素作为一个set1集合,然后调用set.removeAll(set1)方法;
// Set<Cat> set1 = new HashSet<Cat>();
// for (Cat cat : set) {
// // 在读取数据的时候不允许删除
// if (cat.getMonth()<5)
// set1.add(cat);
// }
// set.removeAll(set1);
System.out.println("**********************");
System.out.println("删除花花二代的信息并重新输出:");
for (Cat cat : set) {
System.out.println(cat);
}
// 删除集合中所有信息
System.out.println("**********************");
System.out.println("删除所有信息并重新输出:");
boolean flag1 = set.removeAll(set);
if (set.isEmpty()) {
System.out.println("猫都不见了。。。");
} else {
System.out.println("猫还在。。。");
}
}
}
输出结果:
Cat [姓名:=花花, 月份=12, 品种=英国短毛猫]
Cat [姓名:=凡凡, 月份=13, 品种=中华田园猫]
**********************
添加重复数据后的宠物猫信息:
Cat [姓名:=花花, 月份=12, 品种=英国短毛猫]
Cat [姓名:=凡凡, 月份=13, 品种=中华田园猫]
**********************
添加新数据后的宠物猫信息:
Cat [姓名:=花花, 月份=12, 品种=英国短毛猫]
Cat [姓名:=凡凡, 月份=13, 品种=中华田园猫]
Cat [姓名:=花花二代, 月份=2, 品种=英国短毛猫]
**********************
花花找到了
Cat [姓名:=花花, 月份=12, 品种=英国短毛猫]
**********************
在集合中使用名字来查找花花的信息
花花找到了
Cat [姓名:=花花, 月份=12, 品种=英国短毛猫]
**********************
删除花花二代的信息并重新输出:
Cat [姓名:=花花, 月份=12, 品种=英国短毛猫]
Cat [姓名:=凡凡, 月份=13, 品种=中华田园猫]
**********************
删除所有信息并重新输出:
猫都不见了。。。
Map集合:
Map:
HashMap:
案例1、
代码测试:
package com.imooc.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 DictionaryDemo {
public static void main(String[] args) {
Map<String, String> animal = new HashMap<String, String>();
System.out.println("请输入三组单词对应的注释,并存放到HashMap中:");
Scanner console = new Scanner(System.in);
int i = 0;
while (i < 3) {
System.out.println("请输入key值(单词):");
String key = console.next();
System.out.println("请输入value(注释):");
String value = console.next();
animal.put(key, value);
i++;
}
// 打印输出value的值
System.out.println("*********************");
System.out.println("使用迭代器输出所有的value:");
Iterator<String> it = animal.values().iterator();
while (it.hasNext()) {
System.out.print(it.next() + " ");
}
System.out.println();
// 打印出value和key的值
// 通过entrySet()方法完成
System.out.println("通过entrySet()方法完成key-value的输出:");
Set<Entry<String, String>> entrySet = animal.entrySet();
System.out.println("*********************");
for (Entry<String, String> entry : entrySet) {
System.out.print(entry.getKey() + "-");
System.out.println(entry.getValue());
}
// 通过单词找到注释并输出
// 使用keySet方法
System.out.println("*********************");
System.out.println("请输入要查找的单词:");
String strSearch = console.next();
//1、取得keySet
Set<String> keySet = animal.keySet();
//2、遍历keySet
for (String key:keySet) {
if(strSearch.equals(key)) {
System.out.println("找到了!");
System.out.println("键值对为:"+key+"-"+animal.get(key));
break;
}
}
}
}
输出结果:
请输入三组单词对应的注释,并存放到HashMap中:
请输入key值(单词):
one
请输入value(注释):
1
请输入key值(单词):
two
请输入value(注释):
2
请输入key值(单词):
three
请输入value(注释):
3
*********************
使用迭代器输出所有的value:
1 2 3
通过entrySet()方法完成key-value的输出:
*********************
one-1
two-2
three-3
*********************
请输入要查找的单词:
one
找到了!
键值对为:one-1
案例2:
Goods类:
package com.imooc.set;
public class Goods {
private String id;
private String name;
private double price;
//setter getter
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;
}
//无参构造
public Goods() {
}
//多参构造
public Goods(String id, String name, double price) {
super();
this.id = id;
this.name = name;
this.price = price;
}
@Override
public String toString() {
return "商品编号:" + id + ", 商品名字:" + name + ", 商品价格:" + price ;
}
}
测试代码:
package com.imooc.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);
// 定义HashMap
Map<String, Goods> goodsMap = new HashMap<String, Goods>();
System.out.println("请输入三条商品信息:");
// 循环输入商品信息
for (int i = 0; i < 3; i++) {
System.out.println("请输入第" + (i + 1) + "条商品信息:");
System.out.println("请输入商品编号:");
String goodsId = console.next();
// 判断商品编号是否存在,若存在请重新输入
if (goodsMap.containsKey(goodsId)) {
System.out.println("商品编号已存在,请重新输入!");
i--;
continue;
}
System.out.println("请输入商品名称:");
String goodsName = console.next();
System.out.println("请输入商品价格:");
double goodsPrice = 0;
try {
goodsPrice = console.nextDouble();
} catch (java.util.InputMismatchException e) {
System.out.println("商品价格格式不正确,请输入数值型数据");
console.next();//用来存放错误的数据,防止对后面输入
i--;
continue;
}
// 根据输入创建新的Goods类
Goods goods = new Goods(goodsId, goodsName, goodsPrice);
// 将goodsId设置为唯一的key值
goodsMap.put(goodsId, goods);
}
// 遍历Map,输出商品信息
System.out.println();
Iterator<Goods> itGoods = goodsMap.values().iterator();
while (itGoods.hasNext()) {
System.out.println(itGoods.next());
}
}
}
输出结果:
请输入三条商品信息:
请输入第1条商品信息:
请输入商品编号:
1
请输入商品名称:
iphone7
请输入商品价格:
3000
请输入第2条商品信息:
请输入商品编号:
2
请输入商品名称:
iphone8
请输入商品价格:
4000
请输入第3条商品信息:
请输入商品编号:
2
商品编号已存在,请重新输入!
请输入第3条商品信息:
请输入商品编号:
3
请输入商品名称:
iphoneX
请输入商品价格:
sss
商品价格格式不正确,请输入数值型数据
请输入第3条商品信息:
请输入商品编号:
3
请输入商品名称:
iphoneX
请输入商品价格:
5000
商品编号:1, 商品名字:iphone7, 商品价格:3000.0
商品编号:2, 商品名字:iphone8, 商品价格:4000.0
商品编号:3, 商品名字:iphoneX, 商品价格:5000.0
作业: