一、Object.toString() 的返回值格式
返回该对象的字符串表示。
通常,toString 方法会返回一个“以文本方式表示”此对象的字符串。结果应是一个简明但易于读懂的信息表达式。建议所有子类都重写此方法。
Object 类的 toString 方法返回一个字符串,该字符串由类名(对象是该类的一个实例)、at 标记符“@”和此对象哈希码的无符号十六进制表示组成。换句话说,该方法返回一个字符串,它的值等于:
getClass().getName() + ‘@’ + Integer.toHexString(hashCode())
示例:
public class Test {
public static void main(String[] args) {
User[] users = new User[5];
for (int i = 0; i < users.length; i++) {
users[i] = new User(i);
}
System.out.println(users);
}
}
class User{
int id;
public User(int id) {
super();
this.id = id;
}
}
运行结果:
[Lyu.bai.array.User;@659e0bfd
二、(ArrayList) list.toString()
集合ArrayList类的toString()方法继承自 类 java.util.AbstractCollection,源代码参考如下:
源代码:
public String toString() {
Iterator<E> it = iterator();
if (! it.hasNext())
return "[]";
StringBuilder sb = new StringBuilder();
sb.append('[');
for (;;) {
E e = it.next();
sb.append(e == this ? "(this Collection)" : e);
if (! it.hasNext())
return sb.append(']').toString();
sb.append(',').append(' ');
}
}
集合List 的toString()方法:
返回此 collection 的字符串表示形式
该字符串表示形式由 collection 元素的列表组成,这些元素按其迭代器返回的顺序排列,并用方括号 (“[]”) 括起来。相邻元素由字符 “, “(逗号加空格)分隔。通过 String.valueOf(Object) 可以将元素转换成字符串。
覆盖:类 Object 中的 toString
返回:此 collection 的字符串表示形式
示例:
public class ContainerComparison {
public static void main(String[] args) {
List<BerylliumSphere> list = new ArrayList<BerylliumSphere>();
for (int i = 0; i < 5; i++) {
list.add(new BerylliumSphere());
}
System.out.println(list.toString());
}
class BerylliumSphere {
private static long counter;
private final long id = counter++;
public String toString(){
return "Sphere " + id;
}
public long getCounter() {
return counter;
}
public long getId() {
return id;
}
}
}
运行结果:
[Sphere 0, Sphere 1, Sphere 2, Sphere 3, Sphere 4]