Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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,868 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().