实验1 集合遍历
一、实验目的
实现字符串类型集合元素的遍历并输出
二、实验内容
编写程序,分别使用List、set集合存放学生的姓名,遍历并输出。
现有班级学生5人,姓名分别是:zhangsan、lisi、tom,jack、mick,又转来一名学生,姓名为zhangsan。将学生姓名存储到ArrayList集合、HashSet集合、TreeSet集合,采用普通for循环、增强for循环、Iterator迭代器等方法分别对集合信息遍历输出。
三、程序代码
ArrayList集合
import java.util.ArrayList;
import java.util.Iterator;
public class Collection1 {
public static void main(String[] args) {
ArrayList<String>list = new ArrayList<String>();
list.add("zhangsan");
list.add("lisi");
list.add("tom");
list.add("jack");
list.add("mick");
System.out.print("ArrayList集合for循环输出:");
for(int i=0;i<list.size();i++) {
System.out.print(list.get(i)+"\t");}
System.out.print("\n");
System.out.print("ArrayList集合增强for循环输出:");
for(String e:list) {System.out.print(e+"\t");}
System.out.print("\n");
System.out.print("ArrayList集合Iterator迭代器输出:");
Iterator<String>iterator = list.iterator();
while(iterator.hasNext()) {
System.out.print(iterator.next()+"\t");}
System.out.print("\n");
System.out.println("-------------------");
list.add("zhangsan");
System.out.print("转来学生后for循环输出:");
for(int i=0;i<list.size();i++) {
System.out.print(list.get(i)+"\t");}
System.out.print("\n");
System.out.print("转来学生后增强for循环输出:");
for(String e:list) {System.out.print(e+"\t");}
System.out.print("\n");
System.out.print("转来学生后Iterator迭代器输出:");
Iterator<String>iterator1 = list.iterator();
while(iterator1.hasNext()) {
System.out.print(iterator1.next()+"\t");}
}
}
HashSet集合
import java.util.HashSet;
import java.util.Iterator;
public class Collection2 {
public static void main(String[] args) {
HashSet<String>ht = new HashSet<String>();
ht.add("zhangsan");
ht.add("lisi");
ht.add("tom");
ht.add("jack");
ht.add("mick");
System.out.println("HashSet集合for循环输出:");
for(int i=0;i<ht.size();i++) {
System.out.println(ht.toString());}
System.out.print("HashSet集合增强for循环输出:");
for(String e:ht) {System.out.print(e+"\t");}
System.out.print("\n");
System.out.print("HashSet集合Iterator迭代器输出:");
Iterator<String>iterator = ht.iterator();
while(iterator.hasNext()) {
System.out.print(iterator.next()+"\t");}
System.out.print("\n");
System.out.println("-------------------");
ht.add("zhangsan");
System.out.println("转来学生后for循环输出:");
for(int i=0;i<ht.size();i++) {
System.out.println(ht.toString());}
System.out.print("转来学生后增强for循环输出:");
for(String e:ht) {System.out.print(e+"\t");}
System.out.print("\n");
System.out.print("转来学生后Iterator迭代器输出:");
Iterator<String>iterator1 = ht.iterator();
while(iterator1.hasNext()) {
System.out.print(iterator1.next()+"\t");}
}
}
TreeSet集合
import java.util.Iterator;
import java.util.TreeSet;
public class Collection3 {
public static void main(String[] args) {
TreeSet<String>it = new TreeSet<String>();
it.add("zhangsan");
it.add("lisi");
it.add("tom");
it.add("jack");
it.add("mick");
System.out.println("TreeSet集合for循环输出:");
for(int i=0;i<it.size();i++) {
System.out.println(it.toString());}
System.out.print("TreeSet集合增强for循环输出:");
for(String e:it) {System.out.print(e+"\t");}
System.out.print("\n");
System.out.print("TreeSet集合Iterator迭代器输出:");
Iterator<String>iterator = it.iterator();
while(iterator.hasNext()) {
System.out.print(iterator.next()+"\t");}
System.out.print("\n");
System.out.println("-------------------");
it.add("zhangsan");
System.out.println("转来学生后for循环输出:");
for(int i=0;i<it.size();i++) {
System.out.println(it.toString());}
System.out.print("转来学生后增强for循环输出:");
for(String e:it) {System.out.print(e+"\t");}
System.out.print("\n");
System.out.print("转来学生后Iterator迭代器输出:");
Iterator<String>iterator1 = it.iterator();
while(iterator1.hasNext()) {
System.out.print(iterator1.next()+"\t");}
}
}
实验2 图书信息查看
一、实验目的
实现对象类型集合元素的遍历并输出
二、实验内容
分别使用List、set集合和Map存放多个图书信息,遍历并输出。其中商品属性:编号,名称,单价,出版社。
三、程序代码
1.用ArrayList实现图书信息的遍历并输出
import java.util.ArrayList;
import java.util.List;
class Boook//创建图书类
{ public int id;
public String name;
public double price;
public String press;
public Boook(){super();}
public Boook(int id, String name, double price, String press)
{ super();
this.id = id;
this.name = name;
this.price = price;
this.press = press;}
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 getPrice()
{return price;}
public void setPrice(double price)
{this.price = price;}
public String getPress()
{return press;}
public void setPress(String press)
{this.press = press;}
public String toString()
{return "Book [id=" + id + ", name=" + name +
", press=" + press+ ", price=" + price + "]";}}
public class TestList {
public static void main(String[] args)
{//创建集合中的元素图书对象
Boook b1 = new Boook(1000, "b1", 30.5, "bjsxt");
Boook b1_1 = new Boook(1000, "b1", 30, "bjsxt");
Boook b2 = new Boook(1000, "b2", 50, "bjsxt");
Boook b3 = new Boook(1001, "b3", 30.5, "bjsxt");
Boook b4 = new Boook(1002, "b4", 30.5, "bjsxt");
Boook b5 = new Boook(1003, "b5", 50, "bjsxt");
//使用ArrayList存储图书并遍历
List<Boook> bookList = new ArrayList<Boook>();
bookList.add(b1);
bookList.add(b1);
bookList.add(b2);
bookList.add(b3);
bookList.add(b4);
bookList.add(b5);
bookList.add(b1_1);
//观察结果是否有id重复的图书信息?
System.out.println("遍历输出ArrayList");
System.out.println(bookList.size());
for (Boook book : bookList)
{System.out.println(book.toString());}
}
}
2.使用HashSet和TreeSet存储多个商品信息,遍历并输出
其中商品属性:编号,名称,单价,出版社;要求向其中添加多个相同的商品,验证集合中元素的唯一性。
提示:向HashSet中添加自定义类的对象信息,需要重写hashCode和equals( )
向TreeSet中添加自定义类的对象信息,需要实现Comparable接口,指定比较规则
import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;
class Book implements Comparable<Book>
{ public int id;
public String name;
public double price;
public String press;
public Book()
{super();}
public Book(int id, String name, double price, String press)
{ super();
this.id = id;
this.name = name;
this.price = price;
this.press = press;}
public int compareTo(Book o)//重写compareTo方法
{ if(this.id<o.id) {
return -1;}
else if(this.id>o.id) {
return 1;}
else if(this.id==o.id) {
return 0;} //图书id不一致则为不同图书,并且按id值由大到小排序
return this.id-o.id;}
public int hashCode()//重写hashCode方法,确保id不同返回不同
{ final int prime = 31;
int result = 1;
result = prime * result + id;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((press == null) ? 0 : press.hashCode());
long temp;
temp = Double.doubleToLongBits(price);
result = prime * result + (int) (temp ^ (temp >>> 32));
return result;}
public boolean equals(Object obj)//重写equals方法,保证两个内容不同的两个对象返回false
{if (this == obj)
{return true;}
if (obj == null)
{return false;}
if (getClass() != obj.getClass())
{return false;}
Book other = (Book) obj;
if (id != other.id)
{return false;}
if (name == null)
{if (other.name != null)
{return false;}
} else if (!name.equals(other.name))
{return false;}
if (press == null)
{if (other.press != null)
{return false;}
} else if (!press.equals(other.press))
{return false;}
if (Double.doubleToLongBits(price) != Double
.doubleToLongBits(other.price))
{return false;}return true;}
public String toString()
{return "Book [id=" + id + ", name=" + name + ","
+ " press=" + press+ ", price=" + price + "]";}}
public class TestSet {
public static void main(String[] args)
{//创建图书对象
Book b1 = new Book(1000, "b1", 30.5, "bjsxt");
Book b1_1 = new Book(1000, "b1", 30, "bjsxt");
Book b2 = new Book(1000, "b2", 50, "bjsxt");
Book b3 = new Book(1001, "b3", 30.5, "bjsxt");
Book b4 = new Book(1002, "b4", 30.5, "bjsxt");
Book b5 = new Book(1003, "b5", 50, "bjsxt1");
//使用HashSet存储图书并遍历
Set<Book> hashSet = new HashSet<Book>();
hashSet.add(b1);
hashSet.add(b1);//观察是否b1被添加两次
hashSet.add(b2);
hashSet.add(b3);
hashSet.add(b4);
hashSet.add(b5);
hashSet.add(b1_1);//观察id为1000的图书是否被重复添加
System.out.println("遍历输出hashset");
System.out.println(hashSet.size());
for (Book book : hashSet)
{System.out.println(book.toString());}
//使用TreeSet存储图书并遍历
Set<Book> treeSet = new TreeSet<Book>();
treeSet.add(b1);
treeSet.add(b1);
treeSet.add(b2);
treeSet.add(b3);
treeSet.add(b4);
treeSet.add(b5);
treeSet.add(b1_1);
System.out.println("遍历输出treeset");//观察遍历输出的结果是否排序,如果排序,按什么数据进行的?
for (Book book : treeSet)
{System.out.println(book.toString());}
}
}
3.使用Map类实现存储图书信息并遍历输出
将图书id作为键,图书对象作为值,实现Map集合存储数据
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
class Bbook
{ public int id;
public String name;
public double price;
public String press;
public Bbook()
{super();}
public Bbook(int id, String name, double price, String press)
{ super();
this.id = id;
this.name = name;
this.price = price;
this.press = press;
}
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 getPrice()
{return price;}
public void setPrice(double price)
{this.price = price;}
public String getPress()
{return press;}
public void setPress(String press)
{this.press = press;}
public String toString()
{return "Book [id=" + id + ", name=" + name + ""
+ ", press=" + press+ ", price=" + price + "]";
}
}
public class TestMap {
public static void main(String[] args)
{//创建集合中的元素图书对象
Bbook b1 = new Bbook(1000, "b1", 30.5, "bjsxt");
Bbook b1_1 = new Bbook(1000, "b1", 30, "bjsxt");
Bbook b2 = new Bbook(1000, "b2", 50, "bjsxt");
Bbook b3 = new Bbook(1001, "b3", 30.5, "bjsxt");
Bbook b4 = new Bbook(1002, "b4", 30.5, "bjsxt");
Bbook b5 = new Bbook(1003, "b5", 50, "bjsxt1");
//使用Map存储图书并遍历
Map<Integer, Bbook> bookMap = new HashMap<Integer, Bbook>();
bookMap.put(b1.getId(), b1);
bookMap.put(b1.getId(), b1);
bookMap.put(b2.getId(), b2);
bookMap.put(b3.getId(), b3);
bookMap.put(b4.getId(), b4);
bookMap.put(b5.getId(), b5);
bookMap.put(b1_1.getId(), b1_1);
System.out.println("遍历输出Map");//观察图书id为1000的数据在集合中出现几次?原因是什么?
for (Entry<Integer, Bbook> entry : bookMap.entrySet())
{System.out.println(entry.getKey() + "----------->" + entry.getValue());}
//Map存储的结果是否按照id值进行排序,如果没有,怎么修改程序,要求结果按照id值排序?
}
}
实验3 集合应用
一、实验目的
掌握HashMap集合的数据存储方法
二、实验内容
假如有以下email数据“aa@sohu.com,bb@163.com,cc@sina.com,..”现需要把email中的用户部分和邮件地址部分分离,分离后以键值对应的方式放入HashMap?
三、实验模板
import java.util.HashMap;
import java.util.Map;
public class EmailSplit {
public static void main(String[] args)
{
String str = "aa@sohu.com,bb@163.com,cc@sina.com";
//得到每一个email
String strs[] = str.split(",");
//存放分离后email的信息
Map<String, String> emailMap = new HashMap<String, String>();
for (String email : strs)
{ String temp[] = email.split("@");
//分割email存入map
emailMap.put(temp[0], temp[1]);
}
for(int i=0;i<strs.length;i++) {
if(i != strs.length)
System.out.println(strs[i]);
//依次遍历emailMap中的所有元素并输出
}
}
}
实验4 设计一个简单的图书管理程序
1.编写Data类代码,实现数据的增、删、改、查
import java.util.ArrayList;
public class Data {//使用缺省修饰符的Data类,实现了对主类的隐藏(封装)
private static ArrayList<Books>list = new ArrayList<Books>();
//私有字段list,不允许本类以外的任何类访问(封装)
static int query(String id) {//查询指定ID所在的索引值,返回-1表示不存在
int i = 0,index = -1;
for(Books b:list) {//遍历list集合
if(id.equals(b.id)) {
index = i;
break;
}i++;
}return index;
}static String add(Books b) {//添加图书对象
list.add(b);
return "添加成功";
}
static String editNum(String id,int num) {//更改库存数量
Books b = list.get(query(id));
b.num = b.num + num;
list.set(query(id), b);
return "要添加的图书已存在,仅更新库存";
}
static String del(String id) {//删除ArrayList中的元素
list.remove(query(id));
return "删除成功";
}
static void show (String id) {//按指定ID显示图书对象信息
Books b = list.get(query(id));
System.out.println(b.toString());
}
static void showAll() {//显示ArrayList中所有数据
if(list.size()==0) {//如果ArrayList中没有任何数据
System.out.println( "库中没有任何数据");
return;//后续代码不再执行
}
for(Books b:list) {//遍历list
System.out.println(b.toString());
}
}
}
2.编写Books类代码
public class Books {//共有的Books类
public String id,name,author;//声明Books类字段
public int num;
public boolean chkID(String id) {//用于检查ID格式是否为合法的chkID()方法
char first = id.charAt(0);//取出ID中第一个字符
return Character.isLetter(first)&&id.length()==6;
}//第一位是一个字母并且长度为6,则返回ture,否则false
public String add() {//用于添加图书对象的方法
//访问对象时无须创建类的对象,可以通过类名直接访问
//调用Data类的静态方法query()检查该图书是否已经存在,返回-1表示不存在
if(Data.query(id)==-1)
return Data.add(this);//若不存在,则调用Data.add()
else//否则调用Data.editNum()修改库存
return Data.editNum(id,num);
}
public static void show(String id) {
if(Data.query(id)==-1)//调用Data.query()判断查询ID是否存在
System.out.println("要查询的编号不存在");
else
Data.show(id);
}//若存在,则调用Data.show()显示图书信息
public static void showAll() {
Data.showAll();//调用Data.showAll()显示所有图书信息
}
public static String del(String id) {
if(Data.query(id)==-1)//调用Data.query()查询要删除的图书是否存在
return "要删除的数据不存在";
else
return Data.del(id);
}//若存在,则调用Data.del()方法删除对象
public String toString() {//重写toString()方法显示图书详细数据
return "编号:"+id+",书名:"+name+",作者:"+author+",库存:"+num;
}
}
3.编写主类中主方法的代码
import java.util.Scanner;
public class SX5 {
public static void main(String[] args) {
Scanner val = new Scanner(System.in);
boolean t = true;
while(t) {
System.out.print("1--添加 2--删除 3--查询 4--显示全部 5--退出,请选择:");
switch(val.nextInt()) {
case 1:System.out.print("输入编号,书名,作者,数量:");
Books book = new Books();
String id = val.next();
if(book.chkID(id)) {//若Id合法,则创建book对象
book.id = id;
book.name = val.next();
book.author = val.next();
book.num = val.nextInt();
}
else {
System.out.println("编号输入错误");
val.next();//读取后面的数据,避免对下一次读取造成影响
val.next();
val.next();
continue;
}//返回while语句,开始下一次循环
System.out.println(book.add());//添加图书对象,开始操作结果
break;
case 2:System.out.println("输入要删除的编号:");
System.out.println(Books.del(val.next()));break;
case 3:System.out.print("输入要查询的编号:");
Books.show(val.next());break;
case 4:Books.showAll();break;
case 5:t = false;//修改循环条件,结束循环
System.out.println("bye!");break;
}
}val.close();//关闭Scanner对象
}
}