JAVA中集合(List、HashSet)与数组的转换(Array)

本文详细介绍了在Java中如何进行集合与数组之间的转换,包括List到Array、Array到List、List到HashSet以及HashSet到List的转换方法。转换过程中使用了Arrays工具类和集合的toArray()方法。注意,原始类型数组不能直接用Arrays.asList()转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

JAVA中集合(List、HashSet)与数组的转换(Array)

1、list与Array之间的转换

	/**
     * 1、将数组转为list集合
     * 数组转为List集合,通过Arrays工具类中的asList()方法将数组转为List集合
     * @param strs 传入的数组
     * @return 返回的List集合
     */
    public static List<String> arrayToList(String[] strs){
        List<String> ls = new ArrayList<>(strs.length);
        ls = Arrays.asList(strs);
        return ls;
    }

    /**
     * 2、将List集合转化为数组
     * 将List集合转换为数组,通过List集合总的toArray()方法即可。
     * @param list 传入List集合
     * @return 返回的数组
     */
    public static String[] listToArray(List list){
        String[] strs = (String[]) list.toArray(new String[0]);
        return strs;
    }

2、List与HashSet之间的转换

	 /**
     * 1、将List集合转化为HashSet集合
     * @param hashSet 存入的HashSet集合
     * @return 返回List集合
     */
    public static List<String> listToHashSet(Set<String> hashSet){
        return new ArrayList<>(hashSet);
    }

    /**
     * 2、将HashSet集合转化为List集合
     * @param list 存入的List集合
     * @return 返回HashSet集合
     */
    public static Set<String> hashSetToList(List<String> list){
        return new HashSet<>(list);
    }

3、Array与HashSet之间的转换

	/**
     * 1、数组转化为HashSet,将数组通过Arrays工具类中的asList方法将数组转化为集合在进行转化即可
     * @param strs 传入的数组
     * @return 返回集合
     */
    public static Set<String> arrayToSet(String[] strs){
        return new HashSet<String>(Arrays.asList(strs));
    }

    /**
     * 2、hashSet转化为数组,通过集合的toArray()方法
     * @param hashSet 传入的HashSet集合
     * @return 返回数组
     */
    public static String[] setToArray(Set<String> hashSet){
        return (String[]) hashSet.toArray();
    }

总结

array转化为List集合,通过Arrays工具类中的asList()方法;集合转化为数组,通过调用集合类中的toArray()方法即可。
注意
如果arr 是int[] 或者是其他原始类型的数组 那么不能直接用Arrays.asList()进行转化

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值