简体   繁体   中英

sorting integers in a arraylist of objects

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".

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

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 (eg if price1 < price2, return -1 etc.)

try using

return uno.getPrecio-otro.getPrecio();

I hope getPrecio returns the price value

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM