繁体   English   中英

从ArrayList中删除空条目

[英]Removing null entries from a ArrayList

我正在从GeoCoder GoogleMapApi检索地址,并且在将结果提前传递到Spinner对象之前,我需要从列表中删除所有空条目。

我尝试了以下两种方法,但没有任何作用:

locs.removeAll(Arrays.asList("", null));
locs.removeAll(Collections.singleton(null));

--

private List<Address> getAddress(double latitude, double longitude,int maxResults) {
    Geocoder gCoder = new Geocoder(getApplicationContext(),Locale.getDefault());
    try {
        locs = gCoder.getFromLocation(latitude, longitude, maxResults);
        locs.removeAll(Arrays.asList("", null));
        //locs.removeAll(Collections.singleton(null));
    } catch (IOException e) {
        e.printStackTrace();
    }

    return locs;

}

只需使用此代码遍历列表

    for (int i = 0; i < locs.size(); i ++){
        if (locs.get(i) == null){
            locs.remove(i);
            i --;
        }
    }

尝试这个

    List locs = new ArrayList();
    locs.add("");
    locs.removeAll(Arrays.asList("", null));
    System.out.println(locs.size());

输出

0

和这个

    locs.add("");
    locs.removeAll(Collections.singleton(null));
    System.out.println(locs.size());

输出

1

它们是有区别的

for(int i=0;i<list.size();i++) { if(list.get(i)==null||list.get(i).equals(""))// in case of string only otherwise only one检查就足够了{ list.remove(i); i--; }`}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM