现在有如下情况class A{
int a;
ArrayList<A> arrayList = new ArrayList<A>;
//.........
}
现在有这样的需求,
需要对arrayList进行排序,排序的时候呢,要用到arrayList与持有这个arrayList的某A对象的成员a进行一系列运算得到的值。
本想使用Comparator或comparable接口实现操作,但在调用时,无法同时获取到arrayList和成员a。
但想到的一个实现方法是,自己写一个排序方法调用。
但请问是否可以通过java本身提供的一些接口实现
int a;
ArrayList<A> arrayList = new ArrayList<A>;
//.........
}
现在有这样的需求,
需要对arrayList进行排序,排序的时候呢,要用到arrayList与持有这个arrayList的某A对象的成员a进行一系列运算得到的值。
本想使用Comparator或comparable接口实现操作,但在调用时,无法同时获取到arrayList和成员a。
但想到的一个实现方法是,自己写一个排序方法调用。
但请问是否可以通过java本身提供的一些接口实现
public static void main(String[] args) {
List<A> list = new ArrayList<A>();
list.add(new A(1));
list.add(new A(5));
list.add(new A(6));
list.add(new A(2)); Collections.sort(list, new Comparator<A>() {
public int compare(A a, A b) {
return a.getA() - b.getA();
}
}); System.out.println(list);
}
}class A {
int a; public A(int a) {
this.a = a;
} public int getA() {
return a;
} @Override
public String toString() {
return "" + a;
}
}
int a;
ArrayList<A> arrayList = new ArrayList<A>;
void sort(){
final int thisA = this.a;
Collections.sort(arrayList, new Comparator<A>(){
public int compare(A a1, A a2) {
//a1.a, a2.a, thisA
}
});
}
}
实际上是这样的:麻烦你看一下,我不清楚的地方就在于,在sort方法,我会传入一个List,但不知道该List由谁持有,如果其他的建议不使用我当前方法,也是可以的
class Item{
int attA; //属性A,B,每个对象不同
int attB;
public int calcSometing(Item item){
return attA * item.attA + attB * attB;
}
//需要对此列表根据
//持有该列表的对象 对 该列表中的各个对象的调用
//calcSometing方法进行计算后得分排序
public ArrayList<Item> ItemList;
}
实际上是这样的:麻烦你看一下,我不清楚的地方就在于,在sort方法,我会传入一个List,但不知道该List由谁持有,如果其他的建议不使用我当前方法,也是可以的
class Item{
int attA; //属性A,B,每个对象不同
int attB;
public int calcSometing(Item item){
return attA * item.attA + attB * attB;
}
//需要对此列表根据
//持有该列表的对象 对 该列表中的各个对象的调用
//calcSometing方法进行计算后得分排序
public ArrayList<Item> ItemList;
}
呃,想清楚了,直接在Item类中写个方法调用排序就行了,打打字把问题描述清楚,就想通了