java - 如何对对象数组列表中的整数进行排序?

标签 java arrays object

我有一个充满对象的数组列表。每个对象由两个整数组成。如何根据第一个整数对数组列表进行排序,同时保留第二个整数与其原始整数?然后如何添加排序后的数组列表的所有第二个整数?

我尝试过这个:

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/

相关文章:

java - 放置在 fragment 中时不显示此处的 map

c++ - 在 C/C++ 中传递多维数组

javascript - 使用Google脚本数组中的搜索功能

JavaScript - 操作对象的嵌套多维数组

java - Dataweave 停止从输入负载端的查询中拾取 Java linkedList 数据

java - 将Java类结构转换为yml文件

java - 在 Controller 中处理删除请求的正确方法是什么?

c - 为什么 * 需要指向数组的指针?

class - 我如何在 Forth 中创建一个基本类和该类的实例?

oop - "No appropriate method"使用类定义对象调用新函数时产生错误