Discuss / Java / 请问Person的String类型字段能不能直接用==比较?

请问Person的String类型字段能不能直接用==比较?

Topic source
import java.util.*;

/**
 * Learn Java from https://www.liaoxuefeng.com/
 * 
 * @author liaoxuefeng
 */
public class Main {
	public static void main(String[] args) {
		List<Person> list = List.of(new Person("Xiao", "Ming", 18), new Person("Xiao", "Hong", 25),
				new Person("Bob", "Smith", 20));
		boolean exist = list.contains(new Person("Bob", "Smith", 20));
		System.out.println(exist ? "测试成功!" : "测试失败!");
	}
}

class Person {
	String firstName;
	String lastName;
	int age;

	public Person(String firstName, String lastName, int age) {
		this.firstName = firstName;
		this.lastName = lastName;
		this.age = age;
	}
	
	/**
	 * TODO: 覆写equals方法
	 */
	public boolean equals(Object o) {
		if(o instanceof Person) {
			Person other = (Person) o;
			return this.firstName == other.firstName && 
					this.lastName == other.lastName &&
					this.age == other.age;
		}
		return false;
	}
}

打印结果:测试成功!

如以上代码显示,直接用==比较两个String字段,firstname 和lastname。没有用equals,也没有用Object.equals静态方法。

这次运行成功了,但是不知道这样写在其他场景下会有什么不良后果吗?

廖雪峰

#2 Created at ... [Delete] [Delete and Lock User]

你自己试试就知道了:

"abc"=="abc"

"abc"=="abcd".substring(0,3)

对于引用字段比较,我们使用 equals(),对于基本类型字段的比较,我们使用 == 判断。
很明显 String  是引用类型的

去看看 前面的章节就知道了

Joker.fu_95

#5 Created at ... [Delete] [Delete and Lock User]

字面量是没影响的,但是new的话就不行,所以字符串比较的是内容,还是用equals


  • 1

Reply