方法 | 描述 |
---|---|
Object clone() | 创建并返回次对象的一个副本 |
boolean equals(Object obj) | 重写后比较两个对象的内容是否相同,否则“==”比较地址 |
String toString() | 返回该对象的字符串 |
Class<?> getClass() | 返回此Object的运行时类 |
int hashCode() | 返回该对象的哈希值 |
void notify() | 唤醒此对象监听器上等待的单个线程 |
void notifyAll() | 唤醒此对象监听器上等待的所有线程 |
void wait() | 在其他线程调用此对象的 notify() 方法或 notifyAll() 方法前,导致当前线程等待。 |
void wait(long timeout) | 在其他线程调用此对象的 notify() 方法或 notifyAll() 方法,或者超过指定的时间量前,导致当前线程等待。 |
void wait(long timeout, int nanos) | 在其他线程调用此对象的 notify() 方法或 notifyAll() 方法,或者其他某个线程中断当前线程,或者已超过某个实际时间量前,导致当前线程等待。 |
void finalize(),从jdk9已弃用 | 当垃圾回收器确定不存在对该对象的更多引用时,由对象的垃圾回收器调用此方法。 |
面试题:==和equals的区别
- == 既可以比较基本类型也可以比较引用类型。对于基本类型就是比较值,对于引用类型就是比较内存地址
- equals的话,它是属于java.lang.Object类里面的方法,如果该方法没有被重写过默认也是==;我们可以看到String、File、Date等类的equals方法是被重写过的,而且String类在日常开发中用的比较多,久而久之,形成了equals是比较值的错误观点。
- 具体要看自定义类里有没有重写Object的equals方法来判断。
- 通常情况下,重写equals方法,会比较类中的相应属性是否都相等。
- equals()只能用于引用数据类型!
toString()
方法签名:public String toString()
① 默认情况下,toString()返回的是“对象的运行时类型 对象的hashCode值(16进制)"
② 在进行String与其它类型数据的连接操作时,自动调用toString()方法
Date now=new Date();
System.out.println(“now=”+now);
//相当于
System.out.println(“now=”+now.toString());
③ 如果我们直接System.out.println(对象),默认会自动调用这个对象的toString()
因为Java的引用数据类型的变量中存储的实际上时对象的内存地址,但是Java对程序员隐藏内存地址信息,所以不能直接将内存地址显示出来,所以当你打印对象时,JVM帮你调用了对象的toString()。
④ 可以根据需要在用户自定义类型中重写toString()方法
如String、File、Date 类重写了toString()方法,返回字符串的值。
s1="hello";
System.out.println(s1);//相当于System.out.println(s1.toString());
例如自定义的Person类:
public class Person { private String name;private int age;// 重写toString()@Overridepublic String toString() {return "Person{" + "name='" + name + '\'' + ", age=" + age + '}';}
}
equals()重写举例
推荐使用IDEA自动实现。
class User{private String host;private String username;private String password;public User(String host, String username, String password) {super();this.host = host;this.username = username;this.password = password;}public User() {super();}public String getHost() {return host;}public void setHost(String host) {this.host = host;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}@Overridepublic String toString() {return "User [host=" + host + ", username=" + username + ", password=" + password + "]";}// 重写equals()@Overridepublic boolean equals(Object obj) {if (this == obj)return true;if (obj == null)return false;if (getClass() != obj.getClass())return false;User other = (User) obj;if (host == null) {if (other.host != null)return false;} else if (!host.equals(other.host))return false;if (password == null) {if (other.password != null)return false;} else if (!password.equals(other.password))return false;if (username == null) {if (other.username != null)return false;} else if (!username.equals(other.username))return false;return true;}}
总结:
在我们自定义类中,如果需要比较对象的内容;或返回对象的内容,而非地址值。就需要显示的重写equals()或toString()。