关于java:通用工具方法数组

40次阅读

共计 1163 个字符,预计需要花费 3 分钟才能阅读完成。

数组

1. 判断数组内是否有反复元素

/** 判断 String 数组内是否有反复元素 */
    public static boolean checkRepeat(String[] strings){
        boolean result = false;
        List<String> list = new ArrayList<>();
        for (int i=0; i < strings.length; i++){if (!list.contains(strings[i])){list.add(strings[i]);
            }
        }
        if (list.size() < strings.length){
            result = true;
            return result;
        }else {return result;}
    }

测试:

后果:

2. 数组转为 List 汇合

(1)Collections.addAll()办法

System.out.println("---------- 数组转为 List 汇合:Collections.addAll()办法 -----------------------------------");
        String[] strings = {"aa","bb","cc"};
        List<String> list3 = new ArrayList<>();
        Collections.addAll(list3, strings);
        System.out.println(list3.toString());

测试:

(2)循环增加数组元素的办法

System.out.println("---------- 数组转为 List 汇合:循环增加数组元素的办法 -----------------------------------");
        String[] string4 = {"aa","bb","cc","dd"};
        List<String> list4 = new ArrayList<>();
        for (int i=0; i<string4.length; i++){list4.add(string4[i]);
        }
        System.out.println(list4.toString());

测试:

(3)Arrays.asList()办法
返回一个受指定数组反对的固定大小的列表,不能做 Add、Remove 等操作

System.out.println("---------- 数组转为 List 汇合:Arrays.asList()办法 -----------------------------------");
        String[] string5 = {"aa","bb","cc","dd","ee"};
        List<String> list5 = new ArrayList<>();
        list5 = Arrays.asList(string5);
        System.out.println(list5.toString());

测试:

正文完
 0