Why is the data array in java.util.ArrayList package-private?

In the java.util.ArrayList class, the object array for the list’s elements is defined as package-private:

transient Object[] elementData; // non-private to simplify nested class access

The comment states that the reason why this field is not private is easier access in nested classes. However, nested classes can access private data of the enclosing class just fine. So why is elementData not private? Is there something happening in the background (e.g., at compilation time)?


When you access a private field from a nested class, the compiler actually generates a synthetic accessor method that is package-visible, and then uses that for the access. It can’t access the private member directly, so to avoid that indirection you can make the member package-visible instead.

Here’s an answer with more details.

Source: stackoverflow
Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Privacy Policy, and Copyright Policy. Content is available under CC BY-SA 3.0 unless otherwise noted. The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 © No Copyrights, All Questions are retrived from public domain..