Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/344.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 用比较器对链表排序_Java_Sorting_Linked List_Comparator - Fatal编程技术网

Java 用比较器对链表排序

Java 用比较器对链表排序,java,sorting,linked-list,comparator,Java,Sorting,Linked List,Comparator,我有个问题。请看下面我的代码, 当我想使用collections.sort和comparator对链表上的数据进行排序时,在写入(collections.sort(…)之后,它会工作,然后再与comparator一起使用吗 是否可以先使用不带collection.sort(…)的比较器 谢谢您可以放弃对Collections.sort()的初始调用,只需使用comparator调用一次即可 您可以将比较器保存到一个静态字段,并将该字段传递给Collections.sort() 但是,您必须提供一

我有个问题。请看下面我的代码, 当我想使用collections.sort和comparator对链表上的数据进行排序时,在写入(collections.sort(…)之后,它会工作,然后再与comparator一起使用吗

是否可以先使用不带collection.sort(…)的比较器


谢谢

您可以放弃对
Collections.sort()的初始调用,只需使用comparator调用一次即可

您可以将比较器保存到一个静态字段,并将该字段传递给
Collections.sort()

但是,您必须提供一些方法来告诉jvm如何对元素排序(除非切换到整数列表)。请参见编辑:

作为最后一个注释,链表上的排序由于其线性复杂度(它必须在最坏情况下迭代每个节点)是昂贵的,考虑使用诸如<>代码>树> <代码>之类的,如先前建议的

。 编辑:如果升序足够,如果所有字符串都是数字,则不带比较器的字符串排序将按预期工作


此外,您的比较器正在处理字符串长度,因此这不会按预期的升序对列表进行排序

请在代码中尝试此操作

 Integer[] ints = {75, 2, 0, 1, 10, 25, 60, 40, 70, 2, 3, 4, 5, 6, 10, 15};
 List<Integer> lList = Arrays.asList(ints);
 final LinkedList unsorted = new LinkedList(lList);

 Collections.sort(unsorted);

 System.out.println("LinkedList (after sorting using Comparator): " + unsorted);
Integer[]int={75,2,0,1,10,25,60,40,70,2,3,4,5,6,10,15};
List-lList=Arrays.asList(ints);
最终未排序的LinkedList=新的LinkedList(lList);
集合。排序(未排序);
System.out.println(“LinkedList(使用比较器排序后):”+未排序);

列表本质上是未排序的集合,因为它们实现了队列接口,这需要后进先出行为。如果您想要一个沿途保持排序顺序的集合,请考虑使用<代码> TeSeSe< /Cord>。您可以直接运行<代码>集合。排序(未排序、比较器)< /C> >对列表进行排序。您可以使用
TreeMap
TreeSet
(如果没有重复的元素)在添加新元素时使其自动排序。哦,好的,我现在完全理解了。谢谢你的建议,但是你能给我创建静态字段的代码并把它传递给Collection.sort()吗?
Unsorted [75, 2, 0, 1, 10, 25, 60, 40, 70, 2, 3, 4, 5, 6, 10, 15]
LinkedList (after sorting using Comparator): [0, 1, 2, 2, 3, 4, 5, 6, 10, 10, 15, 25, 40, 60, 70, 75]
 Integer[] ints = {75, 2, 0, 1, 10, 25, 60, 40, 70, 2, 3, 4, 5, 6, 10, 15};
 List<Integer> lList = Arrays.asList(ints);
 final LinkedList unsorted = new LinkedList(lList);

 Collections.sort(unsorted);

 System.out.println("LinkedList (after sorting using Comparator): " + unsorted);