Collection.sort()方法的工作不如预期。

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

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&lt;String&gt; x = new ArrayList&lt;&gt;();
        x.add(&quot;Liquid Egg Whites&quot;);
        x.add(&quot;LiquiFlav™&quot;);
        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.

huangapple
  • 本文由 发表于 2020年5月4日 23:16:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/61595601.html
匿名

发表评论

匿名网友

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

确定