英文:
Collection.sort() method is not working as expected
问题
以下是翻译好的内容:
在产品列表页面上有一些产品。我正在自动化一个从A到Z的排序功能。为了交叉验证网站的排序选项是否正常工作,我正在将所有可用的产品添加到一个列表中,并使用Collection.sort()
方法,因为它的工作结果与预期不符。
这是我的代码片段:
public static void main(String[] args) {
List<String> x = new ArrayList<>();
x.add("Liquid Egg Whites");
x.add("LiquiFlav™");
Collections.sort(x);
System.out.println(x);
}
输出:
[LiquiFlav™, Liquid Egg Whites]
然而预期的结果应该是:
[Liquid Egg Whites, LiquiFlav™]
根据字母顺序,Liquid Egg Whites
应该排在前面。
有人能否请解释一下为什么会出现这种情况?并提供获取预期结果的其他方法。
英文:
There are some products on a Product Listing page. I'm automating a A-Z sorting functionality. To cross verify whether website sorting option working fine, I'm adding all available product in a list and using Collection.sort()
method as its not working as expected.
This is my piece of code looks like :
public static void main(String[] args) {
List<String> x = new ArrayList<>();
x.add("Liquid Egg Whites");
x.add("LiquiFlav™");
Collections.sort(x);
System.out.println(x);
}
Output:
[LiquiFlav™, Liquid Egg Whites]
While expected should be:
[Liquid Egg Whites, LiquiFlav™]
As per alphabetical order Liquid Egg Whites
should come first.
Can anyone please explain why this happening ? and other method to get the expected result.
答案1
得分: 4
根据字符串比较规则,大写字符优先于小写字符。
例如: "abcdefG" > "abcdefaa", "xyzA" > "xyza"
类似地,"LiquiFlav" > "Liquid Egg Whites"
因此,你收到的回复是正确的。
编辑: 你可以使用 Collections.sort(x, String.CASE_INSENSITIVE_ORDER) 来获得你所期望的输出。
英文:
According to string comparison rules, upper case characters have greater precedence over lower case characters
Eg : "abcdefG" > "abcdefaa", "xyzA" > "xyza"
Similarly, "LiquiFlav" > "Liquid Egg Whites"
So, the response you got is correct.
Edit : You can make use of Collections.sort(x,String.CASE_INSENSITIVE_ORDER) to get the output as you desired.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论