1、实验目的与要求
(1) 掌握Vetor、Stack、Hashtable三个类的用途及常用API;
(2) 了解java集合框架体系组成;
(3) 掌握ArrayList、LinkList两个类的用途及常用API。
(4) 了解HashSet类、TreeSet类的用途及常用API。
(5)了解HashMap、TreeMap两个类的用途及常用API;
(6) 结对编程(Pair programming)练习,体验程序开发中的两人合作。
一、理论知识
1、数据结构介绍
(1)一般将数据结构分为两大类:线性数据结构和 非线性数据结构。
(2)线性数据结构:线性表、栈、队列、串、数组 和文件。
(3)线性表按其存储结构可分为顺序表和链表, 用顺序存储结构存储的线性表称为顺序表;
(4)栈(Stack)也是一种特殊的 线性表,是一种后进先出 (LIFO)的结构。
(5)队列(Queue)是限定所有的插入只能在表的一端进行 ,而所有的删除都在表的另一端进行的线性表。
(6)散列表又称为哈希表;
(7)负载因子越高 (越接近1.0),内存的使用效率越高,元素的 寻找时间越长。负载因子越低 (越接近0.0),元素的寻找时 间越短,内存浪费越多。
2、JAVA的集合框架
(1)集合(Collection或称为容器 )是一种包含多个元素 并提供对所包含元素操作方法的类,其包含的元 素可以由同一类型的对象组成,也可以由不同类 型的对象组成。
(2)框架就是一个类库的集合,框架中包含很多 超类,编程者创建这些超类的子类可较方便的设 计设计程序所需的类。例如:Swing类包
(3)集合类的作用: Java的集合类提供了一些基本数据结构的支持。 – 例如Vector;
(4)集合类的使用: Java的集合类包含在java.util包中。
(5)集合类的特点:特点一: 只容纳对象。
特点二:集合类容纳的对象都是Object类的实例,一旦把一个对象置入集合类中,它的类信息将丢失;
3、JDK1.1版本中的集合类
(1)Vector中只能存放对象。
Vector的元素通过下标进行访问。
Vector类关键属性: capacity表示集合最多能容纳的元素个数。capacityIncrement表示每次增加多少容量。size表示集合当前元素个数。
(2)Vector类的关键方法: void addElement(Object obj) void add(int index, Object element) Object elementAt(int index)
(3)Stack类是Vector的子类。
Stack类描述堆栈数据结构,即LIFO。
(4)Hashtable类 :Hashtable通过键来查找元素。
Hashtable用散列码(hashcode)来确定键。所有对象都有一个散列码,可以通过Object类的 hashCode()方法获得。
2、实验内容和步骤
实验1: 导入第9章示例程序,测试程序并进行代码注释。
测试程序1:
l 使用JDK命令运行编辑、运行以下三个示例程序,结合运行结果理解程序;
掌握Vetor、Stack、Hashtable三个类的用途及常用API。
import java.util.Vector; //示例程序1 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++) if(cats.elementAt(i)instanceof Cat)// instanceof运算符是用来指出对象是否是特定类的一个实例 { ((Cat) cats.elementAt(i)).print(); }else { ((Dog) cats.elementAt(i)).print(); } }}
结果如下:
示例2:
//示例程序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]);//放入一个i值 System.out.println(stk); System.out.println("element 2=" + stk.elementAt(2));//element表示一个节点 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();//生成集合类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++;//用来判断r是否为一个间值 else ht.put(r, new Counter());//创建新的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来添加对象且可以重载 // 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")); System.out.println(al.size());//输出al的长度 // 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)); } } }
结果如下:
mport 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");//add方法可以重载 ListIterator li = l.listIterator(0);//迭代器生成li对象 while (li.hasNext())//hasNext方法用来返回迭代器的对象 System.out.println(li.next()); if (l.indexOf("Hello") < 0) //生成循环语句判断最后结果 System.err.println("Lookup does not work"); else System.err.println("Lookup works"); } }
结果如下:
测试程序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()) //hasNext方法 { System.out.println(it.next()); } } }
结果如下:
- 在Elipse环境下调试教材365页程序9-2,结合运行结果理解程序;了解HashSet类的用途及常用API。
package set; import java.util.*; /** * This program uses a set to print all unique words in 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 implements 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."); } }
小结:HashSet类中存放的对象不能重复,不能保证元素的排列顺序,顺序有可能发生变化。
在Elipse环境下调试教材367页-368程序9-3、9-4,结合程序运行结果理解程序;了解TreeSet类的用途及常用API。
package treeSet; import java.util.*; /** * This program sorts a set of item by comparing their descriptions. * @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));//add方法 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 treeSet; import java.util.*; /** * An item with a description and a part number. */ public class Item implements Comparable<Item>//Item类实现Comparable接口 { private String description; private int partNumber; /** * Constructs an item. * * @param aDescription * the item's description * @param aPartNumber * the item's part number */ public Item(String aDescription, int aPartNumber) { description = aDescription;//字符串 partNumber = aPartNumber; } /** * Gets the description of this item. * * @return the description */ 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); } }
结果如下:
小结:TreeSet是一种自带排序的set,TreeSet可以确保集合元素处于排序状态。TreeSet支持两种排序方式,自然排序 和定制排序。
测试程序4:
使用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 map; import java.util.*; /** * This program demonstrates the use of a map with key type String and value type 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<>();//HashMap implements Map 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")); // print all entries System.out.println(staff); // remove an entry staff.remove("567-24-2546"); // replace an entry staff.put("456-62-5527", new Employee("Francesca Miller")); // look up a value System.out.println(staff.get("157-62-7935")); // iterate through all entries staff.forEach((k, v) -> System.out.println("key=" + k + ", value=" + v)); } }
结果如下:
l 实验2:结对编程练习:
关于结对编程:以下图片是一个结对编程场景:两位学习伙伴坐在一起,面对着同一台显示器,使用着同一键盘,同一个鼠标,他们一起思考问题,一起分析问题,一起编写程序。
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,结合使用体验对所运行程序提出完善建议;
l 各自运行合作伙伴实验十编程练习2,结合使用体验对所运行程序提出完善建议;
1、合作伙伴:张燕
- 采用结对编程方式,与学习伙伴合作完成实验九编程练习1;
package xinxi; 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.Arrays; import java.util.Collections; import java.util.Scanner; public class xinxi{ private static ArrayList<Student> studentlist; public static void main(String[] args) { studentlist = new ArrayList<>(); Scanner scanner = new Scanner(System.in); File file = new File("F:\身份证号.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(); Student student = new Student(); student.setName(name); student.setnumber(number); student.setsex(sex); int a = Integer.parseInt(age); student.setage(a); student.setprovince(province); studentlist.add(student); } } 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.查找你的同乡"); String n = scanner.next(); switch (n) { case "1": Collections.sort(studentlist); System.out.println(studentlist.toString()); break; case "2": int max=0,min=100; int j,k1 = 0,k2=0; for(int i=1;i<studentlist.size();i++) { j=studentlist.get(i).getage(); if(j>max) { max=j; k1=i; } if(j<min) { min=j; k2=i; } } System.out.println("年龄最大:"+studentlist.get(k1)); System.out.println("年龄最小:"+studentlist.get(k2)); break; case "3": System.out.println("年龄:"); int yourage = scanner.nextInt(); int near=agenear(yourage); int value=yourage-studentlist.get(near).getage(); System.out.println("和你年龄相近的是"+studentlist.get(near)); break; case "4": System.out.println("输入你的家乡"); String find = scanner.next(); String place=find.substring(0,3); for (int i = 0; i <studentlist.size(); i++) { if(studentlist.get(i).getprovince().substring(1,4).equals(place)) System.out.println("你的同乡是 "+studentlist.get(i)); } break; } } } public static int agenear(int age) { int j=0,min=53,value=0,k=0; for (int i = 0; i < studentlist.size(); i++) { value=studentlist.get(i).getage()-age; if(value<0) value=-value; if (value<min) { min=value; k=i; } } return k; } }
package xinxi; public class Student implements Comparable<Student> { 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) { this.age= age; } public String getprovince() { return province; } public void setprovince(String province) { this.province=province ; } public int compareTo(Student o) { return this.name.compareTo(o.getName()); } public String toString() { return name+" "+sex+" "+age+" "+number+" "+province+" "; } }
心得:通过测试,可以体会到小伙伴的代码与我的不同之处,需要学习的还很多。
- 采用结对编程方式,与学习伙伴合作完成实验十编程练习2。
package S; import java.io.*; import java.io.PrintWriter; import java.util.Scanner; public class jisuan { public static void main(String[] args) { Scanner in = new Scanner(System.in); PrintWriter output = null; try { output = new PrintWriter("text.txt"); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } int sum = 0; for (int i = 1; i <= 10; i++) { int a = (int) Math.round(Math.random() * 100); int b = (int) Math.round(Math.random() * 100); int m = (int) Math.round(Math.random() * 4); switch (m) { case 1: while (b == 0) { b = (int) Math.round(Math.random() * 100); } while (a % b != 0) { a = (int) Math.round(Math.random() * 100); } System.out.println(a + "/" + b + "="); int c1 = in.nextInt(); output.println(a + "/" + b + "=" + c1); if (c1 == a / b) { System.out.println("恭喜答案正确"); sum += 10; } else { System.out.println("抱歉,答案错误"); } break; case 2: System.out.println( a + "*" + b + "="); int c2 = in.nextInt(); output.println(a + "*" + b + "=" + c2); if (c2 == a * b) { System.out.println("恭喜答案正确"); sum += 10; } else { System.out.println("抱歉,答案错误"); } break; case 3: System.out.println( a + "+" + b + "="); int c3 = in.nextInt(); output.println(a + "+" + b + "=" + c3); if (c3 == a + b) { System.out.println("恭喜答案正确"); sum += 10; } else { System.out.println("抱歉,答案错误"); } break; case 4: while (a < b) { a = (int) Math.round(Math.random() * 100); } System.out.println( a + "-" + b + "="); int c4 = in.nextInt(); output.println(a + "-" + b + "=" + c4); if (c4 == a - b) { System.out.println("恭喜答案正确"); sum += 10; } else { System.out.println("抱歉,答案错误"); } break; } } System.out.println("成绩" + sum); output.println("成绩" + sum); output.close(); } }
package S; public class math<T> { private T a; private T b; public int add(int a, int b) { return a + b; } public int reduce(int a, int b) { return a - b; } public int multiplication(int a, int b) { return a * b; } public int division(int a, int b) { if (b != 0 && a % b == 0) return a / b; else return 0; } }
心得:合作小伙伴代码写的很多很详细,我从中学到了很多知识,如果可以的话,可以在代码的精简上多做些功夫。
2) 结对编程代码;
实验九编程练习1:
package xinxi; 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.Arrays; import java.util.Collections; import java.util.Scanner; public class xinxi{ private static ArrayList<Student> studentlist; public static void main(String[] args) { studentlist = new ArrayList<>(); Scanner scanner = new Scanner(System.in); File file = new File("F:\身份证号.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(); Student student = new Student(); student.setName(name); student.setnumber(number); student.setsex(sex); int a = Integer.parseInt(age); student.setage(a); student.setprovince(province); studentlist.add(student); } } 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.查找你的同乡"); String n = scanner.next(); switch (n) { case "1": Collections.sort(studentlist); System.out.println(studentlist.toString()); break; case "2": int max=0,min=100; int j,k1 = 0,k2=0; for(int i=1;i<studentlist.size();i++) { j=studentlist.get(i).getage(); if(j>max) { max=j; k1=i; } if(j<min) { min=j; k2=i; } } System.out.println("年龄最大:"+studentlist.get(k1)); System.out.println("年龄最小:"+studentlist.get(k2)); break; case "3": System.out.println("年龄:"); int yourage = scanner.nextInt(); int near=agenear(yourage); int value=yourage-studentlist.get(near).getage(); System.out.println("和你年龄相近的是"+studentlist.get(near)); break; case "4": System.out.println("输入你的家乡"); String find = scanner.next(); String place=find.substring(0,3); for (int i = 0; i <studentlist.size(); i++) { if(studentlist.get(i).getprovince().substring(1,4).equals(place)) System.out.println("你的同乡是 "+studentlist.get(i)); } break; } } } public static int agenear(int age) { int j=0,min=53,value=0,k=0; for (int i = 0; i < studentlist.size(); i++) { value=studentlist.get(i).getage()-age; if(value<0) value=-value; if (value<min) { min=value; k=i; } } return k; } }
package xinxi; public class Student implements Comparable<Student> { 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) { this.age= age; } public String getprovince() { return province; } public void setprovince(String province) { this.province=province ; } public int compareTo(Student o) { return this.name.compareTo(o.getName()); } public String toString() { return name+" "+sex+" "+age+" "+number+" "+province+" "; } }
实验十编程练习2:
package C; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Random; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); Suanfa counter = new Suanfa(); PrintWriter out = null; try { out = new PrintWriter("test.txt"); } catch (FileNotFoundException e) { System.out.println("文件夹输出失败"); e.printStackTrace(); } int sum = 0; for (int i = 1; i <= 10; i++) { int a = (int) Math.round(Math.random() * 100); int b = (int) Math.round(Math.random() * 100); int m; Random rand = new Random(); m = (int) rand.nextInt(4) + 1; System.out.println("随机生成的四则运算类型:" + m); switch (m) { case 1: a = b + (int) Math.round(Math.random() * 100); while(b == 0){ b = (int) Math.round(Math.random() * 100); } while(a % b != 0){ a = (int) Math.round(Math.random() * 100); } //若生成的除法式子必须能整除,且满足分母为0的条件,则a一定要大于b,且a模b的结果要为0。 System.out.println(i + ": " + a + "/" + b + "="); int c0 = in.nextInt(); out.println(a + "/" + b + "=" + c0); if (c0 == counter.d(a, b)) { sum += 10; System.out.println("正确!"); } else { System.out.println("错误!"); } break; case 2: System.out.println(i + ": " + a + "*" + b + "="); int c = in.nextInt(); out.println(a + "*" + b + "=" + c); if (c == counter.m(a, b)) { sum+= 10; System.out.println("正确!"); } else { System.out.println("错误!"); } break; case 3: System.out.println(i + ": " + a + "+" + b + "="); int c1 = in.nextInt(); out.println(a + "+" + b + "=" + c1); if (c1 == counter.add(a, b)) { sum += 10; System.out.println("正确!"); } else { System.out.println("错误!"); } break; case 4: while (a < b) { b = (int) Math.round(Math.random() * 100); } //因为不能产生运算结果为负数的减法式子,所以a一定要大于b。若a<b,则重新生成b。 System.out.println(i + ": " + a + "-" + b + "="); int c2 = in.nextInt(); out.println(a + "-" + b + "=" + c2); if (c2 == counter.r(a, b)) { sum += 10; System.out.println("正确!"); } else { System.out.println("错误!"); } break; } } System.out.println("成绩" + sum); out.println("成绩:" + sum); out.close(); } }
package C; public class Suanfa<T> { private T a; private T b; public int add(int a,int b) { return a + b; } public int r(int a, int b) { return a - b; } public int m(int a, int b) { return a * b; } public int d(int a, int b) { if (b != 0 && a%b==0) return a / b; else return 0; } }
3) 结对程序运行功能界面截图;
4) 结对过程描述,提供两人在讨论、细化和编程时的结对照片(非摆拍)
在测试过互相的程序后,发现了各自的不足之处,以后会加以改进,然后我们二人又重新开始对以上的程序进行了修改,简化,得出了结果,果然合作的话会有更大的发展空间,还能发现更多的问题。
总结:本章我们学习了Vetor、Stack、Hashtable三个类的用途及常用API;我在测试代码实验中,通过注释,编译逐渐理解了本周理论知识所讲的知识,感受到了它们的区别和联系,在本周实验中还增加了一个结对实验,这个合作实验让我们发现了彼此的不足和需要改进的地方,是 个很好的相互学习的过程。