测试类
public class Test
{
private int year;
private int month;
private int day;
public Test(int year, int month, int day)
{
this.year = year;
this.month = month;
this.day = day;
}
}
toString
① 作用: 让子类重写,输出对象的字符串形式信息
② 源码:
③ 特点: 使用 引用.toString()
或 直接调用 引用
都可以,会自动调用 toString
// 重写 toString 方法
@Override
public String toString()
{
return year + "年 " + month + "月 " + day + "日";
}
public static void main(String[] args)
{
Test te = new Test(2021, 2, 14);
System.out.println(te);
}
运行结果:
重写前:MyTest.Test@1b6d3586
重写后:2021年 2月 14日
④ 自动调用 toString 的原因:
println 调用了 valueOf ,valueOf 又调用了 toString
equals
① 作用: 比较两个对象是否相等。一般需要子类重写,制定两个对象相等的规则。
② 源码:
③ 特点: 默认只是比较两个对象的内存地址是否相等
// 重写 equals 方法
@Override
public boolean equals(Object o)
{
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Test test = (Test) o;
return year == test.year && month == test.month && day == test.day;
}
public static void main(String[] args)
{
Test te = new Test(2021, 2, 14);
System.out.println(te);
}
运行结果:
重写前:false
重写后:true
④ 默认重写: String,Integer 等包装类型已经将 equals 重写好了,可以直接使用 equals 比较内容
⑤ 注意事项: 基本类型用 “==” 比较,引用数据类型用 equals 比较。但 String 类型比较特殊,如下:
String s1= new String("ahha");
String s2 = new String("ahha");
String s3 = "aaa";
String s4 = "aaa";
System.out.println(s1 == s2);
System.out.println(s1 == s3);
System.out.println(s3 == s4);
运行结果:
false
false
true
前两个是 false 没问题,但第三个却是 true
这是由字符串存储机制导致的
在使用双引号定义字符串时,会先在常量池寻找指定字符串,如果有该字符串则直接使用,没有的话就新创建一个。
这就导致 s3 和 s4 其实是指向常量池的同一块内存,在创建 s4 时发现要的字符串已经存在,就直接用了。
所以他们的比较结果是相等
finalize
① 作用: 在对象即将被销毁时,垃圾回收器会自动调用的方法。在里边可以写一些善后的代码 (遗言)。也是需要被重写的。
② 源码: 什么都没有
③ 注意:
- 这个方法在高版本里已经过时了,不过现在最常用的是 jdk1.8 ,该方法还没过时,还是要学一学的 ~
- 该方法调用的时机不可预测,全看垃圾回收器(GC) 心情
- 需要垃圾足够多时(测试了一下在1000000个对象变成垃圾时触发),垃圾回收器才行动起来
- 使用 System.gc(); 可以建议GC进行垃圾回收,但它可能不听
(小东西还挺傲娇[doge])
// 重写 finalize 方法
@Override
protected void finalize() throws Throwable {
super.finalize();
System.out.println(hashCode() + "要死啦~没有遗言,谢谢!");
}
public static void main(String[] args)
{
for(int i=0; i<10; i++) // 创建10个垃圾
{
Test te = new Test(2021, 2, 14);
te = null; // 让对象变成垃圾
System.gc(); // 建议垃圾回收器启动
}
}
运行结果
2028473269要死啦~没有遗言,谢谢!
1982851800要死啦~没有遗言,谢谢!
1913675973要死啦~没有遗言,谢谢!
使用建议时,垃圾回收器启动的概率会提升(记得要放在循环里,每次循环都建议一次,放在循环外概率还是很低)。由于存在概率性,每次回收的对象数也不一样(像这一次是回收了3个)
O_Q (寒冰小澈)