处理对象
1.打印对象和toString方法
都是Object中定义的方法,而所有的类都是继承Object,所以所有对象都有这个方法。
比如System.out.print(xx)中,括号里“xx“不是String类型的话,就自动调用xx的toString方法。
class Person{
private String name;
public Person(String name){
this.name=name;
}
}
public class PrintObject{
public static void main(String[] args)
{
Person p=new Person("abc");
System.out.println(p);
System.out.println(p.toString());
}
}
输出:Person@15db9742
Person@15db9742
因为System.out的println()方法只能在控制台输出字符串,而Person实例是在内存中的对象.
Object类提供的toString方法总是返回该对象实现类的“类名+@+hashCode”值,这个值不能实现真正的自我描述功能,需要重写实现。
class Apple
{
private String color;
private Double weight;
public Apple{}
public Apple(String color,Double weight)
{
this.color=color;
this.weight=weight;
}
public String toString(){
return "the color is:"+color+",the weight is:"+weight;
}
}
public class toStringTest{
public static void main(String[] args)
{
Apple a = new Apple("red",3.44);
System.out.println(a);
}
}
这个时候输出的结果应该是 the color is red,the weight is 3.44
一般重写toString()方法总是返回该对象令人感兴趣的信息所组成的字符串。通常可返回如下格式的字符串:
类名[field1=值1,field2=值2,…]
所以上面的toString()方法可以改为:
public String toString()
{
return "Apple[color="+color+"weight="+weight+"]";
}
2.==和equals方法
- ‘==’
- 如果两个变量是基本常量类型,且都是数值类型,则只要两个变量的值相等,返回true;
- 如果是两个引用类型变量,只有指向同一个对象的时候才返回true。
- equals()方法
- 在比较两个引用类型变量时,与‘==’没有区别
- 通过重写equals方法实现
- String已经重写了equals方法,String的equals中,只要两个字符串所包含的字符序列相同,则返回true,否则返回false。