我正在创建一个方法来添加到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);
}
}