为什么 ArrayList 打印的是实际值而不是内存地址?
Why does ArrayList print the actual value and not the memory address?
在Java中,我了解到原始数据类型存储为值,其余数据类型存储为引用。那为什么打印ArrayList实例变量时得到的是实际值,却不是内存地址呢?我有一个数组变量只是为了比较目的。
public static void main(String[] args) {
Object[] a = new Object[3];
a[0] = 0;
a[1] = 1;
a[2] = 2;
ArrayList<Object> b = new ArrayList<Object>();
b.add(3);
b.add(4);
System.out.println(a);
System.out.println(b);
}
因为实现了toString()
方法。默认输出是哈希码。 Memory Address of Objects in Java 文档如何获取内存地址
两个原因
- 因为
Object.toString()
方法被覆盖了
- 因为 javadocs 表示扩展
AbstractCollection
class 的任何类型的 toString()
方法将显示集合的内容,而不是其“地址”。
除此之外 Object.toString()
实际上并没有显示地址。它显示带有 的身份哈希码可能 与对象的地址相关,也可能不相关。 (并且两个不同的对象可以具有相同的身份哈希码,因此它不是对象相同的可靠指标。)
如果要测试两个对象引用(任何类型)是否指向同一个对象,请使用 ==
。
你不需要查看地址,即使你弄清楚了如何获取对象的真实地址......对象地址在 GC 移动它们时会发生变化,所以这可能不是 100% 可靠的测试对象的方法。
您可以自己发现原因。只需按照文档进行操作即可。
println
方法接受一个 String
对象。参见 its Javadoc。引用:
Prints an Object and then terminate the line. This method calls at first String.valueOf(x) to get the printed object's string value, then behaves as though it invokes print(String) and then println().
这意味着对您传递给 println
的集合对象的 toString
方法进行了调用。
因此请查看 ArrayList
继承的 toString
方法的 Javadoc。引用:
Returns a string representation of this collection. The string representation consists of a list of the collection's elements in the order they are returned by its iterator, enclosed in square brackets ("[]"). Adjacent elements are separated by the characters ", " (comma and space). Elements are converted to strings as by String.valueOf(Object).
在Java中,我了解到原始数据类型存储为值,其余数据类型存储为引用。那为什么打印ArrayList实例变量时得到的是实际值,却不是内存地址呢?我有一个数组变量只是为了比较目的。
public static void main(String[] args) {
Object[] a = new Object[3];
a[0] = 0;
a[1] = 1;
a[2] = 2;
ArrayList<Object> b = new ArrayList<Object>();
b.add(3);
b.add(4);
System.out.println(a);
System.out.println(b);
}
因为实现了toString()
方法。默认输出是哈希码。 Memory Address of Objects in Java 文档如何获取内存地址
两个原因
- 因为
Object.toString()
方法被覆盖了 - 因为 javadocs 表示扩展
AbstractCollection
class 的任何类型的toString()
方法将显示集合的内容,而不是其“地址”。
除此之外 Object.toString()
实际上并没有显示地址。它显示带有 的身份哈希码可能 与对象的地址相关,也可能不相关。 (并且两个不同的对象可以具有相同的身份哈希码,因此它不是对象相同的可靠指标。)
如果要测试两个对象引用(任何类型)是否指向同一个对象,请使用 ==
。
你不需要查看地址,即使你弄清楚了如何获取对象的真实地址......对象地址在 GC 移动它们时会发生变化,所以这可能不是 100% 可靠的测试对象的方法。
您可以自己发现原因。只需按照文档进行操作即可。
println
方法接受一个 String
对象。参见 its Javadoc。引用:
Prints an Object and then terminate the line. This method calls at first String.valueOf(x) to get the printed object's string value, then behaves as though it invokes print(String) and then println().
这意味着对您传递给 println
的集合对象的 toString
方法进行了调用。
因此请查看 ArrayList
继承的 toString
方法的 Javadoc。引用:
Returns a string representation of this collection. The string representation consists of a list of the collection's elements in the order they are returned by its iterator, enclosed in square brackets ("[]"). Adjacent elements are separated by the characters ", " (comma and space). Elements are converted to strings as by String.valueOf(Object).