Java中"=="与equals()方法的区别

xiaoxiao2025-12-12  3

1. 操作符”==”用来比较两个操作元是否相等,这两个操作元既可以是基本类型,也可以是引用类型。

例如:int a1=1,a2=3;

boolean b1=a1==a2; //”==”的操作元为基本类型,b1值为false

String str1=”Hello”,str2=”World”;

boolean b2=str1==str2; //”==”的操作元为引用类型,b2的值为false

2. 当操作符“==”两边都是引用类型变量时,这两个引用变量必须都引用同一个对象,结果才为true,否则为false.

如:

3. 当“==”用于比较引用类型变量时,“==”两边的变量被显式声明的类型必须是同种类型或有继承关系。

class Creature { Creature() { } } class Animal extends Creature { Animal() { } } class Dog extends Animal { Dog() { } } class Cat extends Animal { Cat() { } } public class IntegerTest { public static void main(String[] args) { Dog dog = new Dog(); Creature creature = dog; Animal animal = new Cat(); System.out.println(dog == animal); System.out.println(dog == creature); } } 结果为:false true

 

 

 

5.只要两个对象都是同一个类的对象,并且它们变量属性相同,则结果为true,否则为false.

class TestInteger{ private String name; TestInteger(String name){ this.name=name; } boolean equal(Object o){ if(this==o){ return true; } if(!(o instanceof TestInteger)){ return false; } final TestInteger other=(TestInteger)o; if(this.name.equals(other.name)){ return true; } else{ return false; } } } public class TestIntegerOne { public static void main(String[] args) { TestInteger person1=new TestInteger("Tom"); TestInteger person2=new TestInteger("Tom"); System.out.println(person1==person2); System.out.println(person1.equal(person2)); } } 结果为:false true

 

 

转载请注明原文地址: https://www.6miu.com/read-5040751.html

最新回复(0)