java使自定义类能够进行Collections比较


import java.util.*;

// 自定义类使用Collections进行比较时需要实现的函数
// implements Comparable<Test>
// public int compareTo(T obj)
// public String toString()
// public boolean equals(Object o)

//经典数据类型对自定义类的适配
class Test implements Comparable<Test>{
	public String line;
	public Integer num;
	public Boolean blen;
	
	public Test() {
		this.line = new String("NULL");
		this.num = 0;
		this.blen = false;
		this.printSelf();
	}
	
	public Test(String line,Integer num,Boolean blen) {
		this.line = line;
		this.num = num;
		this.blen = blen;
		this.printSelf();
	}
	
	// public int compareTo(T obj)
	public int compareTo(Test obj) {
		int result = 3;
		if(this.line.compareTo(obj.line) < 0) {
				result = -1;
		}else if(this.line.equals(obj.line)) {
				result = 0;
		}else {
				result = 1;
		}
		System.out.println("[Once] = " + result);
		return result;
	}

	// public String toString()
	@Override
	public String toString() {
		return "Test [line=" + line + ", num=" + num + ", blen=" + blen + "]";
	}
	
	public void printSelf() {
		System.out.println(this.toString());
	}
	
	//重写用于contains()函数
	// public boolean equals(Object o)
	@Override
	public boolean equals(Object obj) {
		if(obj == null) {
			return false;
		}else if(obj instanceof Test) {
			Test t = (Test)obj;
			if(this.line.equals(t.line) &&
				this.num.equals(t.num) &&
				this.blen.equals(t.blen)) {
				return true;
			}
		}
		return false;
	}
	
}


public class Main{
	public static void main(String[] args) {
		//链表
		List<Test> list = new ArrayList<Test>();
		list.add(new Test("asv",120,false));
		list.add(new Test("asd",123,true));
		list.add(new Test());
		list.add(new Test("asf",121,true));
		
//		//排序操作
//		Collections.sort(list);
//		
//		System.out.println("=======================");
//		
////		System.out.println(list);
//		for(int i=0;i<list.size();i++) {
//			System.out.println(list.get(i));
//		}
		
		//包含操作
		boolean ans = list.contains(new Test("asd",123,true));
		System.out.println(ans);
		//如果没有实现equals(Object)函数则返回值为false
	}
}

OK

上一篇:Hashtable,ConcurrentHashMap与Collections.synchronizedMap关键源码


下一篇:4-1 Python常用内置算法与数据结构常考题