Bravoure754 2022-09-23 17:39
浏览 15
已结题

关于toMutableList()与数据类型转化的问题

在学习kotlin泛型型变时,写了以下代码

val list2 = mutableListOf<Int>(4,4,5)
val list : MutableList<out Number> = list2

然后尝试了一下错误的写法

val list3 : MutableList<Number> = list2//error

发现以下代码不会报错

val list3 : MutableList<Number> = list2.toMutableList()

通过源码可以看到数据类型没有变化

/**
 * 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) {
    Object[] a = c.toArray();
    if ((size = a.length) != 0) {
        if (c.getClass() == ArrayList.class) {
            elementData = a;
        } else {
            elementData = Arrays.copyOf(a, size, Object[].class);
        }
    } else {
        // replace with empty array.
        elementData = EMPTY_ELEMENTDATA;
    }
}

所以是如何跳过类型转换的?

  • 写回答

0条回答 默认 最新

    报告相同问题?

    问题事件

    • 系统已结题 10月1日
    • 创建了问题 9月23日

    悬赏问题

    • ¥15 matlab数据降噪处理,提高数据的可信度,确保峰值信号的不损失?
    • ¥15 怎么看我在bios每次修改的日志
    • ¥15 python+mysql图书管理系统
    • ¥15 Questasim Error: (vcom-13)
    • ¥15 船舶旋回实验matlab
    • ¥30 SQL 数组,游标,递归覆盖原值
    • ¥15 为什么我的数据接收的那么慢呀有没有完整的 hal 库并 代码呀有的话能不能发我一份并且我用 printf 函数显示处理之后的数据,用 debug 就不能运行了呢
    • ¥20 gitlab 中文路径,无法下载
    • ¥15 用动态规划算法均分纸牌
    • ¥30 udp socket,bind 0.0.0.0 ,如何自动选取用户访问的服务器IP来回复数据