== vs .equals - 为什么不同的行为? [英] == vs .equals - why different behaviour?

查看:38
本文介绍了== vs .equals - 为什么不同的行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
如何比较 Java 中的字符串?

对于这个相当简单的问题,我很抱歉.我有一个非常简单的java程序:

I'm sorry for this rather simple question. I have this very simple java program:

public class ArgIt {
    public static void main(String[] args){
            if(args[0].equals("x")) System.out.print("x");
            if(args[0] == "x") System.out.println("x2 ");
    }
}

如果我调用程序 >java ArgIt x它只打印一个 x.为什么程序在任何其他情况下都不会确认字符串上的 == ?

If I call the program >java ArgIt x it only prints a single x. Why will the program not acknowledge the == on the string when in any other circumstances it does?

推荐答案

在 Java 中,您必须使用 equals() 来比较 String 之间的相等性.== 测试身份,这是一个不同的概念.

In Java, you must use equals() for comparing equality between Strings. == tests for identity, a different concept.

两个对象可以相等但不完全相同;另一方面,如果两个对象相同,则暗示它们相等.

Two objects can be equal but not identical; on the other hand if two objects are identical it's implied that they're equal.

如果两个对象在物理上指向内存中的相同地址,则它们是相同的,而如果它们具有相同的值,则两个对象是相等的,正如程序员在 equals() 方法中定义的那样.一般来说,您更感兴趣的是找出两个对象是否相等.

Two objects are identical if they physically point to the same address in memory, whereas two objects are equal if they have the same value, as defined by the programmer in the equals() method. In general, you're more interested in finding out if two objects are equal.

这篇关于== vs .equals - 为什么不同的行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆