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

java容器中对对象的不同属性排序的实现

程序员文章站 2024-01-13 22:30:04
...
package shuZu;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

class Stu{
	private int height=0;
	private int age=0;
	private String name=null;
	Stu(int height,int age,String name){
		this.name=name;
		this.age=age;
		this.height=height;
		
	}
	public int getHeight() {
		return height;
	}
	public void setHeight(int height) {
		this.height = height;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	@Override
	public String toString() {
		// TODO Auto-generated method stub
		return getName()+"   "+getHeight()+"   "+getAge();
	}
	
	
}
public class listPaiXu {
	 @SuppressWarnings("unchecked")
	public static void main(String[] args) {
		 Stu a[]=new Stu[5];
//		 for(Stu e:a) {
//			int i=10;
//			
//			 e=new Stu(i,22,"wqdqd");
//			 i--;
//		 }
		 a[0]=new Stu(24,22,"赵");
		 a[1]=new Stu(23,22,"钱");
		 a[2]=new Stu(44,22,"孙");
		 a[3]=new Stu(2242,22,"李");
		 a[4]=new Stu(222,22,"王");
		 ArrayList<Stu> al=new ArrayList<Stu>();
		 for(Stu e:a) {
			al.add(e);
		 }
      Collections.sort(al,new m());		 
      for(Stu e:al) {
			System.out.println(e.toString());
		 }
	 }

}
class m implements Comparator{
	
	@Override
	public int compare(Object o1, Object o2) {
		// TODO Auto-generated method stub
		Stu s1=(Stu)o1;//要进行对象类型转换
		Stu s2=(Stu)o2;
		return s2.getHeight()-s1.getHeight();
	}
}

 

相关标签: jav 比较