API
API
1 概述
API -- application programming interfaces 应用程序接口
是对JDK提供的一套类的解释说明的文档,实际上是官方提供的类的文档注释生成的文档
jdk17离线网页版下载https://www.oracle.com/java/technologies/javase-jdk17-doc-downloads.html
jdk17 api中文在线版 https://doc.qzxdp.cn/jdk/17/zh/api/index.html
2 Object常用方法
Object是java继承关系树的根,所有对象,包括数组都是它的子类
public class TestDemo3 implements Cloneable{
int i;
public static void main(String[] args) throws Throwable {
Object obj = new Object();
// clone() --克隆对象 可以克隆一个新的对象,新的对象的属性值和旧对象一样
// CloneNotSupportedException
// 任何一个对象想要被克隆,那么这个对象对应的类需要实现Cloneable接口
TestDemo3 testDemo3 = new TestDemo3();
System.out.println(testDemo3);
testDemo3.i = 10;
// alt + 回车 + 回车
//
TestDemo3 o = (TestDemo3) testDemo3.clone();
System.out.println(o);
// System.out.println(o.i);
Person person1 = new Person();
Person person2 = new Person();
// 默认是比较两个对象的地址是否相同
// == 针对对象,是比较地址是否相同
System.out.println(person1.equals(person2));
// 通知回收对象
// testDemo3.finalize();
// System.gc();
// 返回对象的真正的类型
Object obj1 = new Person();
System.out.println(obj1.getClass());
// 返回对象的哈希码值
// 哈希码是根据哈希散列算法计算出来的一个值
// 根据哈希散列算法,哈希码会随机散落在将近43亿个值上
// 人为的认为同一个类的不同对象的哈希码值是唯一的
// 往往会根据哈希码来决定对象的内存存储
System.out.println(obj1.hashCode());
System.out.println(obj1);
// 把对象转换成字符串
String string = obj1.toString();
System.out.println(string);
Person person = new Person();
person.setName("郭靖");
person.setAge(40);
System.out.println(person);
}
重写equals方法
// 如果两个对象的属性值都相同,返回true
@Override
public boolean equals(Object obj) {
// 判断地址是否相同
if (this == obj){
return true;
}
// 判断参数是否是null
if (obj == null){
return false;
}
// 判断类型是否一致
if (this.getClass() != obj.getClass()){
return false;
}
Person p = (Person) obj;
// 比较属性值是否相同
if (this.id != p.id){
return false;
}
// 比较年龄是否相同
if (this.age != p.age){
return false;
}
// 比较姓名是否相同
if (this.name == null){
if (p.name != null){
return false;
}
}else if (!this.name.equals(p.name)){
return false;
}
// 比较性别是否相同
if (this.gender == null){
if (p.gender != null){
return false;
}
}else if (!this.gender.equals(p.gender)){
return false;
}
return true;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Person p = (Person) obj;
return this.id == p.id && this.age == p.age && (this.name == p.name || (this.name != null && this.name.equals(p.name))) && (this.gender == p.gender || (this.gender != null && this.gender.equals(p.gender)));
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Person p = (Person) obj;
return this.id == p.id && this.age == p.age && Objects.equals(this.name,p.name) && Objects.equals(this.gender,p.gender);
}

浙公网安备 33010602011771号