从自定义比较器获得布尔答案

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

Get a boolean answer from a custom Comparator

问题

我已经学会了如何创建自己的Comparator,例如,创建一个简单的比较器来基于绝对值进行比较。

class absComparator implements Comparator<Integer> {
    public int compare(Integer a, Integer b) {
        return a * a - b * b;
    }
}

当然,这可以用于自定义排序:

List<Integer> list_1 = new ArrayList<>(Arrays.asList(-3, -2, -1, 0, 1, 2));
list_1.sort(new absComparator());
// >>> [0, -1, 1, -2, 2, -3]

所以这都很好,但是如果我想要仅基于这个比较器比较两个整数,并得到一个布尔值,该怎么办?

// 目前:
System.out.println(-2 > 1);
// >>> false

那么,如何通过使用absComparator来比较-21,得到一个true呢?

英文:

I have learned how to create my own Comparator, for example, create a simple one to compare based on absolute value

class absComparator implements Comparator&lt;Integer&gt; {
    public int compare(Integer a, Integer b) {
        return a * a - b * b;
    }
}

And of course, this can be used for a customized sort:

List&lt;Integer&gt; list_1 = new ArrayList&lt;&gt;(Arrays.asList(-3, -2, -1, 0, 1, 2));
list_1.sort(new absComparator());
&gt;&gt;&gt; [0, -1, 1, -2, 2, -3]

So this is all good, but what if I want to just compare two Integers based on this comparator to give a boolean value?

// Currently:
System.out.println(-2&gt;1);
&gt;&gt;&gt; false

So how do I get a true by comparing -2 and 1, using absComparator?

答案1

得分: 6

调用 compare 函数并使用相同的关系运算符将结果与 0 进行比较。如果您想要检查 -2 > 1,请将这两个数字作为参数传递,并检查结果是否 > 0

Comparator<Integer> comparator = new absComparator();
System.out.println(comparator.compare(-2, 1) > 0);
英文:

Call compare directly and check the result against 0 using the same relational operator. If you want to check -2 &gt; 1, pass those two numbers in as parameters and check if the result is &gt; 0.

Comparator&lt;Integer&gt; comparator = new absComparator();
System.out.println(comparator.compare(-2, 1) &gt; 0);

</details>



# 答案2
**得分**: 2

IMO,应该在 [`Comparator`][1] 接口中添加类似于 `isGreaterThan`、`isLessThan` 的方法。由于目前接口中没有这些方法,我们可以创建一个扩展了 `Comparator` 接口的自定义接口,然后添加默认方法 `isGreaterThan` 和 `isLessThan`,如下所示:

```java
public interface EnhancedComparator<T> extends Comparator<T> {
    default boolean isGreaterThan(T target, T compareTo) {
        return this.compare(target, compareTo) > 0;
    }

    default boolean isLessThan(T target, T compareTo) {
        return this.compare(target, compareTo) < 0;
    }
}

public class AbsoluteValueComparator implements EnhancedComparator<Integer> {
    @Override
    public int compare(Integer a, Integer b) {
        a = Math.abs(a);
        b = Math.abs(b);
        return a.compareTo(b);
    }
}

public class EnhancedComparatorTest {
    public static void main(String[] args) {
        EnhancedComparator<Integer> absoluteValueComparator = new AbsoluteValueComparator();
        System.out.println("2 大于 3 " + absoluteValueComparator.isGreaterThan(2, 3));
        System.out.println("-3 大于 -2 " + absoluteValueComparator.isGreaterThan(-3, -2));
        System.out.println("2 小于 3 " + absoluteValueComparator.isLessThan(2, 3));
        System.out.println("-3 小于 -2 " + absoluteValueComparator.isLessThan(-3, -2));
    }
}

P.S.
a * a 可能会溢出,你可以参考我的示例来进行更健壮的比较。


参考资料
Java™ 教程 默认方法
Java 文档 Comparator
Java 如何处理整数下溢和上溢?如何检查?

英文:

IMO, method like isGreaterThan, isLessThan should be added to Comparator interface.
Since we don't have these in this moment, we can create our own interface extending Comparator, and add default method isGreaterThan, isLessThan, as follow:

public interface EnhancedComparator&lt;T&gt; extends Comparator&lt;T&gt; {
	default boolean isGreaterThan(T target, T compareTo) {
		return this.compare(target, compareTo) &gt; 0;
	}

	default boolean isLessThan(T target, T compareTo) {
		return this.compare(target, compareTo) &lt; 0;
	}
}

public class AbsoluteValueComparator implements EnhancedComparator&lt;Integer&gt; {
	@Override
	public int compare(Integer a, Integer b) {
		a = Math.abs(a);
		b = Math.abs(b);
		return a.compareTo(b);
	}
}

public class EnhancedComparatorTest {
	public static void main(String[] args) {
		EnhancedComparator&lt;Integer&gt; absoluteValueComparator = new AbsoluteValueComparator();
		System.out.println(&quot;2 greater than 3 &quot; + absoluteValueComparator.isGreaterThan(2, 3));
		System.out.println(&quot;-3 greater than -2 &quot; + absoluteValueComparator.isGreaterThan(-3, -2));
		System.out.println(&quot;2 less than 3 &quot; + absoluteValueComparator.isLessThan(2, 3));
		System.out.println(&quot;-3 less than -2 &quot; + absoluteValueComparator.isLessThan(-3, -2));
	}
}

P.S.
a * a may overflow, you may refer to my example for more robust comparison.


References
The Java™ Tutorials Default Method
Java Doc Comparator
How does Java handle integer underflows and overflows and how would you check for it?

答案3

得分: 1

Java不支持运算符重载。

话虽如此,你可以很容易地为其定义自己的静态方法:

private static final Comparator<Integer> ABS_CMP = new AbsComparator();
public static boolean gtAbs (int a, int b) {
    return ABS_CMP.compare(a, b) > 0;
}

然后静态导入并像使用运算符一样使用它:

import static your.UtilityClass.gteAbs;

[...]

int a = 5;
int b = -6;

if (gtAbs(a, b)) {
    // 进行操作
}
英文:

Java does not support operator overloading.

That being said, you can easily define your own static method for it:

private static final Comparator&lt;Integer&gt; ABS_CMP = new AbsComparator();
public static boolean gtAbs (int a, int b) {
return ABS_CMP.compare(a, b) &gt; 0;
}

And then import it statically and use it operator-like:

import static your.UtilityClass.gteAbs;

[...]

int a = 5;
int b = -6;

if (gtAbs(a,b)) {
    // do work
}

答案4

得分: 1

首先,您的问题在于您没有使用您的比较器。

class absComparator implements Comparator<Integer> {
    public int compare(Integer a, Integer b) {
        return a * a - b * b;
    }
}

absComparator comp = new absComparator();

if (comp.compare(-2, 1) > 0) {
    System.out.println(true);
}

但是您的比较器还存在一个更基本的问题。以下情况也会打印出 true。这是因为在减去乘积时存在整数溢出。

if (comp.compare(12345678, 123456789) > 0) {
    System.out.println(true);
}

为了纠正这个问题,将您的比较器编写如下:

class absComparator implements Comparator<Integer> {
    public int compare(Integer a, Integer b) {
        // 通过获取绝对值消除了对乘积的需求(Math.abs() 也可用);
        int a1 = a >= 0 ? a : -a;
        int b1 = b >= 0 ? b : -b;
        // 但是您仍然不应该进行减法,因为对于较大的 a1 和 b1 值,仍然可能发生溢出
        return a1 > b1 ? 1 : a1 < b1 ? -1 : 0;
        // 或者使用 return Integer.compare(a1, b1);
        // 或者 if (a1 > b1) {
        //          return 1;
        //      }
        //      if (a1 < b1) {
        //         return -1;
        //      }
        //      return 0;
    }
}
英文:

First, your problem is that you are not using your comparator.

class absComparator implements Comparator&lt;Integer&gt; {
public int compare(Integer a, Integer b) {
return a * a - b * b;
}
}
absComparator comp = new absComparator();
if (comp.compare(-2,1)) &gt; 0) {
System.out.println(true);
}

But your comparator has a more fundamental problem. The following also<br>
prints true. This is due to integer overflow when you subtract the products.

if (comp.compare(12345678, 123456789) &gt; 0) {		
System.out.println(true);
}

To correct the problem, write your comparator as follows:

class absComparator implements Comparator&lt;Integer&gt; {
public int compare(Integer a, Integer b) {
// eliminate the need for products by 
// getting abs (Math.abs() also available);      
int a1 = a &gt;= 0 ? a : -a;
int b1 = b &gt;= 0 ? b : -b;
// but you still should not subract as overflow can
// still happen for large values of a1 and b1
return a1 &gt; b1 ? 1 : a1 &lt; b1 ? -1 : 0;
// or return Integer.compare(a1,b1);
// or if (a1 &gt; b1) {
//         return 1;
//     }
//     if (a1 &lt; b1) {
//        return -1;
//     }
//     return 0;
}
}
</details>
# 答案5
**得分**: 0
使用您的比较器实例:
```java
absComparator comp = new absComparator();
int result = comp.compare(-2, 1);
if (result > 0) {
// -2 > 1(根据您的比较器)
}
英文:

Use an instance of your comparator:

absComparator comp = new absComparator();
int result = comp.compare(-2, 1);
if (result &gt; 0) {
// -2 &gt; 1 (according to your comparator)
}

huangapple
  • 本文由 发表于 2020年10月23日 21:43:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/64501174.html
匿名

发表评论

匿名网友

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

确定