- import java.util.Arrays;
- import java.util.HashSet;
- class Person implements Comparable {
- private String name;
- int age;
- private int hashcode = 0;
- public Person(String n, int a) {
- name = n;
- age = a;
- for (int i = 0; i < name.length(); i++) {
- hashcode += name.charAt(i);
- }
- }
- public int compareTo(Object p) {
- return name.compareTo(((Person) p).name);
- }
- @Override
- public boolean equals(Object p) {
- return name.equals(((Person)p).name);
- }
- @Override
- public String toString() {
- return "(" + name + "," + age + ")";
- }
- }
- public class MapHashSet {
- public static void main(String[] ar) {
- HashSet hashset1 = new HashSet();
- hashset1.add(new Integer(40));
- hashset1.add(new Integer(60));
- System.out.println(hashset1);
- // 说明hashset里面的元素是会自动排序的
- hashset1.add(new Integer(50));
- System.out.println(hashset1);
- // 说明hashset 里面的元素是不可以重复的
- hashset1.add(new Integer(50));
- System.out.println(hashset1);
- System.out.println(hashset1.contains(new Integer(50)));
- System.out.println(hashset1.contains(new Integer(70)));
- HashSet hashset2 = new HashSet();
- hashset2.add(new Integer(30));
- hashset2.add(new Integer(40));
- hashset2.add(new Integer(50));
- System.out.println(hashset2);
- hashset1.addAll(hashset2);
- System.out.println(hashset2);
- hashset1.removeAll(hashset2);
- System.out.println(hashset1);
- hashset1.remove(new Integer(30));
- System.out.println(hashset1);
- hashset1.retainAll(hashset2);
- System.out.println(hashset1);
- hashset1.add(new Integer(60));
- System.out.println(hashset1);
- hashset1.removeAll(hashset2);
- System.out.println(hashset1);
- hashset1.add(null);
- System.out.println(hashset1);
- HashSet pSet = new HashSet();
- Person[] p = { new Person("Gregg", 25), new Person("Ann", 30),
- new Person("Bill", 20), new Person("Gregg",90),new Person("Kay", 30)};
- for(int i=0;i<p.length;i++){
- pSet.add(p[i]);
- }
- System.out.println(pSet);
- java.util.Iterator it= pSet.iterator();
- ((Person)it.next()).age=50;
- System.out.println(pSet);
- pSet.add(new Person("Craig",40));
- System.out.println(pSet);
- for(int i=0;i<p.length;i++){
- System.out.println(p[i]+" "+pSet.contains(p[i]));
- }
- Person[] pArray=(Person[])pSet.toArray(new Person[0]);
- for(int i=0;i<p.length;i++){
- System.out.println(pArray[i]+" ");
- System.out.println();
- }
- Arrays.sort(pArray);
- for(int i=0;i<p.length;i++){
- System.out.println(pArray[i]+"");
- }
- System.out.println();
- System.out.println(pSet);
- }
- }
HashSet为什么可以插入重复的项?
最新推荐文章于 2024-04-09 16:18:49 发布