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

Java Java Data Structures - Retired Organizing Data Serialization

Nelson Fleig
Nelson Fleig
25,764 Points

Trouble understanding why in this case the Treet[] array is NOT immutable....

How is it that we are able to return an array that is larger than the size of the array we declared when we initialized variable treets? Aren't arrays supposed to be immutable?

    Treet[] treets = new Treet[0]; /* <--- Initializing array with a length of 0 */
    try (
      FileInputStream fis = new FileInputStream("treets.ser");
      ObjectInputStream ois = new ObjectInputStream(fis); 
    ) {
      treets = (Treet[]) ois.readObject(); /* <--- casting outputed object to the Treet array */ 
    } 

2 Answers

Fahad Mutair
Fahad Mutair
10,359 Points

It's default array that has no elements inside it , the purpose of using it to cast the object of ObjectInputStream readObject method to get Treet type and then assign it to that array again.

It's a useful way to use Array objects in binary files.

Also you can assign it to null instead of Treet[0]

Treet[] treets = null; // this way
Treet[] treets = new Treet[0]; // or this 
shu Chan
shu Chan
2,951 Points

You know honestly, this stuff really should be explained in the video itself

Ok so this would cast the objects in treets to be the Treet type But how can it and other objects be assigned to the array again if an array is immutable?

Premise, I'm a noob. I think you are basically over-writing the object. You would get an error if you tried to add stuff to the Treet[0] array. But since the "treets" array is being assigned to something else the immutability doesn't persist. I'd like to be fact-checked but it seems to add up.

In jshell:

String[] strArr = new String[0]

String[] strArr2 = {"a","b","c","z","d"}

strArr.length

retuns 0

strArr = strArr2

strArr.length

now retuns 5