Boo*_*ola 0 java generics list object
我只是出于好奇而写了这两行:
public static void main(String[] args) throws InterruptedException {
Object obj = new ArrayList<String>().add("Some text");
System.out.println("output : " + obj.toString());
}
Run Code Online (Sandbox Code Playgroud)
由于Object类是所有内容的超类,因此该代码可以正确编译.但是当我运行它时,它会输出为:
output : true
Run Code Online (Sandbox Code Playgroud)
可能的原因是什么?
Era*_*ran 10
您正在打印的对象将返回new ArrayList<String>().add("Some text").add()返回a boolean(实际上是for ArrayList,它总是返回true),当分配给Object变量时,它被自动装箱到a 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;
}
Run Code Online (Sandbox Code Playgroud)