【Java】对ArrayList排序

java如何对ArrayList中对象按照该对象某属性排序

(从小到大)

两种方法:

方法一:
Comparator<KNNNode> comparator = new Comparator<KNNNode>() { @Override public int compare(KNNNode o1, KNNNode o2) { System.out.println("进入 compare function"); // TODO Auto-generated method stub if (o1.getDistance() <= o2.getDistance()) {//o1属性小于等于o2属性时,返回1 return 1; } else { return -1; } } };

 

调用方法:

List<KNNNode> nodelist = new ArrayList<KNNNode>();
//此处需要填充nodelist.add();
Collections.sort(nodelist, comparator);// 调用

 

 

 

方法二:
class SortBy implements Comparator { public int compare(Object obj1, Object obj2) { KNNNode point1 = (KNNNode) obj1; KNNNode point2 = (KNNNode) obj2; if (point1.getDistance() <= point2.getDistance()) { return 1; } else { return 0; } } }

 

调用方法:

Collections.sort(nodelist, new SortBy());

KNNNode结点内的属性:

package newKNN;

/**
 * KNN结点类,用来存储最近邻的k个元组相关的信息
 */
public class KNNNode {
	private int index; // 元组标号
	private double distance; // 与测试元组的距离
	private String seq;//滑动窗口motif序列片段
	
	public KNNNode(int index, double distance, String seq) {
		super();
		this.index = index;
		this.distance = distance;
		this.seq = seq;
		
	}
	public int getIndex() {
		return index;
	}
	public void setIndex(int index) {
		this.index = index;
	}
	public double getDistance() {
		return distance;
	}
	public void setDistance(double distance) {
		this.distance = distance;
	}
	public String getSeq() {
		return seq;
	}
	public void setSeq(String seq) {
		this.seq = seq;
	}
	
}

 我想要按照KNNNode的distance属性排序。

 

 

若要按照从大到小的顺序排序,如果只是将

>=返回值改为-1

<返回值改为1 会出现异常。

Comparison method violates its general contract!

 原因是是实现接口Comparator 的类有问题在compare中没有处理好两个比较的对象相等的情况

public int compare(KNNNode o1, KNNNode o2);

即 o1.getDistance() == o2.getDistance() 时,返回值不是0

我最终的实现代码是:(从大到小排序)

Comparator<KNNNode> comparator = new Comparator<KNNNode>() {

		@Override
		public int compare(KNNNode o1, KNNNode o2) {
			// TODO Auto-generated method stub
			if (o1.getDistance() < o2.getDistance()) {
				return 1;
			} else if(o1.getDistance() > o2.getDistance()){
				return -1;
			}else{
				return 0;
			}
		}

	};

 

参考列表:

http://blog.csdn.net/telenewbie/article/details/45061089

http://www.cnblogs.com/xujian2014/p/5215082.html

http://www.cnblogs.com/fzzl/archive/2010/08/14/1799408.html

 

posted @ 2017-10-23 16:52  于淼  阅读(4808)  评论(0编辑  收藏  举报