【问题标题】:why Object.to string is returning true for List type为什么 Object.to 字符串为 List 类型返回 true
【发布时间】:2016-06-27 10:24:29
【问题描述】:

我只是出于好奇写了这两行:

public static void main(String[] args) throws InterruptedException {
    Object obj = new ArrayList<String>().add("Some text");
    System.out.println("output : " + obj.toString());
}

因为 Object 类是所有东西的超类,所以这段代码可以正确编译。但是当我运行它时,它给我的输出是:

output : true

可能的原因是什么?

【问题讨论】:

  • ArrayListadd() 返回一个boolean,这就是您存储在obj 中的内容。
  • 我的错....我没注意到 add :|

标签: java list object generics


【解决方案1】:

您正在打印的对象由new ArrayList&lt;String&gt;().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;
}

【讨论】:

    猜你喜欢
    • 2022-01-21
    • 1970-01-01
    • 2014-04-17
    • 2012-04-12
    • 1970-01-01
    • 2015-09-04
    • 1970-01-01
    • 2014-10-14
    • 2018-03-27
    相关资源
    最近更新 更多