“===”相当于 Java

“===” equivalent in Java

在比较 Java 中的两个值时,如何测试类型和值是否相等?

我知道 Java 中的脚本 === 可以用来完成此操作,所以我在 Java 中尝试过,但没有成功。

我知道这是一个简单的问题,但我尝试查找它却找不到它是什么。

Java没有真假的概念,因此没有严格的比较运算符

如果两个变量的类型不同,您将无法比较它们,因此在这种情况下 == 就足够了。如果它们不可转换,则会引发编译器错误。

=== 在弱类型语言中很有用,例如 Javascript,因为它验证被比较的对象是否属于同一类型并避免隐式转换。

=== 在 Java 等强类型语言中绝对没有用处,因为如果不编写特定的方法就无法比较不同类型的变量。

TL;DR

在Java中没有这样的比较运算符:===,而是==equals

更长的解释

弱类型 语言中,例如 JavaScript,您可以使用严格比较运算符 (===),因为该语言允许比较具有不同的 类型 .

例如,在Java脚本中,如果您这样做,您将不会得到编译错误

var x = 10;
var y = 'foo';
console.log(x == y); // false

这很有用,当您想要比较可能包含 "equals" 但可能属于不同类型的值的变量时。

例如

var x = 10;
var y = '10';
console.log(x == y)  // true
console.log(x === y) // false

强类型语言中,例如Java,你不需要使用严格的比较运算符,因为语言已经"handles"类型比较.

例如:

int x = 10;
String y = "10";
System.out.println("10" == y); // true
System.out.println(x == y);    // compile error : Incompatible operand types int and String

所以,基本上,在 Java 中,不需要使用 === 检查严格性(报告 语法错误 )。

首先,当你使用==运算符比较不同类型的值时,编译器会报错,无法执行conversion

在前面的 Java 代码示例中,如果您想比较 xy 可以使用 equals:

int x = 10;
String y = "10";
System.out.println(y.equals(x)); // compile warning: Unlikely argument type for equals(): int seems to be unrelated to String

作为旁注,请注意无法对基本类型调用 equals 方法。

一些有用的读物​​是:

  • 15.21. Equality Operators
  • What is the difference between a strongly typed language and a statically typed language?
  • What issues should be considered when overriding equals and hashCode in Java?

在 Java 中,您可以使用“==”比较基本类型,如 int、double、char、long、float。在这种情况下,比较值。 对于对象的比较,这是不够的,因为如果比较对象的标识相同,'==' 仅计算为 'true' - 'identity' 是存储对象的内存地址。这是因为所有 classes 都隐含地继承了 'Object' class 提供的所有方法,而 'equals()' 方法仅包含一个基本实现。因此,任何 class 其对象涉及比较,用于数据结构或在它自己的包之外应该包含 equals() 和 hashCode() 方法的可靠实现 提供正确的功能。

注意以下实现:

public class MyClass {

  private final int val;
  private final String name;

  public MyClass(int val, String name) {
     this.val = val;
     this.name = name;
  }

  public int getVal() { return val; }

  public String getName() { return name; }

  public boolean equals(Object o) {
     if(o == null) return false;
     if(this == o) return true;
     if(!this.getClass().getSimpleName().equals(o.getClass().getSimpleName()) return false;

     MyClass other = (MyClass) o;

     return this.getVal() == other.getVal() && this.getName().equals(other.getName());
  }

  public int hashCode() { ... }

}

另请查看官方 Java API 了解更多信息 https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html .

没有用于比较的===运算符。当你想比较两个参考时,你应该检查 - 1. 如果他们指向同一个对象。

if(firstreference==secondreference) 
  1. 如果上面的条件 1 不满足,那么你应该通过 instanceof 运算符检查它们的类型:
if (secondreference instanctof classoffirstreference)
  1. 如果上面的条件 2 满足,那么您应该检查 属性 等号运算符的比较,例如
firstreference.property1.equals(secondreference.property1)
//do this for all properties.

我做了一个函数,r复制了JavaJava脚本中===的功能Java

static boolean compareData(Object v1, Object v2)
{
    if(v1 != null && v2 != null)
        return (v1.getClass() == v2.getClass() && (v1.toString().equals(v2.toString())));
    else
    {
        return (v1 == null ? v2 == null : v1.equals(v2));
    }
}

我能够将任何数据类型(数组除外)的值传递给此函数,并且仅当数据类型和值得到 true 时match 否则它 returns false。 List 和 HashMap 等派生数据类型也适用.

对该函数的调用如下所示:

float s1 = 0.f;
float s2 = 0.1f;

System.out.println(compareData(s1, s2)); //Returns false

float s1 = 0.0f;
float s2 = 0.0f;

System.out.println(compareData(s1, s2)); //Returns true

float s1 = 0.1f;
String s2 = "0.1f";

System.out.println(compareData(s1, s2)); //Returns false 

String s1 = "sdf";
String s2 = null;

System.out.println(compareData(s1, s2)); //Returns false 

String s1 = null;
String s2 = null;

System.out.println(compareData(s1, s2)); //Returns true

等等...

更新:也设法比较数组,下面是代码片段,但是,我还没有深入测试这段代码但对我执行的每个测试用例都有效。

if(s1 != null && s2 != null)
    if(s1.getClass().isArray() && s2.getClass().isArray())
        compareDatab = s1.getClass().equals(s2.getClass()) && (Arrays.toString(s1).equals(Arrays.toString(s2)));
    else
        compareDatab = compareData(s1, s2);
else
    compareDatab = compareData(s1, s2);

上述代码段的用法(以下初始化应在上述代码段之前完成,smh :P):

//s1 and s2 can be anything including Arrays and non-Array...
int[] s1 = {1,2,3};
int[] s2 = {1,2,3};
//compareDatab gives true

int[] s1 = {1,2,4};
int[] s2 = {1,2,3};
//compareDatab gives false

float[] s1 = {1,2,3};
int[] s2 = {1,2,3};
//compareDatab gives false

其中 compareData() 与此答案中先前所述的功能相同。

希望这对您有用。 :)

如果我们在 JS 中比较两个变量,我们可以同时使用“==”和“===”。 “==”比较值,“===”也比较类型。

var x = 10;
var y = '10';
console.log(x == y)  // true
console.log(x === y) // false

并且在 Java 中这会给你编译错误,因为类型不一样。

我看不出为此编写自己的比较器有任何好处。特别是如果已经有一个本机实现的话。

java.util.Objects是你的朋友。

里面有很多小帮手,喜欢

Objects.compare(object1, object2, comparator);
Objects.equals(object1, object2);
Objects.deepEquals(object1, object2);
Objects.hash(object1, object2, object3, ...);

我在 equals 中使用 Objects.equals 覆盖,在 hashCode 方法中使用 Objects.hash。它还会为您进行 null 检查,最终代码看起来非常干净且可读。

例如:

...

@Override
public boolean equals(Object o) {
    if (this == o) {
        return true;
    }
    if (!(o instanceof Customer)) {
        return false;
    }
    Customer that = (Customer) o;
    return Objects.equals(firstName, that.firstName)
            && Objects.equals(lastName, that.lastName)
            && Objects.equals(street, that.street)
            && Objects.equals(houseNumber, that.houseNumber)
            && Objects.equals(postalCode, that.postalCode)
            && Objects.equals(city, that.city)
            && Objects.equals(emailAddress, that.emailAddress);
}

@Override
public int hashCode() {
    return Objects.hash(firstName,
            lastName,
            street,
            houseNumber,
            postalCode,
            city,
            emailAddress);
}

...