如何编写 Java 布尔比较方法

How to write a Java boolean compare method

我在 Java 方面需要一些帮助。如果 int a = int b else false,如何将布尔比较方法编写为 return true。会不会是这样的:

public int checkIfEqual(int a, int b) {
  if (int a = int b) {
    return 1;
  } else {
    return -1;
  } 
}

I need some assistance with Java and how to write a boolean compare method to return true if int a = int b and false otherwise

a == b

a.Equals(b)(整数 class)

b.Equals(a)(整数class)

a-b == 0

b-a == 0

我认为足够进行相等性检查了。

现在进行其他检查...添加 if 与 && (a>x && a<y && b>x && b<y)

编辑:不使用 int 作为布尔值。这不是 C(其中 0 为假,!=0 为真),bool 是 bool,int 是 int。

保持简单:

public boolean compare(int a, int b) {
    return a == b;
}

我注意到你试图 return 一个 int: Java 不是 C,所以一些 C 习语如 0 是错误的,非-零是 true 不要保留在 Java.

还有,这样的方法还不如没用,因为:

  • if (a == b)if (compare(a, b))
  • 更短
  • if (a == b)if (compare(a, b))
  • 更清晰
  • compare() 实际上是一个保留字,因为它是 Comparator 接口的(唯一)方法,一个非常常用的 class
  • compare 是一个糟糕的名字,既有前面的原因,也因为 equals 是它真正在做的事情,是 java 约定

正如@Bohemian 所说,如果您只想测试两个 int 值是否相等:

public boolean equal(int a, int b) {
    return a == b;
}

不要调用此方法 compare,因为名称 compare 具有 强烈的含义 测试排序 ... 在 Java.它应该是 equal 还是 equals 值得商榷。

(@Bohemian 关于上述方法无用的观点是恰当的。)


这是实现 int compare(int, int) 的正确比较方法应该是这样的1.

public int compare(int a, int b) {
   if (a == b) {
      return 0;
   } else if (a < b) {
      return -1;
   } else {
      return 1;
   } 
}

这与 Comparator::compare(T, T) 的语义兼容。


I also am not sure how to add the following constraints as well:

0 ≤ a, b ≤ 10000000

添加 if 语句如下:

 if (a < 0 || b > 10000000) {
     throw SomeException("some message");
 }

其中 SomeException 是您应该抛出的异常以指示约束错误。


Also, do I need to create a checker class that implements the comparator interface as well?

检查器 class 应该实施 Comparator 没有具体原因。仅当您的检查器需要用作作为比较器时才这样做。


Would this also work the same for strings with the following constraints:

1 ≤ |a|, |b| ≤ 2000

方法 可用于限制字符串的长度。


1 - 向您展示代码比解释您的版本有什么问题要快。但是比较一下……你应该能算出来。