You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中将int类型数组转换为Vector<Integer>的最优方法是什么?

报错根因

你传入Arrays.asList()的是基本类型int数组,该方法只能接收对象类型数组作为参数,传入基本类型数组时会把整个数组识别为单个对象元素,返回的是List<int[]>类型,和你需要的List<Integer>类型完全不匹配,因此触发泛型边界不兼容的报错。

可用转换方案

  • JDK 8+ 流式转换(推荐,写法简洁效率高)

    直接通过IntStream完成自动装箱再收集为Vector,无额外冗余步骤:

    import java.util.Arrays;
    import java.util.Vector;
    import java.util.stream.Collectors;
    
    // 转换逻辑
    int [] nums={1,2,3,1,1,3};
    Vector<Integer> num = Arrays.stream(nums)
            .boxed()
            .collect(Collectors.toCollection(Vector::new));
    
  • 全版本兼容遍历转换(性能最优,无额外依赖)

    手动遍历数组逐个元素插入,兼容性最好,无多余的中间对象生成,性能高于其他方案:

    import java.util.Vector;
    
    int [] nums={1,2,3,1,1,3};
    Vector<Integer> num = new Vector<>(nums.length); // 预初始化容量避免扩容开销
    for (int n : nums) {
        num.add(n);
    }
    
  • 适配Arrays.asList写法的调整方案

    如果你需要保留Arrays.asList的写法,要先把基本类型int数组转为包装类型Integer数组:

    import java.util.Arrays;
    import java.util.Vector;
    
    int [] nums={1,2,3,1,1,3};
    Integer[] boxedNums = new Integer[nums.length];
    for (int i = 0; i < nums.length; i++) {
        boxedNums[i] = nums[i];
    }
    Vector<Integer> num = new Vector<>(Arrays.asList(boxedNums));
    

注意:Vector是JDK早期提供的线程安全集合类,所有操作默认加synchronized锁,如果你没有多线程场景下的线程安全需求,替换为ArrayList可以获得更高的运行性能。

内容的提问来源于stack exchange,提问作者Rakshith B S

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 05:39:01