临时哈希表上的NullPointerException

时间:2011-12-08 01:25:51

标签: java nullpointerexception

我有一个项目,我必须允许用户将员工输入哈希表,但是我们无法使用预定义的哈希表。我最终得到了一个arraylists数组,构造函数给它一个值,所以它不会得到nullpointerexception ...然后它在第一行使用哈希表得到一个。我注释掉了该片段,因为它不是绝对必要的,然后在下一个哈希实例中出现了同样的问题。 类和构造函数:

public class Hash {
  private ArrayList<Employee>[] hash = (ArrayList<Employee>[])new ArrayList[5];

//
public Hash()
{
    ArrayList<Employee>[] q = (ArrayList<Employee>[])new ArrayList[5];
   hash=q; 
}

以及发生故障的代码:

do
           {
               p = (int) (Math.random( )*999999) + 1 ;
               for (int w = 0; w<5; w++)
               {
                   boolean t = hash[w].isEmpty(); // The line where I get the NPE Error
                   if (t=false)
                   {
                    for (int r = 0 ; r<hash[w].size(); r++) //where it shows up if I comment out the above.
                    {
                   o=o||p==(hash[r].get(w).geteN());
                   }

               }               
           }
           }
           while (o = true);

我真的不确定如何处理这个...提前谢谢。

5 个答案:

答案 0 :(得分:3)

请记住,当您在Java中声明Array Objects时,必须将Array的每个元素设置为某个内容。否则你只有一个nulls数组。

请在构造函数中尝试此操作:

for (int i=0; i<hash.length; i++)
    hash[i] = new ArrayList<Employee>();

例外情况是,如果您声明Array原语(例如intdouble等),那么您将获得零。

答案 1 :(得分:1)

您没有完成初始化阵列。

public Hash() {
    ArrayList<Employee>[] q = (ArrayList<Employee>[])new ArrayList[5];
    for (int i = 0 ; i != q.length ; i++) {
        q[i] = new ArrayList<Employee>();
    }
    hash=q; 
}

声明点处的初始值设定项也没有效果,您可以删除赋值,因为无论如何都要在构造函数中初始化数组。

答案 2 :(得分:0)

您已经创建了一个数组来保存5 ArrayList<Employee>,但是您还没有创建这5个ArrayList中的每一个来进入数组。

因此,数组中不存在对ArrayList<Employee>个对象的引用,而是将数组中的每个元素设置为null的初始值。因此,当您尝试使用这些不存在的ArrayList<Employee>时,您将导致NullPointerException被抛出。

创建数组后,像这样创建每个ArrayList<Employee>

for (int i = 0; i < hash.length; i++)
   hash[i] = newArrayList<Employee>();

答案 3 :(得分:0)

您的代码非常奇怪且随机,其他代码也有助于查看您是否曾初始化它(这可能是您的问题),但这是我对代码的最佳解释。

do {
        p = (int) (Math.random( )*999999) + 1 ;
        for (int w = 0; w<5; w++) {
            if ( hash[w] != null){
            boolean t = hash[w].isEmpty(); // The line where I get the NPE Error
                if (t == false){
                    for (int r = 0; r<hash[w].size(); r++) {
                        o=o||p==(hash[r].get(w).geteN());
                    }

                }
            }           
        }
   }

答案 4 :(得分:0)

  

...但是我们无法使用预定义的哈希表。

我认为这个是你的真正的错误。除非您有一些极端的性能或内存使用限制,否则最好使用散列表的标准Java实现之一(或Apache Commons,Google Guava等的第三方实现)。他们工作(假如你不做一些愚蠢的事情......比如使用可变键)。它们在典型的用例中表现良好。每个人都理解他们。

实现自己的哈希表几乎肯定是一个糟糕的选择,尤其是因为很容易创建一个在各个方面都不能很好地扩展的实现。 IMO,你最好的选择是将你的自制哈希表代码丢失到你的应用程序之前。


如果您在流程中插入随机数,我不明白哈希表如何可能工作。从算法的角度来看,你的代码是不可理解的......这对我来说毫无意义。


如果你告诉我们为什么你认为你不能使用其中一个标准实现,我们可能会更好地为你提供建议。