21xrx.com
2024-11-08 21:19:43 Friday
登录
文章检索 我的文章 写文章
Java Source Does Not Support Diamond Operator in Sort
2023-06-15 16:10:16 深夜i     --     --
java source

, diamond operator, sort

In Java, the diamond operator is a shorthand notation for specifying the types of generic classes. It was introduced in Java 7 and has become a popular way of simplifying code. However, there is one area where the diamond operator cannot be used: sorting.

The reason for this is that the syntax of the sort method in the Collections class predates the introduction of the diamond operator. As a result, when you try to use the diamond operator with the sort method, you will get a syntax error.

For example, the following code will not compile:

List list = new ArrayList<>();

list.add("apple");

list.add("banana");

list.add("cherry");

Collections.sort(list, a -> a.length()); //error: cannot use diamond operator with anonymous class

To work around this limitation, you can use an anonymous inner class to specify the type of the Comparator interface, like this:

Collections.sort(list, new Comparator () {

  @Override

  public int compare(String o1, String o2) {

    return o1.length() - o2.length();

  }

});

Alternatively, you can use lambda expressions, which were introduced in Java 8:

Collections.sort(list, (a, b) -> a.length() - b.length());

In conclusion, while the diamond operator simplifies the syntax of generic classes in Java, it cannot be used with the sort method in the Collections class. To sort a list, you can use either anonymous inner classes or lambda expressions.

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复
    相似文章