为什么会抛出NullPointerException?

Joh*_*nna 0 java collections

这是我的收藏品:

Test<v> map = new Test<V>();
Run Code Online (Sandbox Code Playgroud)

但是当我调用我在Test类中覆盖它的sort方法时,map1是我在Test类中创建的一个集合,它将保留我添加到map集合中的元素,这个异常将被抛出它是for line 5:a [i] = map.get(new Integer(i));

    V[] a = null;
    public void sort() {
    V temp = null;

    for (int i = 0; i < map1.size(); i++) {

        a[i] = map1.get(new Integer(i));

        if (a[i].getName().hashCode() > a[i + 1].getName().hashCode())
            temp = a[i];
        a[i] = a[i + 1];
        a[i + 1] = temp;

    }
Run Code Online (Sandbox Code Playgroud)

Mic*_*rdt 10

V[] a = null;
...
a[i] = ...
Run Code Online (Sandbox Code Playgroud)

这是你的问题.A NullPointerException不仅在尝试调用方法时被抛出null; 尝试通过a访问数组中的索引null具有相同的效果.您必须实例化该数组,但在您的情况下这是有问题的,因为您使用的是泛型类型.使用ArrayList而不是数组.