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

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()进行转化

  • 6
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值