【问题标题】:Size of the list does not match the ones it has列表的大小与它的大小不匹配
【发布时间】:2016-08-03 02:54:58
【问题描述】:

我有一个包含 20 个元素的列表,但它在第 15 位包含一个空值,如何从 List 中删除空值?

【问题讨论】:

  • 您能发布用于执行此操作的代码吗?然后我们可以就如何改变它提出建议。
  • 非常不清楚的问题。您是在问如何从列表中删除空元素?

标签: java android json arraylist


【解决方案1】:

如果您不希望“空”图像出现在列表中,只需执行以下操作:

for each item on a list
    if item == null then continue
    else 
        add an item to <List>Images

如果您将空对象传递给图像列表,它仍然会占据列表中的位置,即使该位置在技术上未初始化。

【讨论】:

    【解决方案2】:

    你不能说null 值意味着对象不存在,即使null 不是java 中的对象。

    String s = null表示String s的引用未设置,但声明完成,是一个String类型的对象,名为s。

    查看更多详情,oracle doc: The Kinds of Types and Values

    public static void main(String[] args)
    {
        ArrayList al = new ArrayList();
        al.add(null);
        al.add("not null");
        System.out.println(al.size()); //output 2
    
        //if you wanna know how many objects inside of list and isn't null
        int count=0;
        for(Object obj:al)
            if(!(obj==null)) 
                count++;
        System.out.println(count); //output 1
    
        System.out.println(al); //output [null, not null] ← null is exist.
    }
    

    所以在你的情况下,size() 的返回值应该是 20。

    【讨论】:

      【解决方案3】:

      经过几天的研究,我使用来自@Lithium 的solution

      tourists.removeAll(Collections.singleton(null));

      此代码从列表中删除所有空值。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-04-21
        • 1970-01-01
        • 2020-12-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-10-25
        相关资源
        最近更新 更多