Using Comparator/Comparable in Java 使用 Java 中的 Comparator/Comparable

huangapple go评论56阅读模式
英文:

Using Comparator/Comparable in Java

问题

I want to sort these elements ascending but "cat" should remain in first position. How can I implement in Java using comparator/comparable?

英文:

newbie to java. i have elements cat,dog,apple,zebra,parrot. I want to sort these elements ascending but "cat" should remain in first position. How can i implement in java using comparator/comparable?

答案1

得分: 1

最简单的方法是将它们放入一个列表中,然后对subList进行排序。

List<String> list = Arrays.asList(
    "cat", "dog", "apple",
    "zebra", "parrot");

Collections.sort(list.subList(1, list.size()));
System.out.println(list);

输出

[cat, apple, dog, parrot, zebra]

这是因为subList提供了列表的视图,所以排序操作在该视图上执行。

如果你更喜欢使用数组,你可以使用Arrays.asList将其转换为List,以便对subList进行排序。这也会使用数组作为列表的后端,所以对列表的更改会反映在数组中。这仅适用于对象数组(例如String[]Integer[]),但不适用于原始数组(例如int[]double[])。

String[] arr = {"cat", "dog", "apple", "zebra", "parrot"};
Collections.sort(Arrays.asList(arr).subList(1, arr.length));
System.out.println(Arrays.toString(arr));

输出与上面相同。

英文:

The easiest way is to put them in a list and sort a subList.

List&lt;String&gt; list = Arrays.asList(
		&quot;cat&quot;,&quot;dog&quot;,&quot;apple&quot;,
		&quot;zebra&quot;,&quot;parrot&quot;);

Collections.sort(list.subList(1,list.size()));
System.out.println(list);

Prints

[cat, apple, dog, parrot, zebra]

It works because a subList gives a view of the list so the sort operates on that view.

If you prefer to stick with arrays, you can employ Arrays.asList to convert to a List for the subList sort. This also uses the array to back the list so changes to the list are reflected in the array. This only works for Object arrays (e.g. String[], Integer[]) but not primitive arrays (e.g. int[], double[]).

String[] arr = {&quot;cat&quot;, &quot;dog&quot;, &quot;apple&quot;,&quot;zebra&quot;,&quot;parrot&quot;};
Collections.sort(Arrays.asList(arr).subList(1,arr.length));
System.out.println(Arrays.toString(arr));

The output is the same as above.

huangapple
  • 本文由 发表于 2020年8月2日 23:52:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/63218067.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定