在对象的数组列表排序整数 [英] sorting integers in a arraylist of objects

查看:111
本文介绍了在对象的数组列表排序整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,对不起坏英语:(

first of all, sorry for bad English :(

好吧,我开始使用Java,我的问题是,我有对象的ArrayList(Articulos,是指文章),这个对象有自己的属性(如名称,价格等)。我想作为排序依据每个对象的价格ArrayList中。下面是我试过。

Well, I'm starting with Java, and my problem is that I have an Arraylist of objects("Articulos", means Articles), and this object has properties (like name, price, etc...). I want to sort the Arraylist by the price of each object. Here's what I've tried.

首先,我手动填写的ArrayList

First, I fill the Arraylist manually:

public static void Introducir_Articulo(){
        Articulo a=new Articulo();

        System.out.println("Codigo del articulo: "+(art.size()+1));
        if(a.codArt==0){
            a.codArt++;
        } else {
            a.codArt+=art.size();
        }
        System.out.println("Nombre del articulo: ");
        a.NombreArt=sc.next();

        System.out.println("Precio del articulo: ");
        a.precio=sc.nextInt();

        System.out.println("IVA del articulo: ");
        a.iva=sc.nextInt();

        art.add(a);
}

后来,我尝试这样做

Later, I tried this

//copying the arraylist, so I don't have to change the original
artOrdenado=new ArrayList<Articulo>(art);
System.out.println(artOrdenado);

Collections.sort(artOrdenado, new Comparator<Articulo>(){
    public int compare(Articulo uno, Articulo otro){
       return uno.getPrecio().compareTo(otro.getPrecio());
    }
});

但它抛出一个异常它说诠释不能deferenced。

but it throws an exception which says "int can not be deferenced".

推荐答案

您需要做的比较在你的比较是这样的:

You need to do the comparision in your comparator like this:

Collections.sort(artOrdenado, new Comparator<Articulo>(){
    public int compare(Articulo uno, Articulo otro){
        return (uno.getPrecio() - otro.getPrecio());
    }

});

通过使用的或> Integer.compare();

这篇关于在对象的数组列表排序整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆