简体   繁体   中英

How comparator in 2d Array set ascending and decending order based on return values in java

I was practicing a leetcode problem in java, in one of the solution I find out that a user posted a code in which Array is sorted based on using comparator. I did a small Rnd of comparator in reference website, I got to know it is used for setting sorting order (ascending or descending). Then I opened my IDE to practice the same so I wrote the particular code. but while coding I scretched my mind that it was returing -1 0 & 1. So How Will I got to know it will be sent on descending or ascending.

And Most Important thing HOW COMPARATOR IS WORKING ON THE FOLLOWING INPUT.

 int ar [][]= {{7,0}, {4,4}, {7,1}, {5,0}, {6,1}, {5,2}};
 Arrays.sort(ar,(a,b)-> a[0]>b[0]?1:-1);

    System.out.println(Arrays.deepToString(ar));

Guys I am new to programming please explain in depth, the process of sorting in the above example.

Comparator interface is used to order the objects of user-defined classes. A comparator object is capable of comparing two objects of two different classes. Following function compare obj1 with obj2

Syntax:

public int compare(Object obj1, Object obj2):

it retuern value indicate whether other object is equals, more of less to your object.

0 - if they are equal;
1 - if your object is greater;
-1 - if your object is lesser.

For your case

a[0]>b[0]?1:-1

you are just comparing 0 index of every subarray.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM