我只是出于好奇才写了这两行:
public static void main(String[] args) throws InterruptedException {
Object obj = new ArrayList<String>().add("Some text");
System.out.println("output : " + obj.toString());
}
由于 Object 类是所有内容的父类(super class),因此该代码可以正确编译。但是当我运行它时,它给我的输出为:
output : true
可能的原因是什么?
最佳答案
您正在打印的对象由 new ArrayList<String>().add("Some text")
返回。 add()
返回 boolean
(事实上,对于 ArrayList
,它总是返回 true
),当分配给 Object
变量时,它会自动装箱为 Boolean
。
/**
* Appends the specified element to the end of this list.
*
* @param e element to be appended to this list
* @return <tt>true</tt> (as specified by {@link Collection#add})
*/
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
关于java - 为什么 Object.to string 对于 List 类型返回 true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38051529/