java Compratorインターフェース
3186 ワード
Compratorインターフェース:compare()とequals()の方法があり、オブジェクトのある属性の大きさを比較するために使用されます。
このときも使用します。配列は、オブジェクトを配列に入れます。
collection.sort()の方法を利用して、オブジェクトのある属性の比較を実現します。
collections.sort()この方法はCompratorインターフェースを呼び出して種類の書き換えを実現するcomple()方法があります。
主要コード:
このときも使用します。配列は、オブジェクトを配列に入れます。
collection.sort()の方法を利用して、オブジェクトのある属性の比較を実現します。
collections.sort()この方法はCompratorインターフェースを呼び出して種類の書き換えを実現するcomple()方法があります。
主要コード:
List list = new ArrayList();
/* list.add() , */
ComparatorClass compare = new ComparatorClass();
Collections.sort(list,compare);
簡単な例で説明します。package com.learn.notes;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* @ClassName ComparatorTest
* @Description TODO
*
* @author XingZhaohu [email protected]
* @date 2016-3-30 10:05:09
*/
public class ComparatorTest {
/**
* @Title main
* @Description TODO
* @param args
* @return void
*
* @author XingZhaohu [email protected]
* @date 2016-3-30 10:05:09
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Students[] students = new Students[3];
students[0] = new Students(" "," ",19,110);
students[1] = new Students(" "," ",18,111);
students[2] = new Students(" "," ",20,112);
List list = new ArrayList();
for(Students s:students)
list.add(s);
Compares compare = new Compares();
Collections.sort(list,compare);
for(Students ss:(List<Students>)list)
System.out.println(ss.toString());
}
}
/**
*
* @ClassName Person
* @Description TODO
*
* @author XingZhaohu [email protected]
* @date 2016-3-30 10:40:09
*/
class Person{
private String name;
private String sex;
private int age;
public Person(String name,String sex,int age){
this.sex = sex;
this.name = name;
this.age = age;
}
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public String getSex(){
return sex;
}
public void setSex(String sex){
this.sex = sex;
}
public int getAge(){
return age;
}
public void setAge(int age){
this.age = age;
}
}
/**
*
* @ClassName Students
* @Description TODO
*
* @author XingZhaohu [email protected]
* @date 2016-3-30 10:40:20
*/
class Students extends Person{
private int id;
public Students(String name,String sex,int age,int id){
super(name,sex,age);
this.id = id;
}
public void setId(int id){
this.id = id;
}
public int getId(){
return id;
}
public String toString(){
return "name="+super.getName()+" sex="+super.getSex()+" age="+super.getAge()+" id="+this.getId();
}
}
/**
*
* @ClassName Compares
* @Description TODO
*
* @author XingZhaohu [email protected]
* @date 2016-3-30 10:39:44
*/
class Compares implements Comparator<Students>{
/* (non-Javadoc)
* @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
*/
@Override
public int compare(Students o1, Students o2) {
// TODO Auto-generated method stub
if(o1.getAge()>o2.getAge())
return 1;
else if(o1.getAge()<o2.getAge())
return -1;
else
return 0;
}
}