简体   繁体   English

函数中的Collection.sort(arraylist)对另一个arraylist进行排序

[英]Collection.sort(arraylist) in a function sorting another arraylist

say, I made an arraylist in (public class class1(String args[])) 说,我在(公共类class1(String args []))中创建了一个arraylist

static List<Double> list1 = new ArrayList<Double>();

then I pass this arraylist to a function in (public static void main(String args[])) 然后我将此arraylist传递给(public static void main(String args []))中的一个函数

biggestvalue(list1);

this is the function for example: 这是函数,例如:

public static double biggestvalue(List<Double> list){
    Collections.sort(list);
    return list.get(list.size()-1);
}

I pass it into a function so that hopefully it will only sort list but not list1, but then list1 gets sorted as well, and I do not understand why that is. 我将其传递给一个函数,以便希望它仅对list排序,而不对list1排序,然后对list1也进行排序,我不明白为什么这样做。 Therefore, please explain to me why that is, and what solutions to this error are out there? 因此,请向我解释为什么会这样,对于该错误有什么解决方案?

You only pass a reference to the List when you pass it as an argument. 仅当将List作为参数传递时,才传递对List的引用。 Therefore, both list and list1 point to the same List . 因此, listlist1指向相同的List

A good rule of thumb is to not modify objects passed into a method, so I would make a copy inside the method: 一个好的经验法则是不要修改传递给方法的对象,因此我将在方法内部进行复制:

public static double biggestvalue(List<Double> list){
    List<Double> temp = new ArrayList<>(list);
    Collections.sort(temp);
    return temp.get(temp.size()-1);
}

list1 gets sorted as well because you are passing a reference to that object. list1得到排序,因为您正在传递对该对象的引用。 You want to duplicate the list before sorting it, so the original object doesn't get modified: 您要在对列表进行排序之前复制它,因此原始对象不会被修改:

List<Double> dup = new ArrayList<>(list);
Collections.sort(dup);
return dup.get(dup.size() - 1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM