public int compare(Integer o1, Integer o2) { return o2-o1; }
时间: 2024-02-15 09:50:24 浏览: 42
This is a Java method that compares two Integer objects and returns an integer value indicating their relative order.
The method takes two Integer objects as parameters: o1 and o2. It subtracts o1 from o2 and returns the result, which will be a negative integer if o2 is greater than o1, zero if they are equal, or a positive integer if o1 is greater than o2.
This method is useful for sorting Integer objects in descending order, as it will return a negative value when the second object is greater than the first, causing it to be placed before it in the sorted list.
相关问题
public List<List<Integer>> threeSum(int[] nums) { List<List<Integer>> res = new ArrayList<>(); int len = nums.length; if(len<3) return res; Arrays.sort(nums, new Comparator<Integer>() { public int compare(Integer o1, Integer o2) { return o1-o2; } });为什么这里的实现Comparator部分会出错
这段代码的问题在于`Arrays.sort`方法的第二个参数的类型不匹配。`Arrays.sort`方法有多个重载版本,其中一个版本的第二个参数是`Comparator`类型,用于指定排序规则。但是这个版本的`sort`方法的第二个参数是`Comparator`类型的数组,用于指定每个元素的排序规则。
因此,如果要使用`Comparator`指定排序规则,可以改为以下代码:
```java
Arrays.sort(nums);
for (int i = 0; i < len - 2; i++) {
if (i > 0 && nums[i] == nums[i - 1]) continue;
int left = i + 1, right = len - 1;
while (left < right) {
int sum = nums[i] + nums[left] + nums[right];
if (sum == 0) {
res.add(Arrays.asList(nums[i], nums[left], nums[right]));
left++;
right--;
while (left < right && nums[left] == nums[left - 1]) left++;
while (left < right && nums[right] == nums[right + 1]) right--;
} else if (sum < 0) {
left++;
} else {
right--;
}
}
}
return res;
```
这里的排序用的是`Arrays.sort(nums)`,没有使用`Comparator`,因为默认的排序规则就是升序排列。
Integer[] arr={2,3,1,5,6};Arrays.sort(arr, new Comparator<Integer>() {@Override public int compare(Integer o1, Integer o2) {return 0;}});这段代码中为什么Arrays一调用sort方法就能执行匿名内部类中的排序规则呢
这是因为`Arrays.sort()`方法接收一个`Comparator`对象作为其第二个参数,这个`Comparator`对象是用来比较数组元素的。在这个例子中,我们使用了一个匿名内部类来创建一个`Comparator`对象,并覆盖了`compare`方法,这个方法定义了两个参数`o1`和`o2`的比较规则。当我们调用`Arrays.sort(arr, new Comparator<Integer>() {...})`时,`sort`方法会按照`Comparator`对象的比较规则对数组进行排序。因此,我们可以在匿名内部类中定义任何我们想要的比较规则,以实现自定义的排序。