JAVA集合类(3):Set集合

JAVA集合类(3):Set集合_第1张图片

JAVA集合类(3):Set集合_第2张图片

JAVA集合类(3):Set集合_第3张图片

JAVA集合类(3):Set集合_第4张图片

 

Eclipse提供了快捷重写equals与hashCode的方法:在Source工具栏中提供了快捷方法:

package com.test.array;

import java.util.HashSet;

public class HashTest {
	public static void main(String[] args) {
		HashSet set = new HashSet();
		set.add(new Person("lisi"));
		set.add(new Person("lisi"));
		
		System.out.println(set);
	}
}

class Person{
	String name;
	public Person(String name){
		this.name = name;
	}
	
	public int hashCode() {
		return this.name.hashCode();
	}
	
	public boolean equals(Object obj) {
		if(this == obj){
			return true;
		}
		if(obj != null && obj instanceof Person){
			Person p = (Person)obj;
			if(name.equals(p.name)){
				return true;
			}
		}
		return false;
	}
}

 

结果只打印出了一个对象

 JAVA集合类(3):Set集合_第5张图片

 

package com.test.array;

import java.util.HashSet;
import java.util.Iterator;

public class IteratorTest {
	public static void main(String[] args) {
		HashSet set = new HashSet();
		set.add("a");
		set.add("b");
		set.add("c");
		set.add("d");
		set.add("e");
		Iterator iter = set.iterator();
		while(iter.hasNext()){
			String value = (String)iter.next();
			System.out.println(value);
		}
	}
}

也可使用for循环迭代

for(Iterator iter = set.iterator();iter.hasNext();){
			String value = (String)iter.next();
			System.out.println(value);
		}

  

 

下例中的TreeSet必须要有一个comparator类,才能往里添加Student对象,否则会抛出ClassCastException

package com.test.array;

import java.util.Comparator;
import java.util.TreeSet;

public class TreeSetTest {
	public static void main(String[] args) {
		TreeSet set = new TreeSet(new StudentComparator());
		set.add(new Student(80));
		set.add(new Student(90));
		set.add(new Student(60));
		set.add(new Student(70));
		
		System.out.println(set);
	}
}

class Student{
	int score;

	public Student(int score) {
		this.score = score;
	}
	
	public String toString() {
		return String.valueOf(score);
	}
}

class StudentComparator implements Comparator{

	//按学生成绩升序 
	public int compare(Object o1, Object o2) {
		Student s1 =(Student)o1;
		Student s2 =(Student)o2;
		return s1.score - s2.score;
	}
	
}







 

 

你可能感兴趣的:(java集合)