gpt4 book ai didi

java - ArrayList 的排序顺序奇怪地丢失了,但为什么呢?

转载 作者:行者123 更新时间:2023-12-01 18:18:58 24 4
gpt4 key购买 nike

我创建了一个简单的 POJO 类 Person 和两个比较器“compareByValue”和“compareByIndex”来对 Person 类的 ArrayList 进行排序。我首先对 ArrayList 'persons' 进行排序,并在其他数组的循环内进行一些过滤操作。对于第一遍来说还可以,但是在循环的第二遍中,Arraylist“persons”的顺序立即丢失。我的代码有什么问题吗?使用 ArrayList 'persons' 完成的唯一操作是 subArray 调用,它会破坏列表的顺序吗?

class Result {
static class Person
{
public Person(int index,int value){
this.index=index;
this.value=value;
}

int index;
int value;

public int getValue() {
return value;
}

public int getIndex() {
return index;
}
}

public static Comparator<Person>compareByValue=new Comparator<Result.Person>()
{
@Override
public int compare(Person o1, Person o2) {
// TODO Auto-generated method stub
return o1.getValue()-o2.getValue();
}
};
public static Comparator<Person>compareByIndex=new Comparator<Result.Person>(){

@Override
public int compare(Person o1, Person o2) {

return o1.getIndex()-o2.getIndex();
}
};

public static int target(int targetValue,List<Person> persons)
{
int res=-1;
int s=0;
int e=persons.size()-1;

while(s<=e)
{
int m = (s+e)/2;
if(persons.get(m).getValue()<targetValue){
s=m+1;
}else{
res=m;
e=m-1;
}
}
return res;
}

public static List<Integer> kthPerson(int k, List<Integer> p, List<Integer> q) {

List<Person> persons=new ArrayList<>();
List<Integer> queryRes=new ArrayList<>();

for(int j=0;j<q.size();j++){
queryRes.add(0);
}

for(int j=0;j<p.size();j++)
{
Person person=new Person(j,p.get(j));
persons.add(person);
}

persons.sort(compareByValue);

for(int j=0;j<q.size();j++)
{
int targetIndex=target(q.get(j).intValue(), persons);
if(targetIndex==-1){continue;}

if(persons.size()-targetIndex>=k)
{
List<Person> targetPersons=persons.subList(targetIndex, persons.size());
targetPersons.sort(compareByIndex);
queryRes.set(j, targetPersons.get(k-1).getIndex()+1);
}
}
return queryRes;
}
}

最佳答案

subList() 方法不会更改任何顺序,但也不会返回新列表。 Javadoc :

Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive. (If fromIndex and toIndex are equal, the returned list is empty.) The returned list is backed by this list, so non-structural changes in the returned list are reflected in this list, and vice-versa.
...
(Structural modifications are those that change the size of this list, or otherwise perturb it in such a fashion that iterations in progress may yield incorrect results.)

这意味着如果子列表中的顺序发生更改,列表中也会反射(reflect)出相同的情况。如果不需要,请创建返回子列表的副本:

List<Person> targetPersons = new ArrayList(persons.subList(targetIndex, persons.size()));

我不明白问题中发布的代码的算法,这个答案主要基于问题文本

关于java - ArrayList 的排序顺序奇怪地丢失了,但为什么呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60314481/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com