-2

I am trying to reduce the amount of memory being used in a Java project I'm working on, and one of the thing I'm looking into is using iterators of arrays, rather that copies of arrays. However, I'm not sure if this will work or not with private data inside of an object. For instance:

public class MyClass {
    private ArrayList<String> data;

    public ArrayList<String> getData(){ return this.data; }
    public Iterator getDataIter(){ return this.data.iterator(); }
}

public static void main(String[] args) {
    MyClass c = MyClass();
    ArrayList<String> copyOfData = c.getData();

    Iterator dataIter = c.getDataIter();
}

As you can see, in main() I couldn't just go c.data because it is private. However, c.getData() will copy the whole array. So here are my questions:

  1. Will dataIter be able to iterate over the values in data, even though it is a private variable?
  2. Will doing this save me any memory because I'm not passing large arrays around anymore?
caffein
  • 575
  • 8
  • 26
  • 3
    `getData` will not copy whole array – Iłya Bursov Feb 25 '19 at 23:42
  • As for saving memory: If I'm not mistaken, the reference to the array is passed by value to subroutines. The actual values are not copied. This is why void methods have side effects on arrays (and objects). – vapurrmaid Feb 25 '19 at 23:45
  • Just as a data point: `ArrayList.iterator()` iterates over a private array. – Andy Turner Feb 25 '19 at 23:46
  • 1
    I'm voting to close this question as off-topic because the question is based on a misunderstanding of how Java object references work, and the posed question is therefore meaningless. – Andreas Feb 25 '19 at 23:48
  • I see, what confused me is how Java uses pass-by-value for input and output of methods. But if those values are references, then I wouldn't need to worry about the size. – caffein Feb 25 '19 at 23:49

1 Answers1

1

c.getData() will not copy the whole array, at least, not in the code you pasted.

That makes the rest of the questions moot, but, sure, dataIter works fine here.

I suggest you review how java's memory model works. All non-primitive values (all objects) are passed around in reference form. this.data is a pointer to the array. If you return it, you return a copy of the pointer, which is a small number (64-bit usually), which refers to the array.

You can trivially test this: call .getData(), and modify something in the array. That modification will also occur in the MyClass, because there's just one array, with both the data field as well as the result of calling getData() referencing this one array.

rzwitserloot
  • 85,357
  • 5
  • 51
  • 72
  • It's still passing by value - it's just that the value passed is the value of the reference. https://stackoverflow.com/a/12757868/8954866 – vapurrmaid Feb 25 '19 at 23:48