Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Android Build a Simple Android App (2014) Coding the Fun Facts Properties of Arrays

Emily Cain
Emily Cain
5,850 Points

why not facts.length()?

I'm just wondering why length is not a method of an array like it is for other data structures (e.g. set.size()).

1 Answer

William Li
PLUS
William Li
Courses Plus Student 26,867 Points

Hi, Emily Cain

That's the language design choice made by the Java creator; I believe it's mainly for memory efficiency.

From Oracle's Java Array doc

An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed.

Because Array's length is fixed and never going to change, it makes sense to have it as a final instance variable.

Same can't be done for the set in java; because Set has interfaces such as set.add() that adds object to the collection hence changing the size of a Set, it's not possible to have its length stored as final instance variable, it must be calculated dynamically by calling the method set.size().