JAVA中Set集合--HashSet的使用


一、使用HashSet添加一個String類型的值:

 

public static void hashSet1(){
  HashSet<String> hashSet = new HashSet<String>();
  hashSet.add("java001");
  hashSet.add("java01");
  hashSet.add("java011");
  hashSet.add("java002");
  hashSet.add("java004");
 
  //使用常用迭代器獲取輸出內容
  Iterator<String> iterator = hashSet.iterator();
  while (iterator.hasNext()) {
    String next = iterator.next();
    System.out.println(next);
  }
}

 

二、使用HashSet添加一個對象:

public static void hashSet2(){
    HashSet<Student> hashSet = new HashSet<Student>();
    hashSet.add(new Student("zhangsan1", 21));
    hashSet.add(new Student("zhangsan1", 21));
    hashSet.add(new Student("zhangsan2", 21));
    hashSet.add(new Student("zhangsan3", 23));
    hashSet.add(new Student("zhangsan4", 24));
    //使用常用迭代器獲取值
    Iterator<Student> iterator = hashSet.iterator();
    while (iterator.hasNext()) {
        Student next = (Student) iterator.next();
        System.out.println(next.getName() + " " + next.getAge());
    }
}    

上面使用到的Student對象類:

 

class Student {
private String name;
private int age;
 
public Student(String name, int age) {
this.name = name;
this.age = age;
}
 
//復寫hashCode方法
@Override
public int hashCode() {
 
return 60;
}
 
//復寫equals方法
@Override
public boolean equals(Object arg0) {
if (!(arg0 instanceof Student)) {
return false;
}
Student studet = (Student) arg0;
return this.name.equals(studet.name) && this.age == studet.age;
}
 
public String getName() {
return name;
}
 
public void setName(String name) {
this.name = name;
}
 
public int getAge() {
return age;
}
 
public void setAge(int age) {
this.age = age;
}
}

 

最后使用調用main方法得出結果:

java004
java002
java011
java001
java01
-------------------------
zhangsan1 21
zhangsan2 21
zhangsan3 23
zhangsan4 24

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM