简体   繁体   English

“===”相当于Java

[英]“===” equivalent in Java

While comparing two values in Java, how do you test if both, the type and the value, are equivalent? 在比较Java中的两个值时,如何测试类型和值是否相等?

I know in JavaScript === can be used to accomplish this, so I tried that in Java, but it didn't work. 我知道在JavaScript中===可以用来完成这个,所以我在Java中尝试过,但它没有用。

I know this is a simple question, but I tried looking it up and I couldn't find out what it was. 我知道这是一个简单的问题,但我尝试查找它,但我无法找出它是什么。

TL;DR TL; DR

In Java there is not such a comparison operator: === , but == or equals 在Java中没有这样的比较运算符: === ,但==equals

A longer explanation 更长的解释

In weakly typed languages such as JavaScript you can use the strict comparison operator ( === ) because the language allows comparison between variables which have different types . 在诸如JavaScript之类的弱类型语言中,您可以使用严格比较运算符( === ),因为该语言允许在具有不同类型的变量之间进行比较。

For example, in JavaScript, you won't get a compile error if you do this: 例如,在JavaScript中,如果执行此操作,则不会出现编译错误

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

And it is useful, when you want to compare variables which may hold values that are "equals" but may be of different types. 当你想要比较可能包含“等于”但可能是不同类型的值的变量时,它很有用。

For example 例如

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

In strongly typed languages such as Java, you don't need to use a strict comparison operator because the language already "handles" the type comparison. 在Java等强类型语言中,您不需要使用严格的比较运算符,因为该语言已经“处理”了类型比较。

For example: 例如:

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

So, basically, in Java, there is no need for checking for strictness using === (a syntax error is reported). 因此,基本上,在Java中,不需要使用===检查严格性(报告语法错误 )。

In the first place, the compiler will complain when you compare values of different types using the == operator and conversion cannot be performed. 首先,当您使用==运算符比较不同类型的值时,编译器会抱怨,并且无法执行转换

In the previous example of Java code, if you want to make a comparison between x and y you could use equals : 在前面的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

As a side note, notice the equals method cannot be called on primitive types. 作为旁注,注意不能在原始类型上调用equals方法。

Some useful readings are: 一些有用的读物​​是:

I made a function which r eplicates the functionality of === of Javascript in Java 我创建了一个函数,它在Java中提出了Javascript ===的功能

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));
    }
}

I was able to pass values of any data type (except array) to this function as well as get true only if the data type and the values match else it returns false. 我能够将任何数据类型(数组除外)的值传递给此函数,并且只有在数据类型和值匹配时才会返回true,否则返回false。 Derived data types like List and HashMap also work . List和HashMap等派生数据类型也有效

Call to this function looks like this: 调用此函数如下所示:

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

and so on... 等等...

Update: I managed to compare arrays also , following is the code snippet, but, I haven't tested this code intensively but worked for every test case I performed. 更新:我还设法比较了数组 ,以下是代码片段,但是,我没有密集地测试这个代码,但是对我执行的每个测试用例都有效。

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);

Usage of the above snippet (Following initializations should be done prior to above code snippet,smh :P): 使用上面的代码片段(以下初始化应该在上面的代码片段之前完成,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

Where compareData() is the same function as stated prior in this answer. 其中compareData()与本答案中前面所述的功能相同

Hope this proves useful to you. 希望这证明对你有用。 :) :)

Java中没有truthy和falsy的概念,因此没有严格的比较运算符。

=== is useful in weak typed languages, such as Javascript, because it verifies that the objects being compared are of the same type and avoids implicit conversions. ===在弱类型语言中很有用,例如Javascript,因为它验证被比较的对象是相同的类型并避免隐式转换。

=== has absolutely no use in a strongly typed language such as Java because you can't compare variables of different types without writing a specific method for doing this. ===在Java等强类型语言中绝对没用,因为如果不编写特定的方法,就无法比较不同类型的变量。

In Java you can compare primitive types like int, double, char, long, float by using '=='. 在Java中,您可以使用'=='比较基本类型,如int,double,char,long,float。 In this case values are compared. 在这种情况下,比较值。 For the comparison of objects this is not sufficient because '==' evaluates only to 'true' if the identities of the compared objects are the same - 'identity' is the memory address where the object is stored. 对于对象的比较,这是不够的,因为如果比较对象的标识相同,'=='仅评估为'true' - 'identity'是存储对象的内存地址。 This is due to the fact that all classes inherit implicitly all methods provided by the 'Object' class and where the 'equals()'-method contains only a basic implementation. 这是因为所有类都隐式地继承了'Object'类提供的所有方法,'equals()' - 方法只包含一个基本实现。 Because of this any class whose objects are involved in comparisons, used in data structures or outside it's own package should contain a solid implementation of equals() and hashCode()-method to provide correct functionality. 因为这个对象涉及比较的任何类,在数据结构中使用,或者在它自己的包之外应该包含equals()和hashCode()的可靠实现 - 提供正确功能的方法。

Regard following implementation: 关注以下实施:

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() { ... }

}

Also check out official Java API for further information https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html . 另请参阅官方Java API以获取更多信息https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html

If two variables aren't of the same type you can't compare them, so in this case == will suffice. 如果两个变量的类型不同,则无法比较它们,因此在这种情况下==就足够了。 If they're not convertable it will throw a compiler error. 如果它们不可转换,则会抛出编译器错误。

There is no === operator for comparison. 没有===运算符用于比较。 When you want to compare two references, you should check - 1. If they are pointing to same object. 如果要比较两个引用,则应检查 - 1.如果它们指向同一个对象。

if(firstreference==secondreference) 
  1. If condition 1 above did not meet then you should check for their type by instanceof operator : 如果上面的条件1不符合,那么你应该通过instanceof运算符检查它们的类型:
if (secondreference instanctof classoffirstreference)
  1. If condition 2 above meets then you should check for property comparisons by equals operator like 如果上面的条件2满足,那么你应该通过等于运算符来检查属性比较
firstreference.property1.equals(secondreference.property1)
//do this for all properties.

I can't see any benefit of writing my own comparator for this. 我没有看到为此编写自己的比较器的任何好处。 especially if there is already a native implementation for this. 特别是如果已经存在本机实现。

java.util.Objects is your friend. java.util.Objects是你的朋友。

It contains a lot of little helper, like 它包含很多小帮手,就像

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

I use Objects.equals in overwriting in equals and Objects.hash in hashCode methods. 我使用Objects.equals覆盖equals,并在hashCode方法中使用Objects.hash。 It also does null checks for you and in the end the code looks very clean and readable. 它还为您执行空检查,最后代码看起来非常干净和可读。

In example: 例如:

...

@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);
}

...

If we compare two variables in JS we can use "==" and "===" both. 如果我们比较JS中的两个变量,我们可以使用“==”和“===”。 "==" compare values and "===" compare Types also. “==”比较值和“===”比较类型。

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

and in Java this give you compile error because type is not same. 在Java中,这会给你编译错误,因为类型不同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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