Home > OS >  Java changing size of array objects
Java changing size of array objects

Time:11-23

Let's say I have created an array of objects (Animal) of size 1, but later I call a function that returns an array of objects of size 5. What will happen, animals now will become an array of 5 objects or it will give me some kind of error ?

Animal[] animals = new Animal[1];

animals[0] = new Animal();

animals = createAnimals();

CodePudding user response:

It will work. An array variable does not specify how big the array is. So you can definitely reassign animals to the results of the createAnimals method.

CodePudding user response:

Java changing size of array objects

Nope. That's not what you're doing here at all.

Animal[] animals = new Animal[1];

This does 3 unrelated things:

Animal[] animals;
new Animal[1];
animals = whatever the previous thing returned.
  1. This makes a variable, named animals. variables are like titled postit notes that you can write addresses on.

  2. This makes a new array of size 1. Arrays are like houses. They don't have names, but they have some address.

  3. This writes the address of the house you just built onto your postit note.

When you run animals = createAnimals(), well, createAnimals() returns an address. Not a house - an address of a house. You can't return a house in java; it is simply not possible. All variables are either references or primitives (and that's a hardcoded list of a few numeric types, nothing complicated, all fixed size concepts). animals = createAnimals() simply wipes out your postit (its written in pencil), and writes that address on it instead.

So, if the code of createAnimals looks like:

Animals[] newArr = new Animals[5];
return newArr;

Then the method built an entirely new (larger) house and returned the address of that, and not your postit leads to a different house. The original house is still around. The original house is now, and will forever be, size 1, because java arrays cannot be resized. But array references (postits with addresses on them) can be wiped out and new addresses can be written on them.

So, a house? They don't magically change size. But postits with pencil marks on em? You can run the concept: "Read address from postit, hop in car, drive off, measure house you find at that address" today, and you may get a different result tomorrow: That'd be because someone wrote a different address on the postit, not because someone invented a magic alice in wonderland house.

If you want a new object in java, somebody somewhere needs to call new to make one. Here, let's see it in action:

Animal[] a = new Animal[1];
a[0] = new Dog();
Animal[] b = a;
a[0] = new Cat();
System.out.println(a[0].makeNoise());

That'll print miauw. That's because there's only one house (only one array), and two postits, each with the same address. We merely copied the address with our b = a; instruction, we didn't build a new house.

  • Related