Java中的Object类的常用方法和代码示例
时间: 2024-05-13 12:19:04 浏览: 106
Java中的Object类是所有类的父类,提供了一些常用的方法,下面是常用的方法和代码示例:
1. equals(Object obj)方法:判断当前对象是否和另一个对象相等,即比较两个对象的内容是否相同。
```java
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Person person = (Person) obj;
return age == person.age && Objects.equals(name, person.name);
}
}
// 测试代码
Person p1 = new Person("Tom", 18);
Person p2 = new Person("Tom", 18);
System.out.println(p1.equals(p2)); // true
```
2. hashCode()方法:返回当前对象的哈希码,一般用于哈希表等数据结构中。
```java
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
}
// 测试代码
Person p1 = new Person("Tom", 18);
System.out.println(p1.hashCode()); // 2316056
```
3. toString()方法:返回当前对象的字符串表示。
```java
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
// 测试代码
Person p1 = new Person("Tom", 18);
System.out.println(p1.toString()); // Person{name='Tom', age=18}
```
4. getClass()方法:返回当前对象的类类型。
```java
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
// 测试代码
Person p1 = new Person("Tom", 18);
System.out.println(p1.getClass()); // class Person
```
5. clone()方法:复制当前对象,返回一个新的对象。
```java
public class Person implements Cloneable {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
// 测试代码
Person p1 = new Person("Tom", 18);
Person p2 = (Person) p1.clone();
System.out.println(p1 == p2); // false
```
阅读全文