java - ArrayList 空指针异常

标签 java android arraylist

将对象添加到 hello ArrayList 时遇到 NullPointerException。我想在特定索引处添加对象,因此如果我事先没有将 null 对象添加到数组中,当我尝试在以下索引处添加对象时,我会收到 IndexOutOfBoundsException :之前的索引尚未填充。为什么我会收到 NullPointerException 以及是否有其他方法可以实现它?

    public void test()
    {
        ArrayList<TEST> temp = new ArrayList<>(4);

        temp.add(0,new TEST(2));
        temp.add(1,new TEST(3));
        temp.add(2,new TEST(1));
        temp.add(3,new TEST(0));


        for(int i=0; i<4; i++)
            Log.e("test", "i: "+i+ " index: "+temp.get(i).x);


        ArrayList<TEST> hello = new ArrayList<>(4);
        hello.add(null);
        hello.add(null);
        hello.add(null);
        hello.add(null);

        hello.add(temp.get(0).x, temp.get(0));
        hello.add(temp.get(1).x, temp.get(1));
        hello.add(temp.get(2).x, temp.get(2));
        hello.add(temp.get(3).x, temp.get(3));


        Log.e("test", "___________________________");
        for(int i=0; i<4; i++)
            Log.e("test", "i: "+i+ " index: "+hello.get(i).x);

    }

    public class TEST
    {
        int x;

        public TEST(int x) {
            this.x = x;
        }


    }

最佳答案

当你写的时候

hello.add(temp.get(0).x, temp.get(0));

您不会替换放入 temp.get(0).x 索引中的 null。您只需将该 null 移动到下一个索引即可。

因此,在循环中:

    for(int i=0; i<4; i++)
        Log.e("test", "i: "+i+ " index: "+hello.get(i).x);

您遇到 null 值,因此 hello.get(i).x 抛出 NullPointerException

修改为

    hello.set(temp.get(0).x, temp.get(0));
    hello.set(temp.get(1).x, temp.get(1));
    hello.set(temp.get(2).x, temp.get(2));
    hello.set(temp.get(3).x, temp.get(3));

以便用非空值替换所有空值。

关于java - ArrayList 空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28134453/

相关文章:

java - json 格式的 hashmap 输出数组

c# - C#中的多维关联数组

java - 为什么 DocumentFile 这么慢,我应该用什么来代替?

java - 未调用 RecyclerView 适配器方法

android - android surfaceview在调整大小时崩溃

android - 带有 Recyclerview 的 ViewPager 上的 NullPointerException

java - java 中 arrayList 与 Set 的比较

java - 在布局中使用表面 View 隐藏/显示软键盘时的黑色区域

java - 所有应用内购买都会在五分钟内取消并退款(Alpha 测试)

java - 修改 JavaFX Accordion