实验十一 集合
实验时间2018-11-8
1、实验目的与要求
(1) 掌握Vetor、Stack、Hashtable三个类的用途及常用API;
(2) 了解java集合框架体系组成;
(3) 掌握ArrayList、LinkList两个类的用途及常用API。
(4) 了解HashSet类、TreeSet类的用途及常用API。
(5)了解HashMap、TreeMap两个类的用途及常用API;
(6) 结对编程(Pair programming)练习,体验程序开发中的两人合作。
2、实验内容和步骤
实验1: 导入第9章示例程序,测试程序并进行代码注释。
测试程序1:
l 使用JDK命令运行编辑、运行以下三个示例程序,结合运行结果理解程序;
l 掌握Vetor、Stack、Hashtable三个类的用途及常用API。
//示例程序1 import java.util.Vector; class Cat { private int catNumber; Cat(int i) { catNumber = i; } void print() { System.out.println("Cat #" + catNumber); } } class Dog { private int dogNumber; Dog(int i) { dogNumber = i; } void print() { System.out.println("Dog #" + dogNumber); } } public class CatsAndDogs { public static void main(String[] args) { Vector cats = new Vector(); for (int i = 0; i < 7; i++) cats.addElement(new Cat(i)); cats.addElement(new Dog(7)); for (int i = 0; i < cats.size(); i++) ((Cat) cats.elementAt(i)).print(); } } 运行结果: |
//示例程序2 import java.util.*; public class Stacks { static String[] months = { "1", "2", "3", "4" }; public static void main(String[] args) { Stack stk = new Stack(); for (int i = 0; i < months.length; i++) stk.push(months[i]); System.out.println(stk); System.out.println("element 2=" + stk.elementAt(2)); while (!stk.empty()) System.out.println(stk.pop()); } } 运行结果:
|
//示例程序3 import java.util.*; class Counter { int i = 1; public String toString() { return Integer.toString(i); } } public class Statistics { public static void main(String[] args) { Hashtable ht = new Hashtable(); for (int i = 0; i < 10000; i++) { Integer r = new Integer((int) (Math.random() * 20)); if (ht.containsKey(r)) ((Counter) ht.get(r)).i++; else ht.put(r, new Counter()); } System.out.println(ht); } } 运行结果: |
测试程序2:
l 使用JDK命令编辑运行ArrayListDemo和LinkedListDemo两个程序,结合程序运行结果理解程序;
import java.util.*; public class ArrayListDemo { public static void main(String[] argv) { ArrayList al = new ArrayList(); // Add lots of elements to the ArrayList... al.add(new Integer(11)); al.add(new Integer(12)); al.add(new Integer(13)); al.add(new String("hello")); // First print them out using a for loop. System.out.println("Retrieving by index:"); for (int i = 0; i < al.size(); i++) { System.out.println("Element " + i + " = " + al.get(i)); } } } 运行结果:
|
import java.util.*; public class LinkedListDemo { public static void main(String[] argv) { LinkedList l = new LinkedList(); l.add(new Object()); l.add("Hello"); l.add("zhangsan"); ListIterator li = l.listIterator(0); while (li.hasNext()) System.out.println(li.next()); if (l.indexOf("Hello") < 0) System.err.println("Lookup does not work"); else System.err.println("Lookup works"); } } 运行结果:
|
l 在Elipse环境下编辑运行调试教材360页程序9-1,结合程序运行结果理解程序;
l 掌握ArrayList、LinkList两个类的用途及常用API。
测试程序3:
l 运行SetDemo程序,结合运行结果理解程序;
import java.util.*; public class SetDemo { public static void main(String[] argv) { HashSet h = new HashSet(); //也可以 Set h=new HashSet() h.add("One"); h.add("Two"); h.add("One"); // DUPLICATE h.add("Three"); Iterator it = h.iterator(); while (it.hasNext()) { System.out.println(it.next()); } } } 运行结果:
|
l 在Elipse环境下调试教材365页程序9-2,结合运行结果理解程序;了解HashSet类的用途及常用API。
package 示例程序;
import java.util.*;
/**
* 此程序使用一组来打印System.in中的所有唯一单词
* @version 1.12 2015-06-21
* @author Cay Horstmann
*/
public class SetTest
{
public static void main(String[] args)
{
Set<String> words = new HashSet<>(); // HashSet实现了 Set
long totalTime = 0;
try (Scanner in = new Scanner(System.in))
{
while (in.hasNext())
{
String word = in.next();
long callTime = System.currentTimeMillis();
words.add(word);
callTime = System.currentTimeMillis() - callTime;
totalTime += callTime;
}
}
Iterator<String> iter = words.iterator();
for (int i = 1; i <= 20 && iter.hasNext(); i++)
System.out.println(iter.next());
System.out.println(". . .");
System.out.println(words.size() + " distinct words. " + totalTime + " milliseconds.");
}
}
l 在Elipse环境下调试教材367页-368程序9-3、9-4,结合程序运行结果理解程序;了解TreeSet类的用途及常用API。
package 示例程序;
import java.util.*;
/**
* 该程序通过比较他们的描述来对一组项目进行描述.
* @version 1.12 2015-06-21
* @author Cay Horstmann
*/
public class TreeSetTest
{
public static void main(String[] args)
{
SortedSet<Item> parts = new TreeSet<>();
parts.add(new Item("Toaster", 1234));
parts.add(new Item("Widget", 4562));
parts.add(new Item("Modem", 9912));
System.out.println(parts);
NavigableSet<Item> sortByDescription = new TreeSet<>(
Comparator.comparing(Item::getDescription));
sortByDescription.addAll(parts);
System.out.println(sortByDescription);
}
}
package 示例程序;
import java.util.*;
/**
* 带有说明和部件号的项目.
*/
public class Item implements Comparable<Item>
{
private String description;
private int partNumber;
/**
* 构建一个项目
*
* @param aDescription
* 对该对象的描述
* @param aPartNumber
* 该项目的部件号
*
*/
public Item(String aDescription, int aPartNumber)
{
description = aDescription;
partNumber = aPartNumber;
}
/**
* 获取此项的描述.
*
* @return 描述
*/
public String getDescription()
{
return description;
}
public String toString()
{
return "[description=" + description + ", partNumber=" + partNumber + "]";
}
public boolean equals(Object otherObject)
{
if (this == otherObject) return true;
if (otherObject == null) return false;
if (getClass() != otherObject.getClass()) return false;
Item other = (Item) otherObject;
return Objects.equals(description, other.description) && partNumber == other.partNumber;
}
public int hashCode()
{
return Objects.hash(description, partNumber);
}
public int compareTo(Item other)
{
int diff = Integer.compare(partNumber, other.partNumber);
return diff != 0 ? diff : description.compareTo(other.description);
}
}
测试程序4:
l 使用JDK命令运行HashMapDemo程序,结合程序运行结果理解程序;
import java.util.*; public class HashMapDemo { public static void main(String[] argv) { HashMap h = new HashMap(); // The hash maps from company name to address. h.put("Adobe", "Mountain View, CA"); h.put("IBM", "White Plains, NY"); h.put("Sun", "Mountain View, CA"); String queryString = "Adobe"; String resultString = (String)h.get(queryString); System.out.println("They are located in: " + resultString); } } 运行结果:
|
l 在Elipse环境下调试教材373页程序9-6,结合程序运行结果理解程序;
package 示例程序;
import java.util.*;
/**
* 该程序掩饰了如何使用具有键类型String和值类型Employee的映射.
* @version 1.12 2015-06-21
* @author Cay Horstmann
*/
public class MapTest
{
public static void main(String[] args)
{
Map<String, Employee> staff = new HashMap<>();
staff.put("144-25-5464", new Employee("Amy Lee"));
staff.put("567-24-2546", new Employee("Harry Hacker"));
staff.put("157-62-7935", new Employee("Gary Cooper"));
staff.put("456-62-5527", new Employee("Francesca Cruz"));
// 打印所有的条目
System.out.println(staff);
// 删除一个条目
staff.remove("567-24-2546");
// 替换条目
staff.put("456-62-5527", new Employee("Francesca Miller"));
// 查找一个值
System.out.println(staff.get("157-62-7935"));
// 遍历所有的条目
staff.forEach((k, v) ->
System.out.println("key=" + k + ", value=" + v));
}
}
package 示例程序;
/**
* 一个以测试为目的的employee类中的mini表.
*/
public class Employee
{
private String name;
private double salary;
/**
* 构建一个薪水为零的员工.
* @param n 员工姓名
*/
public Employee(String name)
{
this.name = name;
salary = 0;
}
public String toString()
{
return "[name=" + name + ", salary=" + salary + "]";
}
}
l 了解HashMap、TreeMap两个类的用途及常用API。
实验2:结对编程练习:
l 关于结对编程:以下图片是一个结对编程场景:两位学习伙伴坐在一起,面对着同一台显示器,使用着同一键盘,同一个鼠标,他们一起思考问题,一起分析问题,一起编写程序。
l 关于结对编程的阐述可参见以下链接:
http://www.cnblogs.com/xinz/archive/2011/08/07/2130332.html
http://en.wikipedia.org/wiki/Pair_programming
l 对于结对编程中代码设计规范的要求参考:
http://www.cnblogs.com/xinz/archive/2011/11/20/2255971.html
以下实验,就让我们来体验一下结对编程的魅力。
l 确定本次实验结对编程合作伙伴;
l 各自运行合作伙伴实验九编程练习1,结合使用体验对所运行程序提出完善建议;
package 人员身份证;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class Founctions {
private static ArrayList<People> peoplelist;
public static void main(String[] args) {
peoplelist = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
File file = new File("/Users/eleanorliu/Desktop/学习/java文件/实验六/身份证号.txt");
try {
FileInputStream fis = new FileInputStream(file);
BufferedReader in = new BufferedReader(new InputStreamReader(fis));
String temp = null;
while ((temp = in.readLine()) != null) {
Scanner linescanner = new Scanner(temp);
linescanner.useDelimiter(" ");
String name = linescanner.next();
String number = linescanner.next();
String sex = linescanner.next();
String age = linescanner.next();
String province =linescanner.nextLine();
People people = new People();
people.setName(name);
people.setnumber(number);
people.setsex(sex);
int a = Integer.parseInt(age);
people.setage(a);
people.setprovince(province);
peoplelist.add(people);
}
} catch (FileNotFoundException e) {
System.out.println("找不到学生信息文件");
e.printStackTrace();
} catch (IOException e) {
System.out.println("学生信息文件读取错误");
e.printStackTrace();
}
boolean isTrue = true;
while (isTrue) {
System.out.println("选择你的操作,输入正确格式的选项");
System.out.println("1.字典排序");
System.out.println("2.输出年龄最大和年龄最小的人");
System.out.println("3.寻找老乡");
System.out.println("4.寻找年龄相近的人");
System.out.println("5.退出");
String m = scanner.next();
switch (m) {
case "1":
Collections.sort(peoplelist);
System.out.println(peoplelist.toString());
break;
case "2":
int max=0,min=100;
int j,k1 = 0,k2=0;
for(int i=1;i<peoplelist.size();i++)
{
j=peoplelist.get(i).getage();
if(j>max)
{
max=j;
k1=i;
}
if(j<min)
{
min=j;
k2=i;
}
}
System.out.println("年龄最大:"+peoplelist.get(k1));
System.out.println("年龄最小:"+peoplelist.get(k2));
break;
case "3":
System.out.println("老家?");
String find = scanner.next();
String place=find.substring(0,3);
for (int i = 0; i <peoplelist.size(); i++)
{
if(peoplelist.get(i).getprovince().substring(1,4).equals(place))
System.out.println("老乡"+peoplelist.get(i));
}
break;
case "4":
System.out.println("年龄:");
int yourage = scanner.nextInt();
int near=agenear(yourage);
int value=yourage-peoplelist.get(near).getage();
System.out.println(""+peoplelist.get(near));
break;
case "5":
isTrue = false;
System.out.println("退出程序!");
break;
default:
System.out.println("输入有误");
}
}
}
public static int agenear(int age) {
int j=0,min=53,value=0,k=0;
for (int i = 0; i < peoplelist.size(); i++)
{
value=peoplelist.get(i).getage()-age;
if(value<0) value=-value;
if (value<min)
{
min=value;
k=i;
}
}
return k;
}
}
package 人员身份证;
public class People implements Comparable<People> {
private String name;
private String number ;
private String sex ;
private int age;
private String province;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getnumber() {
return number;
}
public void setnumber(String number) {
this.number = number;
}
public String getsex() {
return sex ;
}
public void setsex(String sex ) {
this.sex =sex ;
}
public int getage() {
return age;
}
public void setage(int age) {
// 定义 a = Integer.parseInt(age);
this.age= age;
}
public String getprovince() {
return province;
}
public void setprovince(String province) {
this.province=province ;
}
public int compareTo(People o) {
return this.name.compareTo(o.getName());
}
public String toString() {
return name+" "+sex+" "+age+" "+number+" "+province+" ";
}
}
各自运行合作伙伴实验十编程练习2,结合使用体验对所运行程序提出完善建议;
package 异常;
import java.io.PrintWriter;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
@SuppressWarnings("resource")
Scanner in = new Scanner(System.in);
Demo demo=new Demo();
PrintWriter output = null;
try {
output = new PrintWriter("test.txt");
} catch (Exception e) {
e.printStackTrace();
}
int sum = 0;
for (int i = 0; i < 10; i++) {
int a = (int) Math.round(Math.random() * 100);
int b = (int) Math.round(Math.random() * 100);
int c = (int) Math.round(Math.random() * 3);
switch (c) {
case 0:
System.out.println(a + "+" + b + "=");
int d0 = in.nextInt();
output.println(a + "+" + b + "=" + d0);
if (d0 == demo.demo1(a, b)) {
sum += 10;
System.out.println("恭喜答案正确");
} else {
System.out.println("抱歉,答案错误");
}
break;
case 1:
while (a < b) {
int x = a;
a = b;
b = x;
}
System.out.println(a + "-" + b + "=");
int d1 = in.nextInt();
output.println(a + "-" + b + "=" + d1);
if (d1 == demo.demo2(a, b)) {
sum += 10;
System.out.println("恭喜答案正确");
} else {
System.out.println("抱歉,答案错误");
}
break;
case 2:
System.out.println(a + "*" + b + "=");
int d2 = in.nextInt();
output.println(a + "*" + b + "=" + d2);
if (d2 == demo.demo3(a, b)) {
sum += 10;
System.out.println("恭喜答案正确");
} else {
System.out.println("抱歉,答案错误");
}
break;
case 3:
while (b == 0 || a % b != 0) {
a = (int) Math.round(Math.random() * 100);
b = (int) Math.round(Math.random() * 100);
}
System.out.println(a + "/" + b + "=");
int d3 = in.nextInt();
output.println(a + "/" + b + "=" + d3);
if (d3 == demo.demo4(a, b)) {
sum += 10;
System.out.println("恭喜答案正确");
} else {
System.out.println("抱歉,答案错误");
}
break;
}
}
System.out.println("你的得分为" + sum);
output.println("你的得分为" + sum);
output.close();
}
}
package 异常;
public class Demo<T> {
private T a;
private T b;
public Demo() {
a = null;
b = null;
}
public Demo(T a, T b) {
this.a = a;
this.b = b;
}
public int demo1(int a, int b) {
return a + b;
}
public int demo2(int a, int b) {
return a - b;
}
public int demo3(int a, int b) {
return a * b;
}
public int demo4(int a, int b) {
return a / b;
}
}
本周学习总结:
首先,区分最顶层接口的区别:Collection和Map的区别:前者是单个元素;后者存储的是一对元素。Collection有List和Set两个子接口,两个子接口下分别有Vector和ArrayList以及HashSet和TreeSet等实现类;Map有HashMap、TreeMap、HashTable三种实现类。现分别总结它们的区别。
一、在Collection下面,有Set和List两个接口继承了Collection,两者区别如下:
List里面的元素是有游标的,因此它们是可以通过游标进行get相应的值,同时,由于游标的存在,内部的元素允许重复;与之对应的是Set,Set存储时是无顺序的(当然,treeSet会通过一定的顺序储存排列数据),因此内部元素之间不能重复。
1、List下面的ArrayList、Vector、LinkedList三者的区别:
a、Vector和ArrayList的区别:Vector是重量级的,不支持并发操作,数据操作时异步的,因此相对于ArrayList的消耗会更大;ArrayList与之对应,支持并发操作,线性不安全。因此,Vector和ArrayList的区别主要是:前者支持数据同步,后者支持多线程对数据操作。
b、LinkedList与Vector和ArrayList的区别:LinkedList存储数据的方式是链表方式,而Vector和ArrayList是有顺序的队列形式,因此,他们主要的特点区别是:LinkedList相对于Vector和ArrayList而言,存储数据的速度更快,但是查找数据的速度较Vector和ArrayList慢。
2、Set下面的HashSet和TreeSet的区别:HashSet中元素是无序的,元素不可重复,可以有null值;TeeSet元素以一定的顺序排列,但是不能保证是和元素add进去的顺序一样,同时,TreeSet不可重复,不可有null值。
3、HashMap和HashTable以及TreeMap的区别:首先,三者均是实现Map接口的实现类,所以,在存储数据方面均是以一组数据的形式储存,每个数据包含Key和Value值。首先,要明确的是,在Map下面的实现类都是通过key值来映射对应的value值的,所以Key值都是唯一的。三者的主要区别主要表现在能否加null值,是否支持数据同步,值得储存是否有序。
在HashMap中,key和value都可以是null,value值允许重复,不支持数据同步,即允许多线程操作数据
在HashTable中,key和value均不能是null值,同时HashTable支持数据同步,线性安全。
TreeMap插入的元素是有序的,key值不允许为空,value允许为空值