简体   繁体   English

初始化成员变量而不是实例变量

[英]initializing a member variable instead of an instance variable

I have been having issues with a class named arrayList that represents a list of objects and supports random access to its objects via a numeric position index. 我遇到了一个名为arrayList的类,该类表示对象列表并支持通过数字位置索引对其对象的随机访问。

After working out the issues with toString() and size() , I encountered an issue where I am not initializing my member array; 解决了toString()size()的问题后,我遇到了一个不初始化成员数组的问题。 only init'ing a locale variable. 仅初始化一个语言环境变量。 However I was under the impression that a modification I made should have solved the issue. 但是,我的印象是,我进行的修改应该可以解决该问题。

public Object get(int a) {
    if (a < 0 || a >= logicalSize) {
        throw new IndexOutOfBoundsException("Positions must be from position 0 to position "+
                                            (logicalSize - 1));
    }
    else {
        return array[a];
    }
} 

But shouldn't my declaration of private static Object[] array = new Object[5]; 但是我不应该声明private static Object[] array = new Object[5]; solve that? 解决那个?

I am currently getting an error throwing my exception, telling me my position must be from 0 to -1, suggesting it isn't created. 我目前在抛出异常时遇到错误,告诉我我的排名必须在0到-1之间,表明未创建。

Full Code: 完整代码:

public class Tester  {
        public static void main(String [] args)
        {
            arrayList a1, a2;
            a1 = new arrayList();
            a2 = new arrayList(5);
            a2.size();
            System.out.println(a1.toString());
            //System.out.println(a2.toString());
        }
    }

public class arrayList
{
    private int logicalSize;
    private static Object[] array = new Object[0];
    private Object[] original;
    private Object removedElement;

    public arrayList()
    {
        Object[] array = new Object[]{null,null,null,null,null}; 
    }

    public arrayList(int i)
    {
        logicalSize = i;
        Object[] array = new Object[logicalSize - 1];
    }

    public arrayList(Object[] array)
    {
       logicalSize = array.length;
       Object[] copyArray = array;
    }

    public String toString(Object[] array)
    {
       String str = " ";

       for(int a = 0; a < logicalSize; a++)
       {
          str = str + array[a];
       }

       str = str + "\nSize: " + size();
      return str;
   }  

   public int size()
   {
       int length = array.length;
       return length;
   }
}

Much Thanks, Packerfan504 非常感谢,Packerfan504

First, you should follow Java conventions for class names. 首先,您应该遵循Java约定中的类名。 It should start with a capital letter and go CamelCase. 它应该以大写字母开头,然后转到CamelCase。

array should certainly not be static . array当然应该是static When you declare a member static , it means that it is shared between all instances 当您声明成员static ,意味着它在所有实例之间共享

In the Constructors, you set local variables instead of the member. 在构造函数中,设置局部变量而不是成员。

 // remove Object[] in front
 array = new Object[]{null,null,null,null,null};

The constructor from an array does not set the member array . 数组的构造函数未设置成员array

public arrayList(Object[] array)
{
   logicalSize = array.length;
   //Object[] copyArray = array;
   this.array = array;
}

This does not do any copy: the member reference the array passed as a parameter. 这不会做任何复制:成员引用作为参数传递的数组。 I you want some kind of "copy constructor", you need to actually instantiate a new array and copy each element. 我想要某种“复制构造函数”,实际上需要实例化一个新数组并复制每个元素。 Or use Arrays.copyOf() . 或使用Arrays.copyOf()

You should overide toString() method from java.langObject with right signature (why pass the array as a parmeter?). 您应该使用正确的签名覆盖 java.langObject toString()方法(为什么将数组作为参数传递?)。 All classes in Java extends implicitly Object class. Java中的所有类都隐式扩展了Object类。

You should differentiate the Object[] array size - which is the number of potenital slots you have before needing an increase of the array, and the logical size that reflects the number of elements you have put in your array. 您应该区分Object[]数组的大小-这是需要增加数组之前的电位槽的数量,以及反映您在数组中放置的元素数量的逻辑大小。 Here you set the logical size to array.length, thats just redundant information. 在这里,您将逻辑大小设置为array.length,那只是多余的信息。


EDIT Additional advices 编辑其他建议

In the constructor with the size as parameter, you create an array of (logicalSize-1). 在以size为参数的构造函数中,创建一个数组(logicalSize-1)。 Why? 为什么?

In the default constructor, you don't initialize logicalSize , it is then set to 0 . 在默认构造函数中,您无需初始化logicalSize ,然后将其设置为0 It's ok for me, but then, why do you set it to i in the constructor with a size as parameter? 对我来说可以,但是,为什么要在构造函数中以大小作为参数将其设置为i呢? Then it's normal that in the a1.get(0) : 然后在a1.get(0)是正常的:

if (a < 0 || a >= logicalSize) {...}

is true and throw the exception. true并抛出异常。

I would recommend that you clarify the role of logicalSize which is (for me) the number of actual objects in the ArrayList . 我建议您弄清楚logicalSize的作用(对我而言)是ArrayList中实际对象的数量。 Note that in your test, you don't put anything in your array yet. 请注意,在测试中,您尚未将任何东西放入数组中。 Even if you have an internal array that can hold 5 Objects, until you add(...) something, calling get(0) should throw an exception. 即使您有一个可以容纳5个对象的内部数组,在add(...) ,调用get(0)引发异常。

You have a class static variable 你有一个类的静态变量

private static Object[] array 

and in your constructor you are creating a local variable array; 然后在构造函数中创建一个局部变量数组;

ie doing this 即这样做

Object[] array 

is again going to create a local variable for that function. 再次将为该函数创建一个局部变量。

since you have declared it Object[] again its going to be a variable within the constructor scope. 由于您再次声明了Object [],因此它将成为构造函数范围内的变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM