- package com.itheima.test2;
- public class 对象中Integer成员变量的比较 {
- public static void main(String[] args) {
- Foo foo1 = new Foo(1000000);
- Foo foo2 = new Foo(1000000);
- System.out.println(foo1.equals(foo2));//false [参考equals方法]
- Foo foo3 = new Foo(1);
- Foo foo4 = new Foo(1);
- System.out.println(foo3.equals(foo4));//true
- }
- }
- class Foo {
- public Foo(Integer integer) {
- super();
- this.integer = integer;
- }
- private Integer integer;// 如果是int 则可以直接用“==”比较
- public Integer getInteger() {
- return integer;
- }
- public void setInteger(Integer integer) {
- this.integer = integer;
- }
- @Override
- public boolean equals(Object obj) {
- System.out.println("调用equals方法");
- if (obj instanceof Foo) {
- return this.integer == ((Foo) obj).integer;
- /*
- Integer类中equals方法的实现,可以看到最终Integer转换成了int再使用“==”比较
- public boolean equals(Object obj) {
- if (obj instanceof Integer) {
- return value == ((Integer)obj).intValue();
- }
- return false;
- }
- */
- // return this.integer.equals(((Foo) obj).integer);
- }
- return false;
- }
- }
复制代码 细节:对象中有Integer类型的成员变量做值的大小比较时,尽量采用Integer的equals方式比较保险!
|