如何检查数组是否为空?

时间:2016-11-09 09:34:25

标签: java arrays

我一直在创建这个java程序,它在数组中找到重复项,并且能够给出重复项的位置。

这是代码

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    // String to list 
    String foxes = "The,Quick,Brown,Fox,Jumps,Over,The,Lazy,Dog."; //*creates string
    System.out.println(" Here is the string unedited: " + foxes); //prints string
    String lowerCase = foxes.toLowerCase() .replaceAll("[\.:;'\"!\?]", " "); //remove punctuation + sets to lower case
    System.out.println(" Here is the string (no caps + no punctuation): " + lowerCase); //prints no punctuation

    List<String> foxesList = new ArrayList<String>(Arrays.asList(lowerCase.split(","))); //converts string into array

Map<String, ArrayList<Integer>> map = new HashMap<>(); //creates new hashmap and array
        for (int i = 0; i < foxesList.size(); i++) { //loops through array
        String fox = foxesList.get(i); //gets the duplicate + its postion
        ArrayList<Integer> list = map.get(fox); //gets duplicate integer

        if (list == null) {
         list = new ArrayList<>(); //creates new list
         list.add(i); //adds duplicate positon to array
          map.put(fox, list); //adds lists/arrays to map
        } else { //else
         list.add(i); //adds duplicate to list 
         System.out.println(" The duplicate was: [" + fox + "] In the positions: " + list); //prints duplicates as well as duplicate postions
        }

        String empty = fox.replaceAll("[\.:;'\"!\?],", " ");
        List<String> emptyfox = new ArrayList<String>(Arrays.asList(empty.split("")));

        if (emptyfox == null) {
         System.err.println("array is empty");
        } else {
         System.err.println("System contains duplicate");
        } 
    }
}      

}

代码存在问题,最后阶段我试图在阵列重复时让系统打印。它当前打印了很多次(这是因为嵌套循环),如果它是空的,则不能正确打印。我删除了方括号和逗号来检查它,但它仍然无法正常工作。以下代码不起作用:

String empty = fox.replaceAll("[\.:;'\"!\?],", " ");
        List<String> emptyfox = new ArrayList<String>(Arrays.asList(empty.split("")));

        if (emptyfox == null) {
         System.err.println("array is empty");
        } else {
         System.err.println("System contains duplicate");

我希望你能帮忙!

1 个答案:

答案 0 :(得分:0)

您可以使用isEmpty()方法检查集合是否为空。 如果要从集合中删除重复的项目,请尝试使用

Set<String> emptyfox = new HashSet<>(Arrays.asList(empty.split("")));
boolean isEmpty = emptyfox.isEmpty()