【问题标题】:Java: Can we cast a set into an arraylist ?Java:我们可以将一个集合转换成一个数组列表吗?
【发布时间】:2015-02-08 16:51:47
【问题描述】:

我有一个名为gghashmap。我想使用keySet() 方法取出它的键并将它们作为另一个方法的参数传递。

method_A( gg.keySet());

public void method_A(ArrayList<Integer> jj){
 ....
}

但是我得到了这个错误: error: incompatible types: Set&lt;Integer&gt; cannot be converted to ArrayList&lt;Integer&gt;.

然后我看到了这个:

method_A (new ArrayList&lt;Integer&gt;(gg.keySet()));

它实际上在做什么?在我看来,这就像类型转换。我很困惑。有人可以向我解释发生了什么吗?

【问题讨论】:

    标签: java arraylist casting set type-conversion


    【解决方案1】:

    new ArrayList&lt;Integer&gt;(gg.keySet()) 不是类型转换。它更像是一个复制构造函数(尽管实际的复制构造函数通常采用与被实例化的相同类型的参数,但这里不是这种情况)。

    它使用接受Collection 作为参数的构造函数创建一个新的ArrayList&lt;Integer&gt; 实例。它将在Collection 中找到的所有元素添加到新的ArrayList

    这是该构造函数的文档:

       /**
         * Constructs a list containing the elements of the specified
         * collection, in the order they are returned by the collection's
         * iterator.
         *
         * @param c the collection whose elements are to be placed into this list
         * @throws NullPointerException if the specified collection is null
         */
        public ArrayList(Collection<? extends E> c)
    

    【讨论】:

    • 因此,在某种意义上应用迭代器来取出特定集合中的所有元素并将它们添加到数组列表中。我对么 ?另外想问一下&lt;? extends E&gt; c怎么解释?
    • 另外想问一下&lt;? extends E&gt; c怎么解读?
    • @mynameisJEFF 这意味着要使用此构造函数创建ArrayList&lt;E&gt; 的实例,您可以传递任何Collection&lt;T&gt; 实例,以便T 扩展或实现E
    猜你喜欢
    • 2012-12-20
    • 2020-06-24
    • 2015-04-18
    • 1970-01-01
    • 2012-11-20
    • 2022-12-05
    • 2021-06-24
    • 2021-01-07
    • 2019-02-19
    相关资源
    最近更新 更多