关于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 了两个对象吗

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;

}
}

运行结果:
图片说明

1、this指当前字符串,比如"a".equals("b"),this指"a"
2、student.name指s2,Student student = (Student)anObject; 其中anObject是equals参数,你写的是s1.equals(s2)。所以是s2

指的是当前类的类的对象

显然是另一个对象的。s1调用equals,this才是s1

一楼正解!this就是当前对象.