如何避免以阵列(Java)的引用相同的索引? [英] How to avoid referencing the same index in an array (Java)?

查看:116
本文介绍了如何避免以阵列(Java)的引用相同的索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我的Java数组的问题。我正在使用类作为类中的字段,这些都是静态的,因为我不实例化类的数组。我把这样一个数组(顺便说一句,这是一个对象数组,客户就是自己的类):

I am having problems with my arrays in Java. I am using arrays in classes as class fields, which are all static since I do not instantiate the class. I call an array like so (btw this is an array of objects, 'Customer' is its own class):

 public static Customer[] cDatabase = new Customer[MAX_DATABASE];

其中MAX_DATABASE为常数重新presenting项的最大数目。但发生的事情是,当我键入:

Where MAX_DATABASE is a constant representing the maximum number of entries. BUT what happens is when I type:

 className.cDatabase[0].firstName = "John";

(只使用为简单的方法避免)
该值被调整,但在每一个其他小区的每名字字段阵列中也改变。我相信这有一切与我称为数组的方式,但是当我这样做:

(avoiding using methods just for simplicity) That value is adjusted, but every firstName field in every other cell in the array also changes. I am sure this has everything to do with the way that I called the array, but when I do this:

 for(int i = 0; i<className.MAX_DATABASE; i++){
      className.cDatabase[i] = new Customer();
 }

声明字段,如在此之后:

After declaring the fields like this:

 public static Customer[] cDatabase;

但然后我得到NullPointerException异常。是什么让这个数组正常工作,使元素不指向数组的索引相同的最好方法?
我敢肯定,正确的答案也避免了NPE ...

But then I get nullpointerexception. What is the best way to get this array working properly so the elements do not point to the same index of an array? I'm sure the correct answer also avoids NPE...

推荐答案

您需要做两件事。创建一个新的数组,并提出了新的对象到该数组中。

You need to do both. Create a new array and put new Objects into that array.

public static Customer[] cDatabase = new Customer[MAX_DATABASE];
for(int i = 0; i<className.MAX_DATABASE; i++){
      className.cDatabase[i] = new Customer();
}

这篇关于如何避免以阵列(Java)的引用相同的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆