欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

comparatable and comparator

程序员文章站 2022-04-06 15:34:00
...
package com.zhoubo.concurrent.collection;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
 * 通过实现comparable来实现对对象的排序。
 * @author Administrator
 *
 */
public class OrderList2 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		List list = new ArrayList();
		list.add(new B(1));
		list.add(new B(4));
		list.add(new B(2));
		list.add(new B(3));
		list.add(new B(3));
		//排序之前的顺序
		System.out.println(list);
		Collections.sort(list);
		//排序之后的顺序
		System.out.println(list);

	}

}

class A {
	public int i = 0;
	public A(int ii) {
		this.i = ii;
	}
	
	@Override
	public String toString() {
		return i+"";
	}
}

class B extends A implements Comparable{
	public B(int ii){
		super(ii);
	}
	
	@Override
	public int compareTo(Object arg0) {
		if(this.i > ((A)arg0).i)
			return 1;
		else if(this.i == ((A)arg0).i)
			return 0;
		else
			return -1;
	}
}

 

package com.zhoubo.concurrent.collection;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
 * 对list中的对象排序,使用comparator
 * @author Administrator
 *
 */
public class OrderList {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		List list = new ArrayList();
		list.add(new Aobject(1));
		list.add(new Aobject(4));
		list.add(new Aobject(2));
		list.add(new Aobject(3));
		list.add(new Aobject(3));
		System.out.println(list);
		Collections.sort(list,new Acomparator());
		System.out.println(list);
	}	

}
class Aobject {
	public int i = 0;
	public Aobject(int ii) {
		this.i = ii;
	}
	
	@Override
	public String toString() {
		return i+"";
	}
}

class Acomparator implements Comparator{
	@Override
	public int compare(Object arg0, Object arg1) {
		if(((Aobject)arg0).i >((Aobject)arg1).i){
			return 1;
		}else if(((Aobject)arg0).i ==((Aobject)arg1).i){
			return 0;
		}else
			return -1;
	}
	
}

 

相关标签: list