1. 程式人生 > >集合操作集合排序,內容篩選

集合操作集合排序,內容篩選

集合操作集合排序,內容篩選

List集合使用Collections.sort()方法進行排序(必須實現Comparable介面,並重寫compareTo方法)

Set集合中的TreeSet集合,(實現Comparable介面,並重寫compareTo方法後可以自動排序)

Circle.java

public class Circle implements Shape ,Comparable<Circle>{
	public int r;
	static final double PI=3.14;
	public Circle(int r){
		this.r=r;
	}
	@Override
	public double GetArea() {
		return PI*r*r;
	}
	@Override
	public String toString() {
		return "Circle [r=" + r +","+"Area:"+GetArea()+ "]";
	}
	@Override
	public int compareTo(Circle arg0) {
		return this.r-arg0.r;
	}
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + r;
		return result;
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Circle other = (Circle) obj;
		if (r != other.r)
			return false;
		return true;
	}
	
}

Shape.java

public interface Shape {
	public double GetArea();
}
Test.java

import java.util.Iterator;
import java.util.Random;
import java.util.Set;
import java.util.TreeSet;

public class Test {
	static Set<Circle> set=new TreeSet<Circle>();
       public static void Initialise() {
			Random random=new Random();
		for(int i=0;i<20;i++){
			set.add(new Circle(random.nextInt(100)));
		}
	}
	public static void Shaixuan(){
		System.out.println(set.size());
		Iterator<Circle>it=set.iterator();
		while(it.hasNext()) {
			if(it.next().GetArea()<5000) {
				it.remove();
			}
		}
		for(Circle C:set){
				System.out.println(C);
			}			
	  System.out.println(set.size());
	}
	public static void main(String[] args) {
		 Initialise();
		 Shaixuan();		
	}
}