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条)

报告相同问题?

悬赏问题

  • ¥50 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?