• 当我们直接打印定义的对象的时候,隐含的是打印toString()的返回值。


     

    以下介绍的三种方法属于Object:

    (1)  finalize方法:当一个对象被垃圾回收的时候调用的方法。

    (2)  toString():是利用字符串来表示对象。

    当我们直接打印定义的对象的时候,隐含的是打印toString()的返回值。

    可以通过子类作为一个toString()来覆盖父类的toString()

    以取得我们想得到的表现形式,即当我们想利用一个自定义的方式描述对象的时候,我们应该覆盖toString()

    (3)equal

    首先试比较下例:

    String A=new String(“hello”);

    String A=new String(“hello”);

    A==B(此时程序返回为FALSE)

    因为此时AB中存的是地址,因为创建了新的对象,所以存放的是不同的地址。

     

    附加知识:

    字符串类为JAVA中的特殊类,String中为final类,一个字符串的值不可重复。因此在JAVA VM(虚拟机)中有一个字符串池,专门用来存储字符串。如果遇到String a=”hello”时(注意没有NEW,不是创建新串),系统在字符串池中寻找是否有”hello”,此时字符串池中没有”hello”,那么系统将此字符串存到字符串池中,然后将”hello”在字符串池中的地址返回a。如果系统再遇到String b=”hello”,此时系统可以在字符串池中找到 “hello”。则会把地址返回b,此时ab为相同。

     

     

    String a=”hello”;

    System.out.println(a==”hello”);

    系统的返回值为true

     

    故如果要比较两个字符串是否相同(而不是他们的地址是否相同)。可以对a调用equal:

    System.out.println(a.equal(b));

    equal用来比较两个对象中字符串的顺序。

    a.equal(b)ab的值的比较。

     

     

    注意下面程序:

    student a=new student(“LUCY”,20);

    student b=new student(“LUCY”,20);

    System.out.println(a==b);

    System.out.println(a.equal(b));

    此时返回的结果均为false

     

    以下为定义equal(加上这个定义,返回turefalse

    public boolean equals(Object o){

      student s=(student)o;

      if (s.name.equals(this.name)&&s.age==this.age)

    else return false;

    }如果equals()返回的值为

     

    以下为实现标准equals的流程:

    public boolean equals(Object o){

      if (this==o) return trun;  //此时两者相同
      if (o==null) return false;

      if (! o instanceof strudent) return false;  //不同类

      studeng s=(student)o; //强制转换

      if (s.name.equals(this.name)&&s.age==this.age) return true;

    else return false;

    }

     

    以上过程为实现equals的标准过程。

     

     练习:建立一个employee类,有String name,int id,double salary.运用getset方法,使用toString,使用equals

  • 相关阅读:
    雅礼集训2017day5乱写
    任意值域最长公共子序列问题
    雅礼集训2017day4乱写
    雅礼集训2017day2乱写
    SP839
    雅礼集训2017day1乱写
    CF671E
    仅维护当前区间影响类问题的线段树
    「雅礼集训 2017 Day4」编码
    Codeforces Round #503 Div. 2
  • 原文地址:https://www.cnblogs.com/borter/p/10744019.html
Copyright © 2020-2023  润新知