java多线程    Java入门    vsftp    ftp    linux配置    centos    FRP教程    HBase    Html5缓存    webp    zabbix    分布式    neo4j图数据库    

Comparator比较器对ArrayList排序

boy 男生 对象

package com.javaer.examples.sort;

public class Boy {
	String name;//姓名
	int score;// 分数
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getScore() {
		return score;
	}
	public void setScore(int score) {
		this.score = score;
	}
}

Comparator强行对某个对象collection进行整体排序的比较函数,可以将Comparator传递给Collections.sort或Arrays.sort。

比较算法

package com.javaer.examples.sort;

import java.util.Comparator;

public class MyComparator implements Comparator {
	
	//接口,必须实现的方法
	public int compare(Object o1, Object o2) {
		Boy p1 = (Boy) o1;
		Boy p2 = (Boy) o2;
		if (p1.score < p2.score)
			return 1;
		else if (p1.score > p2.score)
			return -1;
		else
			return 0;
	}
}

实际运用

package com.javaer.examples.sort;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ScoreSort{

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		List boys = new ArrayList();
		Boy b = new Boy();
		b.name = "tom";
		b.score = 89;
		boys.add(b);
		
		b = new Boy();
		b.name = "jim";
		b.score = 92;
		boys.add(b);
		
		b = new Boy();
		b.name = "jack";
		b.score = 77;
		boys.add(b);
		
		for(int i=0 ;i < boys.size();i++){
			b = (Boy)boys.get(i);
			System.out.println(b.name + " : " + b.score);
		}
		
		System.out.println("------------------------");
		
		MyComparator mc = new MyComparator();
		Collections.sort(boys,mc);  
		
		for(int i=0 ;i < boys.size();i++){
			b = (Boy)boys.get(i);
			System.out.println(b.name + " : " + b.score);
		}

		
		
	}

}


This entry was posted in JAVA and tagged , . Bookmark the permalink.
月小升QQ 2651044202, 技术交流QQ群 178491360
首发地址:月小升博客https://java-er.com/blog/comparator-sort-arraylist/
无特殊说明,文章均为月小升原创,欢迎转载,转载请注明本文地址,谢谢
您的评论是我写作的动力.

Leave a Reply