用户工具

站点工具


zh:courses:java2025:ch06

这是本文档旧的修订版!


第六章:集合类

课件

下载:集合类

List的实现类:ArrayList类

ArrayList类:实例

ArrayListTester.java
package cn.edu.bjut.chapter6;
 
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
 
public class ArrayListTester {
	public static void main(String[] args) {
		List<Integer> strList = new ArrayList<Integer>();
 
		strList.add("123");
		strList.add("456");
		strList.add("234");
		strList.add(2, "121");
		System.out.println(strList);
 
		strList.remove(2);
		System.out.println(strList);
 
		for (int i = 0; i < strList.size(); i++) {
			System.out.print(strList.get(i) + "\t");
		}
		System.out.println();
 
		for (Iterator<String> it = list1.iterator(); it.hasNext();) {
			System.out.print(it.next() + "\t");
		}
		System.out.println();
	}
}

ArrayList类:构造函数

ArrayListConstructorTester.java
package cn.edu.bjut.chapter6;
 
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
 
public class ArrayListConstructorTester {
	public static String getRandomString(int length) { 
		String base = "abcdefghijklmnopqrstuvwxyz0123456789";
		Random random = new Random();
		StringBuffer sb = new StringBuffer(length);
		for (int i = 0; i < length; i++) {
			int number = random.nextInt(base.length());
			sb.append(base.charAt(number));
		}
		return sb.toString();
	}
 
	public static void main(String[] args) {
		int n = 1000000;
 
		long startTime1 = System.currentTimeMillis();
		List<String> list1 = new ArrayList<String>();
		for (int i = 0; i < n; i++) {
			list1.add(getRandomString(5));
		}
		long endTime1 = System.currentTimeMillis();
 
		long startTime2 = System.currentTimeMillis();
		List<String> list2 = new ArrayList<String>(n);
		for (int i = 0; i < n; i++) {
			list2.add(getRandomString(5));
		}
		long endTime2 = System.currentTimeMillis();
 
		System.out.println((endTime1 - startTime1) + "ms\t" 
				+ (endTime2 - startTime2) + "ms");
	}
}

List排序

Person类

Person.java
package cn.edu.bjut.chapter6;
 
public class Person implements Comparable<Person> {
	private String name;
	private char gender;
 
	public Person(String name, char gender) {
		this.name = name;
		this.gender = gender;
	}
 
	public String getName() {
		return name;
	}
 
	public void setName(String name) {
		this.name = name;
	}
 
	public char getGender() {
		return gender;
	}
 
	public void setGender(char gender) {
		this.gender = gender;
	}
 
	@Override
	public String toString() {
		return (name + "\t" + gender);
	}
 
	@Override
	public int compareTo(Person o) {
		if (gender < o.gender) {
			return -1;
		} else if (gender > o.gender) {
			return 1;
		} else {
			return name.compareTo(o.name);
		}
	}
}

测试类

ListSortTester.java
package cn.edu.bjut.chapter6;
 
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
 
public class ListSortTester {
	public static void main(String[] args) {
		String[] strArray = new String[] { "dtk", "abc", "ekd", "def" };
		List<String> strList = Arrays.asList(strArray);
		System.out.println(strList);
		Collections.sort(strList);
		System.out.println(strList);
		Collections.reverse(strList);
		System.out.println(strList);
 
		List<Person> stuList = new ArrayList<Person>();
		stuList.add(new Person("李文慧", 'F'));
		stuList.add(new Person("白富美", 'F'));
		stuList.add(new Person("谢祖隆恩", 'M'));
		stuList.add(new Person("梁化祥", 'M'));
		System.out.println(stuList);
		Collections.sort(stuList);
		System.out.println(stuList);
 
		Collections.sort(stuList);
		System.out.println(stuList);
		int idx = Collections.binarySearch(stuList, new Person("白晨", 'F'));
		if (idx >= 0) {
			System.out.println("Found");
		} else {
			System.out.println("Not Found");
		}
	}
}

人员分组

Grouper类

Grouper.java
package cn.edu.bjut.chapter6;
 
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
 
public class Grouper<T> {
	private List<T> data;
	private int nfold; 
	private int[] starts = null;
 
	public Grouper(List<T> data, int nfold, long seed) {
		this.data = data; 
		this.nfold = nfold; 
 
		Collections.shuffle(data, new Random(seed));
 
		this.starts = new int[nfold + 1]; 
		for (int v = 0; v <= nfold; v++) {
			starts[v] = Math.round(data.size() * (v / (float) nfold)); 
		}
	}
 
	public List<T> getGroup(final int split) {
		if (split >= nfold || split < 0) {
			return null; 
		} 
 
		List<T> group = new ArrayList<T>(); 
		for (int m = starts[split]; m < starts[split + 1]; m++) {
			group.add(data.get(m)); 
		}
 
		return group; 
	}
}

GrouperTester类

GrouperTester.java
package cn.edu.bjut.chapter6;
 
import java.util.ArrayList;
import java.util.List;
 
public class GrouperTester {
	public static void main(String[] args) {
		List<Person> students = new ArrayList<Person>();
		students.add(new Person("李文慧", 'F'));
		students.add(new Person("白晨", 'F'));
		students.add(new Person("谢天昊", 'M'));
		students.add(new Person("梁化祥", 'M'));
		students.add(new Person("高明", 'M'));
		students.add(new Person("孔雀", 'F'));
 
		Grouper<Person> grouper = new Grouper<Person>(students, 2, 1); 
		System.out.println("The first group:");
		System.out.println(grouper.getGroup(0));
		System.out.println("The second group:"); 
		System.out.println(grouper.getGroup(1));
	}
}

Stack类实现

MyStack类

MyStack.java
package cn.edu.bjut.chapter6;
 
import java.util.LinkedList;
 
public class MyStack<E> {
	private LinkedList<E> list;
 
	public MyStack() {
		list = new LinkedList<E>();
	}
 
	public void push(E e) {
		list.push(e);
	}
 
	public E pop() {
		return list.pop();
	}
 
	public int size() {
		return list.size();
	}
 
	public boolean isEmpty() {
		return list.isEmpty();
	}
}

Stack测试类

StackTester.java
package cn.edu.bjut.chapter6;
 
public class StackTester {
	public static boolean isMatch(String str) {
		char[] charArray = str.toCharArray();
		MyStack<Character> stack = new MyStack<Character>();
		for (char c : charArray) {
			if (c == '(' || c == '[' || c == '{') {
				stack.push(c);
			} else if (c == ')' || c == ']' || c == '}') {
				if (stack.isEmpty()) {
					return false;
				}
 
				Character cc = stack.pop();
 
				switch (c) {
				case ')':
					if (cc != '(') {
						return false;
					}
					break;
				case ']':
					if (cc != '[') {
						return false;
					}
					break;
				case '}':
					if (cc != '{') {
						return false;
					}
					break;
				}
			}
		}
 
		return stack.isEmpty() ? true : false;
	}
 
	public static void main(String[] args) {
		System.out.println(isMatch("ab(dd[123]}"));
 
		System.out.println(isMatch("ab(dd[123])"));
	}
 
}

HashSet类:实例

HashSetTester.java
package cn.edu.bjut.chapter6;
 
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
 
public class HashSetTester {
	public static void main(String[] args) {
		Set<String> set = new HashSet<String>();
		set.add("Alice");
		set.add("Albert");
		set.add("Mike");
		set.add("Tim");
 
		System.out.println(set);
 
		set.remove("Mike");
		System.out.println(set);
 
		for (String name : set) {
			System.out.print(name + "\t");
		}
		System.out.println();
 
		for (Iterator<String> it = set.iterator(); it.hasNext();) {
			System.out.print(it.next() + "\t");
		}
		System.out.println();
	}
}

HashSet过滤重复元素

Name类

Name.java
package cn.edu.bjut.chapter6;
 
public class Name {
	private String firstName, lastName;
 
	public Name(String firstName, String lastName) {
		this.firstName = firstName;
		this.lastName = lastName;
	}
 
	public String getFirstName() {
		return firstName;
	}
 
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}
 
	public String getLastName() {
		return lastName;
	}
 
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}
 
	@Override
	public String toString() {
		return "[" + lastName + ", " + firstName + "]";
	}
 
	@Override
	public boolean equals(Object obj) {
		if ((obj == null) || !(obj instanceof Name)) {
			return false;
		}
 
		if (this == obj) {
			return true;
		}
 
		Name other = (Name) obj;
 
		return (firstName.equalsIgnoreCase(other.firstName) 
				&& lastName.equalsIgnoreCase(other.lastName));
	}
 
	@Override
	public int hashCode() {
		return (firstName.toLowerCase().hashCode() * 10 
				+ lastName.toLowerCase().hashCode());
	}
}

Name测试类

NameTester.java
package cn.edu.bjut.chapter6;
 
import java.util.HashSet;
import java.util.Set;
 
public class NameTester {
	public static void main(String[] args) {
		Set<Name> names = new HashSet<Name>();
		names.add(new Name("Albert", "Einstein"));
		names.add(new Name("albert", "einstein"));
		names.add(new Name("Issac", "Netwon"));
		names.add(new Name("issac", "Netwon"));
 
		System.out.println(names); // names中只有两个元素
	}
}

SortedSet的实现类:TreeSet

Name2类

Name2.java
package cn.edu.bjut.chapter6;
 
public class Name2 implements Comparable<Name2> {
	private String firstName, lastName;
 
	public Name2(String firstName, String lastName) {
		this.firstName = firstName;
		this.lastName = lastName;
	}
 
	public String getFirstName() {
		return firstName;
	}
 
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}
 
	public String getLastName() {
		return lastName;
	}
 
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}
 
	@Override
	public String toString() {
		return "[" + lastName + ", " + firstName + "]";
	}
 
	@Override
	public boolean equals(Object obj) {
		if ((obj == null) || !(obj instanceof Name2)) { return false; }
 
		if (this == obj) { return true; }
 
		Name2 other = (Name2) obj;
 
		return (firstName.equalsIgnoreCase(other.firstName) 
				&& lastName.equalsIgnoreCase(other.lastName));
	}
 
	@Override
	public int hashCode() {
		return (firstName.toLowerCase().hashCode() * 10 
				+ lastName.toLowerCase().hashCode());
	}
 
	@Override
	public int compareTo(Name2 name) {
		if (!lastName.equalsIgnoreCase(name.lastName)) {
			return lastName.compareTo(name.lastName); 
		} else {
			return firstName.compareTo(name.firstName); 
		}
	}
}

Name2测试类

Name2Tester.java
package cn.edu.bjut.chapter6;
 
import java.util.Comparator;
import java.util.Set;
import java.util.TreeSet;
 
public class Name2Tester {
	public static void main(String[] args) {
		Set<Name2> nameSet1 = new TreeSet<Name2>(); // 自然排序
		nameSet1.add(new Name2("Albert", "Einstein"));
		nameSet1.add(new Name2("Issac", "Netwon"));
		nameSet1.add(new Name2("Qiang", "Yang")); 
		nameSet1.add(new Name2("Prem", "Gopalan")); 
		nameSet1.add(new Name2("Jaewon", "Yang")); 
		System.out.println(nameSet1);
 
		Set<Name2> nameSet2 = new TreeSet<Name2>(new Comparator<Name2>() {
			@Override
			public int compare(Name2 arg0, Name2 arg1) {
				return arg0.getFirstName().compareToIgnoreCase(arg1.getFirstName());
			}
 
		}); // 自定义排序
 
		for (Name2 name: nameSet1) {
			nameSet2.add(name); 
		}
		System.out.println(nameSet2);
	}
}

匿名类

Rectangle.java
package cn.edu.bjut.chapter6;
 
public class Rectangle {
	private int length, width; 
 
	public Rectangle(int length, int width) {
		this.length = length; 
		this.width = width; 
	}
 
	public int getLength() {
		return length;
	}
 
	public void setLength(int length) {
		this.length = length;
	}
 
	public int getWidth() {
		return width;
	}
 
	public void setWidth(int width) {
		this.width = width;
	}
 
	public int perimeter() {
		System.out.println("长方形周长计算:");
		return 2 * (length + width); 
	}
}
AnonymousClassTester.java
package cn.edu.bjut.chapter6;
 
public class AnonymousClassTester {
	public void test() {
		// 创建的匿名类继承了Rectangle类
		Rectangle rect = new Rectangle(8, 8) {
			public int perimeter() {
				System.out.println("正方形周长计算:");
				return this.getLength() << 4; 
			}
		};
		System.out.println(rect.perimeter());
	}
 
	public static void main(String[] args) {
		AnonymousClassTester tester = new AnonymousClassTester();
		tester.test();
	}
}
Shape.java
package cn.edu.bjut.chapter6;
 
public interface Shape {
	void display(); 
}
AnonymousClassDemo.java
package cn.edu.bjut.chapter6;
 
public class AnonymousClassDemo {
	public void test() {
		Shape circle = new Shape() {
			@Override
			public void display() {
				System.out.println("This is a circle."); 
			}
		};
		circle.display();
	}
 
	public static void main(String[] args) {
		AnonymousClassDemo demo = new AnonymousClassDemo(); 
		demo.test();
	}
}

Map的实现类:实例

MapTester类

MapTester.java
package cn.edu.bjut.chapter6;
 
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
 
public class MapTester {
	public static void main(String[] args) {
		Map<String, Name> id2Names = new HashMap<String, Name>();
		id2Names.put("213456", new Name("Albert", "Einstein"));
		id2Names.put("123456", new Name("Albert", "Einstein"));
		id2Names.put("321456", new Name("Qiang", "Yang"));
		id2Names.put("456321", new Name("Qiang", "Yang"));
 
		System.out.println(id2Names);
		System.out.println(id2Names.keySet());
		System.out.println(id2Names.values());
 
		Map<String, Name> id2Names2 = new LinkedHashMap<String, Name>();
		id2Names2.put("213456", new Name("Albert", "Einstein"));
		id2Names2.put("123456", new Name("Albert", "Einstein"));
		id2Names2.put("321456", new Name("Qiang", "Yang"));
		id2Names2.put("456321", new Name("Qiang", "Yang"));
 
		System.out.println(id2Names2);
		System.out.println(id2Names2.keySet());
		System.out.println(id2Names2.values());
 
		for (Map.Entry<String, Name> entry : id2Names.entrySet()) {
			System.out.println(entry.getKey() + ":" + entry.getValue());
		}
	}
}

单词词频统计

WordCounter类

WordCounter.java
package cn.edu.bjut.chapter6;
 
import java.util.Map;
import java.util.TreeMap;
 
public class WordCounter {
	private String[] tokens;
	private Map<String, Integer> counter;
 
	public WordCounter(String[] tokens) {
		this.tokens = tokens;
		this.counter = new TreeMap<String, Integer>();
	}
 
	public void count() {
		for (String token : tokens) {
			if (counter.containsKey(token)) {
				int count = counter.get(token);
				counter.put(token, count + 1);
			} else {
				counter.put(token, 1);
			}
		}
	}
 
	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();
		for (Map.Entry<String, Integer> entry : counter.entrySet()) {
			sb.append(entry.getKey() + ": " + entry.getValue() + "\n");
		}
 
		return sb.toString();
	}
}

WordCounter测试类

WordCounterTester.java
package cn.edu.bjut.chapter6;
 
public class WordCounterTester {
	public static void main(String[] args) {
		String text = "1648年 , 牛顿 被 送去 读书 。 少年 时 的 牛顿 并 不是 " 
				+ "神童 , 他 成绩 一般 , 但 他 喜欢 读书 , 喜欢 看 "
				+ "一些 介绍 各种 简单 机械 模型 制作 方法 的 读物 ,  "
				+ "并 从中 受到 启发 , 自己 动手 制作 些 奇奇怪怪 的 " 
				+ "小  玩意 , 如 风车 、 木钟 、 折叠式 提灯 等等 。";
		String[] words = text.toLowerCase().split("\\s+");
 
		WordCounter wc = new WordCounter(words);
		wc.count();
		System.out.println(wc);
	}
}

WordCounter测试类2

WordCounterTester2.java
package cn.edu.bjut.chapter6;
 
import java.util.HashMap;
import java.util.Map;
 
public class WordCounterTester2 {
	public static void main(String[] args) {
		Map<String, WordCounter> map = new HashMap<String, WordCounter>();
 
		String[] ids = { "000089219800222", "000088691000018", "000166992000025" };
		String[] titles = { "Liposomal doxorubicin in the palliative treatment of head and neck cancer",
				"The long-term complications of chemotherapy in childhood genitourinary tumors",
				"Adenovirus-mediated tumor suppressor p53 gene therapy for anaplastic thyroid carcinoma in vitro and in vivo" };
 
		for (int i = 0; i < ids.length; i++) {
			WordCounter counter = new WordCounter(titles[i].toLowerCase().split("\\s+"));
			counter.count();
			map.put(ids[i], counter);
		}
 
		for (Map.Entry<String, WordCounter> entry : map.entrySet()) {
			System.out.println(entry.getKey());
			System.out.println(entry.getValue());
		}
	}
}

上机作业

  • 建立一个Corpus类,用于存储专利文献集合(每篇专利文献的信息见第五章最后一道上机作业),建立查询和删除方法,可根据专利申请号、申请日期、IPC分类号和CPC分类号查询和删除相应专利文献。

返回Java课程页

zh/courses/java2025/ch06.1742733230.txt.gz · 最后更改: 2025/03/23 20:33 由 pzczxs