英文:
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<String> list = Arrays.asList(
"cat","dog","apple",
"zebra","parrot");
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 = {"cat", "dog", "apple","zebra","parrot"};
Collections.sort(Arrays.asList(arr).subList(1,arr.length));
System.out.println(Arrays.toString(arr));
The output is the same as above.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论