1、finalize
JVM:
1 跨平台
2 面向对象
3 多线程
4 自动垃圾回收
finalize
1每个java对象都有
2 不需要程序员调用,有系统自动调用
3 垃圾:没有更多引用指向该对象的时候,该对象被视为垃圾数据。
4 对象被回收之前,会自动帮我们调用该对象的finalize方法
finalize方法,并没有垃圾回收的功能,知识垃圾被回收之前,自动执行而已,所以我们手动调用该方法是没有任何作用的。
public class finallize_01_a {
public static void main(String[] args) {
finallize_01_a f =new finallize_01_a();
f=null;
// System.gc();
for(long i=0;i<99000000;i++){
new finallize_01_a();
}
}
protected void finalize() throws Throwable{
System.out.println(this+"被回收");
}
}
2、hashcode
hashcode(): 方法设计目的,是为了给每个对象生成一个唯一的标识符。
同一个对象生成多次值,值一定相同
不同对象生成的值,也有可能相同,叫做hashcode冲突
覆写hashcode的时候,还需要考虑:
覆写hashcode,是因为equals和hashcode不同,是没有办法在散列表中表示方法唯一性的。
hash算法是一种安全的加密算法,把不定长的值,改为定长的值
直接寻址法
数字分析法
除留余数法
随机数法
折叠法
public static void main(String[] args) {
hashcode_01_a hashcode_1= new hashcode_01_a();
hashcode_01_a hashcode_2= new hashcode_01_a();
// hashcode 返回该对象的hash值
int hash = hashcode_1.hashcode();
// 十进制
System.out.println(hash);
// toHexString: 转换为十六进制展示
System.out.println(Integer.toHexString(hash ));
System.out.println(hashcode_1);
System.out.println(hashcode_2);
}
public int hashcode(){
return 2;
}
}
class person15{
int age;
String name;
}
3、toString
设计目的:
返回该对象的字符串表示形式,可以通过这个方法,把每个对象输出出来,让外界知道
输出一个引用类型的时候,底层会自动调用该对象的toString()方法
Object中的toString
public String toString(){
return getClass().getName()+ "@"Integer.toHexString(hashcode());
}
public static void main(String[] args) {
person14 person1 = new person14("张三",13);
person14 person2 = new person14("李四",12);
System.out.println(person1);
System.out.println(person2);
}
}
class person14{
String name;
int age;
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public int getAge(){
return age;
}
public String toString(){
return this.name+":"+this.age;
}
public void println(){
System.out.println(this.name + ":" +this.age);
}
public person14(String name,int age){
super();
this.name =name;
this.age = age;
}
}