qq_26893785 2015-04-23 15:16 采纳率: 100%
浏览 1741
已采纳

关于Java中 源代码 String 类中的 equals

public boolean equals(Object anObject) {
    if (this == anObject) {
        return true;
    }
    if (anObject instanceof String) {
        String anotherString = (String) anObject;
        int n = value.length;
        if (n == anotherString.value.length) {
            char v1[] = value;
            char v2[] = anotherString.value;
            int i = 0;
            while (n-- != 0) {
                if (v1[i] != v2[i])
                        return false;
                i++;
            }
            return true;
        }
    }
    return false;
}

第二行的 this指的是什么?

这还有一个扩展的程序

public class EqualsTest
{
public static void main(String[] args)
{
Student s1 = new Student("zhangsan");
Student s2 = new Student("zhangsan");

    System.out.println(s1 == s2);
    System.out.println(s1.equals(s2));      
}

}

class Student
{
String name;

public Student(String name)
{
    this.name = name;
}

public boolean equals(Object anObject)
{
    if(this == anObject)
    {
        return true;
    }

    if(anObject instanceof Student)
    {
        Student student = (Student)anObject;

        if(student.name.equals(this.name))
        {
            return true;
        }
    }

    return false;
}

}

这个程序中student.name 指的是s1还是s2

new对象的时候不是new 了两个对象吗

  • 写回答

5条回答

  • whz1998gt 2015-04-23 16:04
    关注

    package com.answer;

    public class Student {
    public static void main(String[] args) {
    Student s1 = new Student("zhangsan");
    Student s2 = new Student("zhangsan");
    System.out.println(s1 == s2); // == 比较的是内存结果

      System.out.println("调用equal方法前");
      System.out.println(s1.equals(s2));   // 根据重写的equal方法进行判断
      System.out.println("调用equal方法后");
      System.out.println(s1);
      System.out.println(s2);    // 观察输出 内存地址不同
    

    }
    String name;
    public Student(String name)
    {
    this.name = name;
    }

    public boolean equals(Object anObject)
    {
    System.out.println("调用equal方法");
    // this 在这里是s1 与 s2 内存地址不同 不成立
    if(this == anObject)
    {
    return true;
    }
    // s2是Student类的对象 if条件成立
    if(anObject instanceof Student)
    {
    // 类型转换
    Student student = (Student)anObject;

          // 都等于zhangsan 返回true
          if(student.name.equals(this.name))
          {
              return true;
          }
      }
    
      return false;
    

    }
    }

    运行结果:
    图片说明

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘