sorting integers in a arraylist of objects

蹲街弑〆低调 提交于 2020-01-06 02:25:08

问题


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.

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());
    }
});

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


回答1:


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());
    }

});

Or by using Integer.compare();




回答2:


I'm guessing that getPrecio() returns int (a primitive). You can't call methods on primitives (they're not objects). You can call methods on objects, however, and if getPrecio() returns an Integer (the object counterpart to an int) then you should have more success (see here for more info on this aspect of Java, called boxing)

Alternatively you can compare the ints directly in your compare() method (e.g. if price1 < price2, return -1 etc.)




回答3:


try using

return uno.getPrecio-otro.getPrecio();

I hope getPrecio returns the price value




回答4:


What is the Type of the returning Value of getPrecio()? Have you defined the behavior of compareTo() in this Class? If you Type is int use the normal Operators >, < and == to compare the values and return the signum you want. Or simply use:

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



回答5:


Use this method to compare instead

public int compare(Articulo uno, Articulo otro)
{
    int comparation= (uno.getPrecio()> otro.getPrecio()) ? 1 : 0;
    if(comparation== 0)
    {
       comparation= (uno.getPrecio()== otro.getPrecio()) ? 0 : -1;
    }

return comparation;
}


来源:https://stackoverflow.com/questions/16934613/sorting-integers-in-a-arraylist-of-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!