从数组中删除空元素(Java) [英] Removing empty element from Array(Java)

查看:240
本文介绍了从数组中删除空元素(Java)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过将现有的元素复制到一个新的数组中去除数组中的空元素。但是,初始化新数组会导致我的返回值为null,即使在循环中初始化它时也是如此。

  public String [] wordsWithout(String [] words,String target){
for(int i = 0; i< words.length; i = i +1 ){
String store [] = new String [words.length];
if(words [i] == target){
words [i] =;
}
else if(words [i]!= target){
words [i] = store [i];
}
}
返回单词;




$ div class =h2_lin>解决方案

数组是不可变的,保持不变,你需要创建一个新的数组
所以,如果你创建一个新的数组基地的旧数组的大小,你仍然会有空元素



如果只想使用数组,则只需计算数组中的非空元素即可获取新数组的大小。它只是更容易使用一个List / ArrayList

  public String [] wordsWithout(String [] words,String target){
List< String> tempList = new ArrayList< String>();
for(int i = 0; i
if(words [i]!= null || words [i] .trim ().length()> 0){
tempList.add(words [i]);
}

}
return(String [])tempList.toArray();
}


I'm trying to remove the empty element from the array by copying the existing element to a new array. However, initialization of the new array is causing my return value to be null even when I initialize it within the for loop.

public String[] wordsWithout(String[] words, String target) {
    for(int i = 0; i < words.length; i = i +1){
        String store[] = new String[words.length];
        if (words[i] == target){
            words[i] ="";
        }
        else if(words[i] != target){
            words[i] = store[i];
        }       
    }
    return words;
}

解决方案

Array are immutable so the size stays the same you need to create a new Array So if you create a new Array base on the Size of the Old array you will still have null elements

If you want to use arrays only you need to count the non null elements in the array to get the size of the new Array. It just easier to use a List/ArrayList

public String[] wordsWithout(String[] words, String target) {
    List<String> tempList=new ArrayList<String>();
    for(int i = 0; i < words.length; i = i +1){

        if (words[i]!=null||words[i].trim().length()>0){
            tempList.add(words[i]);
        }

    }
    return (String[]) tempList.toArray();
}

这篇关于从数组中删除空元素(Java)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆