我正在創建一個方法來添加到ArrayList,其中包含具有名稱,地址和年齡的人物對象。它應該從最低到最高排序。我只適用於如果它不在最後的地方或不是空的,我怎樣才能以不同的方式寫我的代碼?添加到數組列表(按年齡)
public void addAgeSorted(Person p){
int a = 0;
while(p.getAge() >= this.plist.get(a).getAge()){
a++;
}
this.plist.add(a,p);
}
我正在創建一個方法來添加到ArrayList,其中包含具有名稱,地址和年齡的人物對象。它應該從最低到最高排序。我只適用於如果它不在最後的地方或不是空的,我怎樣才能以不同的方式寫我的代碼?添加到數組列表(按年齡)
public void addAgeSorted(Person p){
int a = 0;
while(p.getAge() >= this.plist.get(a).getAge()){
a++;
}
this.plist.add(a,p);
}
如果您使用的是Java 8或更新版本,你可以使用一個比較器,只需添加你的人,然後排序歲列表。
plist.sort(Comparator.comparing(Person::getAge));
看看你正在嘗試做的事:
public void addAgeSorted(Person p){
你爲什麼不改爲使用prioryty隊列?
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));
這是正確的收集,因爲它一旦你插入你的元素進行排序...
只要寫基於人的年齡比較,並使用它。
Comparator<Person> c = new Comparator<Person>() {
@Override
public int compare(Person o1, Person o2) {
return Integer.compare(o1.getAge(), o2.getAge());
}
};
list.sort(c);
Collections.sort(personList, new Comparator<Person>() {
public int compare(Person p1, Person p2) {
return p1.getAge().compareTo(p2.getAge());
}
});
這會爲你的需求
工作,如果我得到它的權利,你要的對象在特定的索引添加到您已經排序的人名單。您可以通過添加條件檢查來處理邏輯失敗的兩種情況:
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);
}
}