Sort Array using an int variable from another class


I am currently new to this java and I have a question about sorting arrays . I have this code in a previously created class.

public class Orden {

    int value;

    public Orden(){}

    public Orden(int value){

        this.value= value;

    public int getValue() {
        return value;

    public void setValue(int value) {
        this.value = value;


Then I have another class with the following:

public class Main {

    public static void main(String[] args) {

        int i;
        int j;
        int aux;
        Orden[] cosa=new Orden[10];

        cosa[1]= new Orden(5);
        cosa[2]= new Orden(9);
        cosa[3]= new Orden(55);
        cosa[4]= new Orden(88);
        cosa[5]= new Orden(44);
        cosa[6]= new Orden(66);
        cosa[7]= new Orden(33);
        cosa[8]= new Orden(33);
        cosa[9]= new Orden(44);
        cosa[0]= new Orden(88);




But I have an error in the line where cosa[j]=aux; is indicated. According to what I have been able to understand, it is because I am saving an object in a variable int , but I can not see how to save that value in the variable aux . Any recommendation?

asked by Jesus Figuera 06.04.2018 в 07:17

2 answers


You are using POO , then to assign the value to an attribute you should use the setter defined in your class in this way, plus the attribute should be private and not public .

private int value; // clase Orden


But apparently you try to apply the bubble method to order items which is incorrect I recommend reading the documentation on this method. Instead of declaring the temporary variable as a whole (int) declare it of the class type Orden as mentioned @PabloLozano (which in principle I did not take into account)

  int n = cosa.length;
    for (int i = 0; i < n-1; i++){
        for (int j = 0; j < n-i-1; j++){
            if (cosa[j].getValue() > cosa[j+1].getValue()){
                Orden temp = cosa[j];
                cosa[j]= cosa[j+ 1];
                cosa[j+1] = temp;

With Java8 it is easier to Order in the following way. (ascending, if you want descending, change the order p2.getValue () - p1.getValue ()) ;

Arrays.asList(cosa).sort((p1, p2) -> p1.getValue() - p2.getValue());
answered by 06.04.2018 / 07:24

You can define aux of type Order and simply make aux=cosa[i]; , it would be logical to exchange the objects of place in the array and not their values.

answered by 06.04.2018 в 08:38