我有一个充满对象的数组列表。每个对象由两个整数组成。如何根据第一个整数对数组列表进行排序,同时保留第二个整数与其原始整数?然后如何添加排序后的数组列表的所有第二个整数?
我尝试过这个:
Collections.sort(info, new Comparator()
{
public int compare(M one, M two)
{
return m1.getCost().compareToIgnoreCase(m2.getCost());
}
});
class M{
//Declares the attributes belonging to this class
private int money;
private int cost;
//Constructor method
{
//this refers to object in which the method was called
this.cost = cost;
this.money = money;
}
//Returns the cost variable
public int getCost()
{
return cost;
}
public void setCost(int cost)
{
this.cost = cost;
}
//Returns the maximum amount
public int getMoney()
{
return money;
}
public void setMoney(int Money)
{
this.Money = Money;
}
}
我是java新手,因此我们将不胜感激(:
最佳答案
import java.util.*;
public class M implements Comparator<M>{
int i,j;
M(int a, int b){
i=a; j=b;
}
public int compare(M m1, M m2){
return (m1.i-m2.i);
}
public boolean equals(Object o){
if(this.i==((M)o).i)
return true;
else
return false;
}
public static void main(String args[]){
M m1 = new M(2,1);
M m2 = new M(3,2);
M m3 = new M(1,3);
ArrayList<M> a = new ArrayList<M>();
a.add(m1);
a.add(m2);
a.add(m3);
Collections.sort(a,(Comparator<M>)m1);
//ArrayList a is sorted
for(int j=0;j<a.size();j++){
System.out.println(a.get(j).i);
}
}
}
在类中实现 Comparator 接口(interface),以便 Collections.sort 方法将使用类 M 的 int1 对对象进行排序。然后使用 Collections.sort 方法对数组进行排序。这应该回答问题的第一部分。
关于java - 如何对对象数组列表中的整数进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14117093/