HashSet
这个程序将从System.in读取单词,将他们逐个添加到HashSet对象中,最后打印20个单词。
package set;import java.util.*;/*** 这个程序打印System.in中的不同单词,用来测试HashSet类*/public class SetTest{public static void main(String[] args){var words = new HashSet<String>();long totalTime = 0;try (var 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() + " 个不同的单词. " + totalTime + " 毫秒.");}}
可以在命令行中重定向系统输入:java set.SetTest < alice30.txt 。
下面这个名为 alice30.txt 的文本文件有5909个不同的单词
alice30.txt
TreeSet
下面的程序用两个TreeSet对象来组织Item对象,第一个按照编号排序,这是Item对象的默认排序顺序。第二个按照自定义的比较器来排序。
package set;import java.util.*;/*** 用两种方法来对Item对象进行排序*/public class TreeSetTest{public static void main(String[] args) {var tree1 = new TreeSet<Item>();tree1.add(new Item("Toaster", 1234));tree1.add(new Item("Widget", 4562));tree1.add(new Item("Modem", 9912));System.out.println(tree1);var tree2 = new TreeSet<Item>(new AComparator());tree2.addAll(tree1);System.out.println(tree2);}}class AComparator implements Comparator<Item> {@Overridepublic int compare(Item o1, Item o2) {return o1.getDescription().compareTo(o2.getDescription());}}
package set;import java.util.*;/*** 定义一个物品类,包含两个实例字段description和partNumber*/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;}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;var 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);}public String getDescription(){return description;}}
