How do I organize a vector of objects by their attributes in java? (without arraylist)

0

I need to order a Person class vector, and sort it according to age, but without using the Array

  public class Person {
        byte[] years = new byte [5];
        private String name;
        Prueba pruebaObj = new Prueba();
        private byte year;
        public static Person[] listPerson;

public Person(String name, byte year){
    this.setName(name);
    this.setYears(year);
}

public void setName(String name) {
    this.name = name;
}
public String getName(){
    return this.name;
}
public void setYears(byte year) {
    this.year = year;
}
public byte getYear(){
    return this.year;
}
public Person[] person(){
    listPerson = new Person[5];
    listPerson[0] = new Person("pedro", (byte) 23);
    listPerson[1] = new Person("juan", (byte)34);
    listPerson[2] = new Person("pepe", (byte)45);
    listPerson[3] = new Person("pablo", (byte)12);
    listPerson[4] = new Person("nada", (byte)78);
    return listPerson;
}
    
asked by Yeferson Gallo 08.10.2016 в 03:45
source

1 answer

1

Perhaps the method Bubble , would be a valid option, the only thing we should take into account is the way to compare in if the attributes of the class.

for(int i=0;i<(listPerson.length-1);i++){
   for(int j=i+1;j<listPerson.length;j++){
      if(listPerson[i].getEdad()>listPerson[j].getEdad()){
         int aux=listPerson[i].getEdad();
         listPerson[i].setEdad(listPerson[j].getEdad());
         listPerson[j].setEdad((byte) aux);
        }
     }
  }

To compare the Strings Use the CompareTo where the return value can be

  • Positive number: chain 1 is greater than chain 2.
  • 0: the chains are the same.
  • Negative number: chain 1 is smaller than chain 2.

       /* Dentro de los dos for sería así. Forma Ascendente por atributo Nombre*/
       if(listPerson[i].getNombre().compareTo(listPerson[j].getNombre())>0){
          String aux=listPerson[i].getNombre();
          listPerson[i].setNombre(listPerson[j].getNombre());
          listPerson[j].setNombre(aux);
       }
    
answered by 08.10.2016 в 03:54