【问题标题】:getting NullPointerException获取 NullPointerException
【发布时间】:2012-11-20 08:37:40
【问题描述】:

运行 add 方法时,我不断收到“线程“AWT-EventQueue-0”java.lang.NullPointerException 中的异常”。

public class SortedListOfImmutables {

private Listable[] items;

/**
 * This constructor creates an empty list by creating an internal array
 * of size 0.  (Note that this is NOT the same thing as setting the internal
 * instance variable to null.) 
 */
public SortedListOfImmutables() {
    items = new Listable[0];
}

/**
 *  Copy constructor.  The current object will become a copy of the
 *  list that the parameter refers to.  
 *  
 *  The copy must be made in such a way that future changes to
 *  either of these two lists will not affect the other. In other words, 
 *  after this constructor runs, adding or removing things from one of 
 *  the lists must not have any effect on the other list.
 *  
 *  @param other the list that is to be copied
 */
public SortedListOfImmutables(SortedListOfImmutables other) {
    if(other != null) {
        items = new Listable[other.items.length];

        for(int index=0;index<other.items.length;index++){
            items[index] = other.items[index];
        }
    }
}

/**
 * Adds an item to the list.  This method assumes that the list is already
 * sorted in alphabetical order based on the names of the items in the list.
 * 
 * The new item will be inserted into the list in the appropriate place so
 * that the list will remain alphabetized by names.
 * 
 * In order to accommodate the new item, the internal array must be re-sized 
 * so that it is one unit larger than it was before the call to this method.
 *  
 * @param itemToAdd refers to a Listable item to be added to this list
 */
public void add(Listable itemToAdd) {
    if(itemToAdd != null) {
        SortedListOfImmutables temp = new SortedListOfImmutables();
        temp.items = new Listable[this.items.length+1];
        boolean added = false;

        if(this.items.length == 0)
            temp.items[0] = itemToAdd;

        else {
            for(int index = 0;index < this.items.length;index++) {
                if(this.items[index].getName().compareTo(itemToAdd.getName())>0)
                    temp.items[index] = items[index];
                else {
                    if(!added) {
                        temp.items[index] = itemToAdd;
                        added = true;
                    }
                    else temp.items[index+1] = this.items[index];
                }
            }
        }
        this.items = new Listable[temp.items.length];

        for(int tempIndex = 0;tempIndex < temp.items.length;tempIndex++) {
            this.items[tempIndex] = temp.items[tempIndex];
        }
    }
}

Listable 是由 Menagerie 和 Animal 类实现的接口,Menagerie Objects 是动物组。显然,问题是我已经分配了 items 数组但从未分配过它的元素,所以我应该将 this.items[tempIndex] 初始化为一个新对象。但是,它可能是 Animal 或 Menagerie,我不允许使用 instanceOf() 来找出它是哪一个。另外,Animal Constructor 是私有的,所以我不能从一开始就创建一个新的动物对象。 当我尝试将动物添加到 items 数组时,它会很好地添加第一个,但是当我尝试添加更多时会出现 nullpointerexception。我确信解决方案很简单,我只是想多了。

【问题讨论】:

  • 请完整的堆栈跟踪。节省我们的精力。
  • 创建一个0大小的数组有什么意义?
  • @RohitJain - 避免 NullPointerException!
  • 请同时显示您调用 add() 的代码
  • @TedHopp 这不是一个很好的方式。

标签: java arrays eclipse nullpointerexception


【解决方案1】:

如果您使用null 参数调用您的复制构造函数,那么items 将是null,您将在add 中获得一个NPE。当 arg 为 null 时,要么从复制构造函数中抛出异常,要么在所有情况下初始化 items

EDIT 你的代码效率很低。我建议将 ArrayList 用于私有 items 字段。它为您完成所有动态调整大小的工作。像这样的东西应该可以工作:

public class SortedListOfImmutables {

    private List<Listable> items;

    /**
     * This constructor creates an empty list.
     */
    public SortedListOfImmutables() {
        items = new ArrayList<Listable>();
    }

    /**
     *  Copy constructor.  The current object will become a copy of the
     *  list that the parameter refers to.  
     *  
     *  The copy must be made in such a way that future changes to
     *  either of these two lists will not affect the other. In other words, 
     *  after this constructor runs, adding or removing things from one of 
     *  the lists must not have any effect on the other list.
     *  
     *  @param other the list that is to be copied
     */
    public SortedListOfImmutables(SortedListOfImmutables other) {
        items = (other == null)
            ? new ArrayList<Listable>()
            : new ArrayList<Listable>(other.items);
    }

    /**
     * Adds an item to the list. This method assumes that the list is already
     * sorted in alphabetical order based on the names of the items
     * in the list.
     * 
     * The new item will be inserted into the list in the appropriate place so
     * that the list will remain alphabetized by names.
     *
     * itemToAdd will not be added if it is null or if it equals an item
     * already in the list.
     *  
     * @param itemToAdd refers to a Listable item to be added to this list
     */
    public void add(Listable itemToAdd) {
        if (itemToAdd != null) {
            for (int i = 0; i < items.size(); ++i) {
                Listable currentItem = items.get(i);
                int comp = itemToAdd.compareTo(currentItem);
                if (comp > 0) continue;
                if (comp < 0) {
                    // do this unconditionally if you want to allow duplicates
                    items.add(i, itemToAdd);
                }
                return;
            }
        }
    }
}

【讨论】:

    【解决方案2】:

    显然,问题是我已经分配了 items 数组,但是 从未分配过它的元素

    是的。这绝对是一个可能导致空指针异常的问题;)

    但是,它可以是动物或动物园,

    问:“Animal”和“Menagerie”都是某个共同父类的子类吗?

    【讨论】:

      【解决方案3】:

      将您的代码更改为

      public SortedListOfImmutables(SortedListOfImmutables other)
          if(other != null) {
              items = new Listable[other.items.length];
      
              for(int index=0;index<other.items.length;index++){
                  items[index] = other.items[index];
              }
          } else {
             items = new Listable[0];
          }
      }
      

      否则你可以在你的新对象中创建一个空列表。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-12-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多