2

I have 2 classes. The first describes an item, and the seconds is built around an array of items of the first class.

I had learned that just creating an array of objects doesn't initialize them. So I put a for-loop in the constructor of the 2nd class to initialize all items. Yet when entering the clear() function, all elements of the list array are still null. Why is that?

class HneAnalogItem {
    String  description;
    String  unit;         
    float   value;

   HneAnalogItem(){}        
}

class HneAnalogInfo
{
    static final private int MAXANALOGINFOITEMS = 100;

    private HneAnalogItem[] list;

    HneAnalogInfo() {
        list = new HneAnalogItem[MAXANALOGINFOITEMS];
        for(HneAnalogItem item : list) {
            item = new HneAnalogItem();
        }

        clear();
    }

    void clear() {
        for(HneAnalogItem item : list) {
            item.description = "";
            item.unit = "";
            item.value = 0;
        }
    }
}
Hneel
  • 95
  • 10

1 Answers1

4
for (HneAnalogItem item : list) {
    item = new HneAnalogItem();
}

This enhanced for loop doesn't initialize the array elements. It is equivalent to:

for (int i = 0; i < list.length; list++) {
    HneAnalogItem item = list[i];
    item = new HneAnalogItem();
}

To initialize the array elements you need:

for (int i = 0; i < list.length; list++) {
    list[i] = new HneAnalogItem();
}
Eran
  • 387,369
  • 54
  • 702
  • 768