2,Object类,以及重写equals,hashCode,toString方法

xiaoxiao2021-02-28  32

Object类的方法

finalize();GC相关

clone();克隆,复制

equals();什么样的相等,equals表示值相等

toString();在对对象进行展示时需要设置展示的String

hsahCode();身份证号码

wait();线程相关

notify();线程相关

getClass();获取类

重写equals方法后一定要重写hashCoode方法,因为这样才能够保证equals的对象的哈希码也相等

class Test1 { int a; int b; public Test1(int a, int b) { this.a = a; this.b = b; } //重写toString public String toString() { return ""+a+","+b; } //重写equals public boolean equals(Object o) { if(o==null) { return false; }else if(this==o) { return true; }else if(o instanceof Test1) { Test1 other=(Test1)o; return this.a==other.a&&this.b==other.b; } return false; } //重写hashCode //为了保证equals的对象拥有相同的hashCode,所以必须重写hashCode public int hashCode() { final int prime = 31; int result = 1; result = prime * result + a; result = prime * result + b; return result; } }

克隆:浅层,深层

public class Prototype implements Cloneable, Serializable { private static final long serialVersionUID = 1L; private String string; private SerializableObject obj; /* 浅复制 */ public Object clone() throws CloneNotSupportedException { Prototype proto = (Prototype) super.clone(); return proto; } /* 深复制 */ public Object deepClone() throws IOException, ClassNotFoundException { /* 写入当前对象的二进制流 */ ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(this); /* 读出二进制流产生的新对象 */ ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); ObjectInputStream ois = new ObjectInputStream(bis); return ois.readObject(); } public String getString() { return string; } public void setString(String string) { this.string = string; } public SerializableObject getObj() { return obj; } public void setObj(SerializableObject obj) { this.obj = obj; } } class SerializableObject implements Serializable { private static final long serialVersionUID = 1L; }
转载请注明原文地址: https://www.6miu.com/read-2627774.html

最新回复(0)