-1

I am creating a method to add to an ArrayList which contains person objects, which has a name, address and age. It should order them from lowest to highest. Mine only works for if it does not end up in last place or is not empty, how can I write my code differently?

public void addAgeSorted(Person p){
 int a = 0;
 while(p.getAge() >= this.plist.get(a).getAge() ){
  a++;
  }
 this.plist.add(a,p);
}
Zissouu
  • 924
  • 2
  • 10
  • 17

5 Answers5

2

If you are using Java 8 or newer you can use a comparator, just add your person and then sort the list by the age.

plist.sort(Comparator.comparing(Person::getAge));
StefanE
  • 7,578
  • 10
  • 48
  • 75
0

look what you are trying to do:

 public void addAgeSorted(Person p){

why dont you use instead a prioryty queue?

Comparator<Person> foo = (o1, o2) -> Integer.compare(o1.getAge(), o2.getAge());

PriorityQueue<Person> queueOfPersons = new PriorityQueue<>(foo);

queueOfPersons.add(new Person(51));
queueOfPersons.add(new Person(23));
queueOfPersons.add(new Person(33));
queueOfPersons.add(new Person(1));

this is the right collection since it will sort the elements for you once you insert it...

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
0

Just write a comparator based on Person's age and use it.

Comparator<Person> c = new Comparator<Person>() {

    @Override
    public int compare(Person o1, Person o2) {
        return Integer.compare(o1.getAge(), o2.getAge());
    }
};
list.sort(c);
nagendra547
  • 5,672
  • 3
  • 29
  • 43
0
Collections.sort(personList, new Comparator<Person>() {
public int compare(Person p1, Person p2) {
    return p1.getAge().compareTo(p2.getAge());
}
}); 

This will work for your requirement

Kamal Chanda
  • 163
  • 2
  • 12
0

If i get it right you want to add objects to your already sorted persons list at a specific index. You can handle the two cases where your logic fails by adding a conditional check:

public void addAgeSorted(Person p){
    if(plist.isEmpty()){
        this.plist.add(p);
    }
    //if age of person to add higher than all in the list            
    else if(p.age > plist.get(plist.size()-1).getAge()) {
        this.plist.add(p);        
    }
    else{
        int a = 0;
        while(p.getAge() >= this.plist.get(a).getAge() ){
            a++;
        }
        this.plist.add(a,p);
    }
}
Eritrean
  • 15,851
  • 3
  • 22
  • 28