上机实验6 集合案例

简介: 上机实验6 集合案例

实验1 集合遍历

一、实验目的

实现字符串类型集合元素的遍历并输出

二、实验内容

编写程序,分别使用List、set集合存放学生的姓名,遍历并输出。

现有班级学生5人,姓名分别是:zhangsan、lisi、tom,jack、mick,又转来一名学生,姓名为zhangsan。将学生姓名存储到ArrayList集合、HashSet集合、TreeSet集合,采用普通for循环、增强for循环、Iterator迭代器等方法分别对集合信息遍历输出。

三、程序代码

ArrayList集合

1. import java.util.ArrayList;
2. import java.util.Iterator;
3. 
4. public class Collection1 {
5. public static void main(String[] args) {
6.  ArrayList<String>list = new ArrayList<String>();
7.  list.add("zhangsan");
8.  list.add("lisi");
9.  list.add("tom");
10.   list.add("jack");
11.   list.add("mick");
12.   System.out.print("ArrayList集合for循环输出:");
13.   for(int i=0;i<list.size();i++) {
14.     System.out.print(list.get(i)+"\t");}
15.   System.out.print("\n");
16.   System.out.print("ArrayList集合增强for循环输出:");
17.   for(String e:list) {System.out.print(e+"\t");}
18.   System.out.print("\n");
19.   System.out.print("ArrayList集合Iterator迭代器输出:");
20.   Iterator<String>iterator = list.iterator();
21.   while(iterator.hasNext()) {
22.     System.out.print(iterator.next()+"\t");}
23.   System.out.print("\n");
24.   System.out.println("-------------------");
25.   list.add("zhangsan");
26.   System.out.print("转来学生后for循环输出:");
27.   for(int i=0;i<list.size();i++) {
28.     System.out.print(list.get(i)+"\t");}
29.   System.out.print("\n");
30.   System.out.print("转来学生后增强for循环输出:");
31.   for(String e:list) {System.out.print(e+"\t");}
32.   System.out.print("\n");
33.   System.out.print("转来学生后Iterator迭代器输出:");
34.   Iterator<String>iterator1 = list.iterator();
35.   while(iterator1.hasNext()) {
36.     System.out.print(iterator1.next()+"\t");}
37. }
38. }

HashSet集合

1. import java.util.HashSet;
2. import java.util.Iterator;
3. 
4. public class Collection2 {
5. public static void main(String[] args) {
6.  HashSet<String>ht = new HashSet<String>();
7.  ht.add("zhangsan");
8.  ht.add("lisi");
9.  ht.add("tom");
10.   ht.add("jack");
11.   ht.add("mick");
12.   System.out.println("HashSet集合for循环输出:");
13.   for(int i=0;i<ht.size();i++) {
14.     System.out.println(ht.toString());}
15.   System.out.print("HashSet集合增强for循环输出:");
16.   for(String e:ht) {System.out.print(e+"\t");}
17.   System.out.print("\n");
18.   System.out.print("HashSet集合Iterator迭代器输出:");
19.   Iterator<String>iterator = ht.iterator();
20.   while(iterator.hasNext()) {
21.     System.out.print(iterator.next()+"\t");}
22.   System.out.print("\n");
23.   System.out.println("-------------------");
24.   ht.add("zhangsan");
25.   System.out.println("转来学生后for循环输出:");
26.   for(int i=0;i<ht.size();i++) {
27.     System.out.println(ht.toString());}
28.   System.out.print("转来学生后增强for循环输出:");
29.   for(String e:ht) {System.out.print(e+"\t");}
30.   System.out.print("\n");
31.   System.out.print("转来学生后Iterator迭代器输出:");
32.   Iterator<String>iterator1 = ht.iterator();
33.   while(iterator1.hasNext()) {
34.     System.out.print(iterator1.next()+"\t");}
35. }
36. }

TreeSet集合

1. import java.util.Iterator;
2. import java.util.TreeSet;
3. 
4. public class Collection3 {
5. public static void main(String[] args) {
6.  TreeSet<String>it = new TreeSet<String>();
7.  it.add("zhangsan");
8.  it.add("lisi");
9.  it.add("tom");
10.   it.add("jack");
11.   it.add("mick");
12.   System.out.println("TreeSet集合for循环输出:");
13.   for(int i=0;i<it.size();i++) {
14.     System.out.println(it.toString());}
15.   System.out.print("TreeSet集合增强for循环输出:");
16.   for(String e:it) {System.out.print(e+"\t");}
17.   System.out.print("\n");
18.   System.out.print("TreeSet集合Iterator迭代器输出:");
19.   Iterator<String>iterator = it.iterator();
20.   while(iterator.hasNext()) {
21.     System.out.print(iterator.next()+"\t");}
22.   System.out.print("\n");
23.   System.out.println("-------------------");
24.   it.add("zhangsan");
25.   System.out.println("转来学生后for循环输出:");
26.   for(int i=0;i<it.size();i++) {
27.     System.out.println(it.toString());}
28.   System.out.print("转来学生后增强for循环输出:");
29.   for(String e:it) {System.out.print(e+"\t");}
30.   System.out.print("\n");
31.   System.out.print("转来学生后Iterator迭代器输出:");
32.   Iterator<String>iterator1 = it.iterator();
33.   while(iterator1.hasNext()) {
34.     System.out.print(iterator1.next()+"\t");}
35. }
36. }

实验2 图书信息查看

一、实验目的

实现对象类型集合元素的遍历并输出

二、实验内容

分别使用List、set集合和Map存放多个图书信息,遍历并输出。其中商品属性:编号,名称,单价,出版社。

三、程序代码

1.用ArrayList实现图书信息的遍历并输出

1. import java.util.ArrayList;
2. import java.util.List;
3. 
4. class Boook//创建图书类
5. {   public int id;
6.     public String name;
7.     public double price;
8.     public String press;
9.     public Boook(){super();}
10.     public Boook(int id, String name, double price, String press)
11.     {   super();
12.         this.id = id;
13.         this.name = name;
14.         this.price = price;
15.         this.press = press;}
16.     public int getId()
17.     {return id;}
18.     public void setId(int id)
19.     {this.id = id;}
20.     public String getName()
21.     {return name;}
22.     public void setName(String name)
23.     {this.name = name;}
24.     public double getPrice()
25.     {return price;}
26.     public void setPrice(double price)
27.     {this.price = price;}
28.     public String getPress()
29.     {return press;}
30.     public void setPress(String press)
31.     {this.press = press;}
32.     public String toString()
33.     {return "Book [id=" + id + ", name=" + name +
34. ", press=" + press+ ", price=" + price + "]";}}
35. public class TestList {
36.    public static void main(String[] args)
37.       {//创建集合中的元素图书对象
38.           Boook b1 = new Boook(1000, "b1", 30.5, "bjsxt");
39.           Boook b1_1 = new Boook(1000, "b1", 30, "bjsxt");
40.           Boook b2 = new Boook(1000, "b2", 50, "bjsxt");
41.           Boook b3 = new Boook(1001, "b3", 30.5, "bjsxt");
42.           Boook b4 = new Boook(1002, "b4", 30.5, "bjsxt");
43.           Boook b5 = new Boook(1003, "b5", 50, "bjsxt");
44.           //使用ArrayList存储图书并遍历
45.           List<Boook> bookList = new ArrayList<Boook>();
46.           bookList.add(b1);
47.           bookList.add(b1);
48.           bookList.add(b2);
49.           bookList.add(b3);
50.           bookList.add(b4);
51.           bookList.add(b5);
52.           bookList.add(b1_1);
53.           //观察结果是否有id重复的图书信息?
54.           System.out.println("遍历输出ArrayList");
55.           System.out.println(bookList.size());
56.           for (Boook book : bookList)
57.           {System.out.println(book.toString());}
58.       }
59.   }

2.使用HashSet和TreeSet存储多个商品信息,遍历并输出

其中商品属性:编号,名称,单价,出版社;要求向其中添加多个相同的商品,验证集合中元素的唯一性。

提示:向HashSet中添加自定义类的对象信息,需要重写hashCode和equals( )

          向TreeSet中添加自定义类的对象信息,需要实现Comparable接口,指定比较规则

1. import java.util.HashSet;
2. import java.util.Set;
3. import java.util.TreeSet;
4. 
5. class Book implements Comparable<Book>
6. {   public int id;
7.     public String name;
8.     public double price;
9.     public String press;
10.     public Book()
11.     {super();}
12.     public Book(int id, String name, double price, String press)
13.     {   super();
14.         this.id = id;
15.         this.name = name;
16.         this.price = price;
17.         this.press = press;}
18.    public int compareTo(Book o)//重写compareTo方法
19.     {  if(this.id<o.id) {
20.      return -1;}
21.      else if(this.id>o.id) {
22.      return 1;}
23.      else if(this.id==o.id) {
24.      return 0;} //图书id不一致则为不同图书,并且按id值由大到小排序
25.      return this.id-o.id;}
26.     public int hashCode()//重写hashCode方法,确保id不同返回不同
27.     {   final int prime = 31;
28.         int result = 1;
29.         result = prime * result + id;
30.         result = prime * result + ((name == null) ? 0 : name.hashCode());
31.         result = prime * result + ((press == null) ? 0 : press.hashCode());
32.         long temp;
33.         temp = Double.doubleToLongBits(price);
34.         result = prime * result + (int) (temp ^ (temp >>> 32));
35. return result;}
36.     public boolean equals(Object obj)//重写equals方法,保证两个内容不同的两个对象返回false
37.     {if (this == obj)
38.         {return true;}
39. if (obj == null)
40.         {return false;}
41. if (getClass() != obj.getClass())
42.         {return false;}
43.         Book other = (Book) obj;
44. if (id != other.id)
45.         {return false;}
46. if (name == null)
47.         {if (other.name != null)
48.             {return false;}
49.         } else if (!name.equals(other.name))
50.         {return false;}
51. if (press == null)
52.         {if (other.press != null)
53.             {return false;}
54.         } else if (!press.equals(other.press))
55.         {return false;}
56. if (Double.doubleToLongBits(price) != Double
57.                 .doubleToLongBits(other.price))
58.         {return false;}return true;}
59.     public String toString()
60.     {return "Book [id=" + id + ", name=" + name + ","
61. + " press=" + press+ ", price=" + price + "]";}}
62. public class TestSet {
63.    public static void main(String[] args)
64.       {//创建图书对象
65.           Book b1 = new Book(1000, "b1", 30.5, "bjsxt");
66.           Book b1_1 = new Book(1000, "b1", 30, "bjsxt");
67.           Book b2 = new Book(1000, "b2", 50, "bjsxt");
68.           Book b3 = new Book(1001, "b3", 30.5, "bjsxt");
69.           Book b4 = new Book(1002, "b4", 30.5, "bjsxt");
70.           Book b5 = new Book(1003, "b5", 50, "bjsxt1");
71.           //使用HashSet存储图书并遍历
72.           Set<Book> hashSet = new HashSet<Book>();
73.           hashSet.add(b1);
74.           hashSet.add(b1);//观察是否b1被添加两次
75.           hashSet.add(b2);
76.           hashSet.add(b3);
77.           hashSet.add(b4);
78.           hashSet.add(b5);
79.           hashSet.add(b1_1);//观察id为1000的图书是否被重复添加
80.           System.out.println("遍历输出hashset");
81.           System.out.println(hashSet.size());
82.           for (Book book : hashSet)
83.           {System.out.println(book.toString());}
84.           //使用TreeSet存储图书并遍历
85.           Set<Book> treeSet = new TreeSet<Book>();
86.           treeSet.add(b1);
87.           treeSet.add(b1);
88.           treeSet.add(b2);
89.           treeSet.add(b3);
90.           treeSet.add(b4);
91.           treeSet.add(b5);
92.           treeSet.add(b1_1);
93.           System.out.println("遍历输出treeset");//观察遍历输出的结果是否排序,如果排序,按什么数据进行的?
94.           for (Book book : treeSet)
95.           {System.out.println(book.toString());}
96.   }
97. }

3.使用Map类实现存储图书信息并遍历输出

将图书id作为键,图书对象作为值,实现Map集合存储数据

1. import java.util.HashMap;
2. import java.util.Map;
3. import java.util.Map.Entry;
4. 
5. class Bbook
6. {   public int id;
7.     public String name;
8.     public double price;
9.     public String press;
10.     public Bbook()
11.     {super();}
12.     public Bbook(int id, String name, double price, String press)
13.     {   super();
14.         this.id = id;
15.         this.name = name;
16.         this.price = price;
17.         this.press = press;
18.         }
19.     public int getId()
20.     {return id;}
21.     public void setId(int id)
22.     {this.id = id;}
23.     public String getName()
24.     {return name;}
25.     public void setName(String name)
26.     {this.name = name;}
27.     public double getPrice()
28.     {return price;}
29.     public void setPrice(double price)
30.     {this.price = price;}
31.     public String getPress()
32.     {return press;}
33.     public void setPress(String press)
34.     {this.press = press;}
35.     public String toString()
36.     {return "Book [id=" + id + ", name=" + name + ""
37. + ", press=" + press+ ", price=" + price + "]";
38.     }
39.     }
40. public class TestMap {
41.    public static void main(String[] args)
42.       {//创建集合中的元素图书对象
43.           Bbook b1 = new Bbook(1000, "b1", 30.5, "bjsxt");
44.           Bbook b1_1 = new Bbook(1000, "b1", 30, "bjsxt");
45.           Bbook b2 = new Bbook(1000, "b2", 50, "bjsxt");
46.           Bbook b3 = new Bbook(1001, "b3", 30.5, "bjsxt");
47.           Bbook b4 = new Bbook(1002, "b4", 30.5, "bjsxt");
48.           Bbook b5 = new Bbook(1003, "b5", 50, "bjsxt1");
49.      //使用Map存储图书并遍历
50.           Map<Integer, Bbook> bookMap = new HashMap<Integer, Bbook>();
51.           bookMap.put(b1.getId(), b1);
52.           bookMap.put(b1.getId(), b1);
53.           bookMap.put(b2.getId(), b2);
54.           bookMap.put(b3.getId(), b3);
55.           bookMap.put(b4.getId(), b4);
56.           bookMap.put(b5.getId(), b5);
57.           bookMap.put(b1_1.getId(), b1_1);
58.           System.out.println("遍历输出Map");//观察图书id为1000的数据在集合中出现几次?原因是什么?
59.           for (Entry<Integer, Bbook> entry : bookMap.entrySet())
60.           {System.out.println(entry.getKey() + "----------->" + entry.getValue());}
61.     //Map存储的结果是否按照id值进行排序,如果没有,怎么修改程序,要求结果按照id值排序?
62.           }
63.    }

实验3  集合应用

一、实验目的

   掌握HashMap集合的数据存储方法

二、实验内容

假如有以下email数据“aa@sohu.com,bb@163.com,cc@sina.com,..”现需要把email中的用户部分和邮件地址部分分离,分离后以键值对应的方式放入HashMap?

三、实验模板  

1. import java.util.HashMap;
2. import java.util.Map;
3. 
4. public class EmailSplit {
5.  public static void main(String[] args)
6.     {
7. String str = "aa@sohu.com,bb@163.com,cc@sina.com";
8. //得到每一个email
9. String strs[] = str.split(",");
10. //存放分离后email的信息
11.         Map<String, String> emailMap = new HashMap<String, String>();
12. for (String email : strs)
13.         {   String temp[] = email.split("@");
14. //分割email存入map
15.             emailMap.put(temp[0], temp[1]);
16.             }
17. for(int i=0;i<strs.length;i++) {
18.      if(i != strs.length)
19.            System.out.println(strs[i]);
20. //依次遍历emailMap中的所有元素并输出
21.          }
22.        }
23.   }

实验4 设计一个简单的图书管理程序

1.编写Data类代码,实现数据的增、删、改、查

1. import java.util.ArrayList;
2. 
3. public class Data {//使用缺省修饰符的Data类,实现了对主类的隐藏(封装)
4. private static ArrayList<Books>list = new ArrayList<Books>();
5. //私有字段list,不允许本类以外的任何类访问(封装)
6. static int query(String id) {//查询指定ID所在的索引值,返回-1表示不存在
7.  int i = 0,index = -1;
8.  for(Books b:list) {//遍历list集合
9.    if(id.equals(b.id)) {
10.       index = i;
11.       break;
12.     }i++;
13.   }return index;
14. }static String add(Books b) {//添加图书对象
15.   list.add(b);
16.   return "添加成功";
17. }
18. static String editNum(String id,int num) {//更改库存数量
19.   Books b = list.get(query(id));
20.   b.num = b.num + num;
21.   list.set(query(id), b);
22.   return "要添加的图书已存在,仅更新库存";
23. }
24. static String del(String id) {//删除ArrayList中的元素
25.   list.remove(query(id));
26.   return "删除成功";
27. }
28. static void show (String id) {//按指定ID显示图书对象信息
29.   Books b = list.get(query(id));
30.   System.out.println(b.toString());
31. }
32. static void showAll() {//显示ArrayList中所有数据
33.   if(list.size()==0) {//如果ArrayList中没有任何数据
34.     System.out.println( "库中没有任何数据");
35.     return;//后续代码不再执行
36.   }
37.   for(Books b:list) {//遍历list
38.     System.out.println(b.toString());
39.   }
40. }
41. }

2.编写Books类代码

1. public class Books {//共有的Books类
2.        public String id,name,author;//声明Books类字段
3.        public int num;
4.        public boolean chkID(String id) {//用于检查ID格式是否为合法的chkID()方法
5.         char first = id.charAt(0);//取出ID中第一个字符
6.     return Character.isLetter(first)&&id.length()==6;
7.        }//第一位是一个字母并且长度为6,则返回ture,否则false
8.        public String add() {//用于添加图书对象的方法
9.     //访问对象时无须创建类的对象,可以通过类名直接访问
10.      //调用Data类的静态方法query()检查该图书是否已经存在,返回-1表示不存在
11.      if(Data.query(id)==-1)
12.        return Data.add(this);//若不存在,则调用Data.add()
13.      else//否则调用Data.editNum()修改库存
14.        return Data.editNum(id,num);
15.        }
16.        public static void show(String id) {
17.      if(Data.query(id)==-1)//调用Data.query()判断查询ID是否存在
18.            System.out.println("要查询的编号不存在");
19.      else
20.        Data.show(id);
21.        }//若存在,则调用Data.show()显示图书信息
22.        public static void showAll() {
23.      Data.showAll();//调用Data.showAll()显示所有图书信息
24.        }
25.        public static String del(String id) {
26.      if(Data.query(id)==-1)//调用Data.query()查询要删除的图书是否存在
27.        return "要删除的数据不存在";
28.      else
29.        return Data.del(id);
30.        }//若存在,则调用Data.del()方法删除对象
31.        public String toString() {//重写toString()方法显示图书详细数据
32.      return "编号:"+id+",书名:"+name+",作者:"+author+",库存:"+num;
33.        }
34. }

3.编写主类中主方法的代码

1. import java.util.Scanner;
2. 
3. public class SX5 {
4. public static void main(String[] args) {
5.  Scanner val = new Scanner(System.in);
6.  boolean t = true;
7.  while(t) {
8.  System.out.print("1--添加  2--删除  3--查询  4--显示全部  5--退出,请选择:");
9.  switch(val.nextInt()) {
10.   case 1:System.out.print("输入编号,书名,作者,数量:");
11.   Books book = new Books();
12.   String id = val.next();
13.   if(book.chkID(id)) {//若Id合法,则创建book对象
14.     book.id = id;
15.     book.name = val.next();
16.     book.author = val.next();
17.     book.num = val.nextInt();
18.   }
19.   else {
20.     System.out.println("编号输入错误");
21.     val.next();//读取后面的数据,避免对下一次读取造成影响
22.     val.next();
23.     val.next();
24.     continue;
25.   }//返回while语句,开始下一次循环
26.   System.out.println(book.add());//添加图书对象,开始操作结果
27.   break;
28.   case 2:System.out.println("输入要删除的编号:");
29.   System.out.println(Books.del(val.next()));break;
30.   case 3:System.out.print("输入要查询的编号:");
31.   Books.show(val.next());break;
32.   case 4:Books.showAll();break;
33.   case 5:t = false;//修改循环条件,结束循环
34.   System.out.println("bye!");break;
35.   }
36.   }val.close();//关闭Scanner对象
37. }
38. }
目录
相关文章
|
3月前
|
移动开发 前端开发 API
期末测试——H5方式练习题
期末测试——H5方式练习题
35 0
|
3月前
|
存储 C语言
谭浩强 第六章利用数组处理批量数据
谭浩强 第六章利用数组处理批量数据
53 0
|
3月前
【错题集-编程题】春游(模拟 - 分情况讨论)
【错题集-编程题】春游(模拟 - 分情况讨论)
|
存储 算法 C语言
第六章 上机实验【数据结构】
第六章 上机实验【数据结构】
43 0
上机实验9 多线程案例
上机实验9 多线程案例
55 0
|
Java 数据安全/隐私保护 知识图谱
上机实验5 常用实用类
上机实验5 常用实用类
134 0
上机实验4 异常处理案例
上机实验4 异常处理案例
90 0
|
Java Windows
上机实验1 熟悉Java程序开发环境
上机实验1 熟悉Java程序开发环境
77 0
|
数据采集 Java
上机实验8 实现文件的复制访问
上机实验8 实现文件的复制访问
62 0
|
Java
上机实验2-1 简单数据类型和流程控制
上机实验2-1 简单数据类型和流程控制
73 0