PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, November 5, 2022

[FIXED] Why my lambda is not applicable for comparator?

 November 05, 2022     comparator, java, lambda     No comments   

Issue

At first, I write the following code, but it can't build. Arrays.sort(n, (o1 ,o2) -> o1 % 2 == 0 ? 1 : -1); enter image description here

And then , I write another code to test it. Arrays.sort(n,(o1, o2) -> o1 - o2); but it has a same error message in vs code. And then , I try those code in IDEA , and it has different error messages in the following pictureenter image description here it says Operator '-' cannot be applied to 'T', 'T. And then , I rewrite the code : Arrays.sort(n,(int o1, int o2) -> o1 - o2); enter image description here I don't know why my code doesn't work. And I found the code I write yesterday: Arrays.sort(envelopes,(int []o1,int []o2) -> o1[0] == o2[0] ? o2[1] - o1[1] :o1[0] - o2[0]); and it works well.


Solution

You're experiencing one of the warts of Java's type system that made the otherwise nicely backwards compatible lambdas awkward — int is a primitive type.

There are no generics over primitive types (yet), so there is no Comparator<int>. The signature of the sort method you're trying to use is

public static <T> void sort(T[] a, Comparator<? super T> c)

and T cannot be int (or short, byte, etc.).

One way around this is to box your ints, e.g. with a stream:

Arrays.stream(n).boxed().sorted((i1, i2) -> i1 % 2 == 0 ? 1 : -1)


Answered By - OhleC
Answer Checked By - Terry (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing