本文主要是介绍java—toString,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
import java.util.Objects;
public class Person {
private String name;
private int age;
public Person() {
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
return age == person.age &&
Objects.equals(name, person.name);
}
}
另起一个类:
/*
ToString:
直接打印对象相当于调用对象中的ToSting方法
直接打印对象,如果出现的不是地址值,说明重写了ToString方法
equals:
equals比较的是地址值,需要覆盖重新父类Object的方法
注意,当null调用equals方法会报空指针异常
*/
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
public class DemoPerson {
public static void main(String[] args) {
Person r1 = new Person("vergil",21);
System.out.println(r1);
Random r2 = new Random();
System.out.println(r2);
Scanner r3 = new Scanner(System.in);
System.out.println(r3);
ArrayList r4 = new ArrayList();
r4.add(1);
r4.add(2);
System.out.println(r4);
Person r5 = new Person("Alice",23);
System.out.println(r1.equals(r5));
}
}
这篇关于java—toString的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!