Reputation: 1
I am quite a novice programmer so I need so help understanding the difference between arrays storing objects and array lists. Here I have created both but can someone explain what is the difference? Is it that one can store only reference while the other can't or something else?
public class Animal {
int mass;
String color;
String sound;
Animal (int m, String c, String s)
{
mass=m;
color=c;
sound=s;
}
}
import java.util.ArrayList; import java.util.Scanner;
public class Main {
public static void main (String Args [])
{
Animal cat = new Animal(10,"orange","mew");
Animal dog = new Animal(20,"black","Woof");
Animal cow = new Animal(400,"white","muuu");
ArrayList <Animal> a = new ArrayList<Animal>(3);
a.add(cat);
a.add(dog);
a.add(cow);
Scanner scan = new Scanner(System.in);
int mass;
String color;
String sound;
System.out.println("Enter the mass, color and sound of each animal");
Animal [] array = new Animal[3];
for (int q=0; q<3; q++)
{
mass=scan.nextInt();
color=scan.nextLine();
sound=scan.nextLine();
array[q] = new Animal(mass,color,sound);
}
}
}
Upvotes: 0
Views: 25
Reputation: 362
@jcm there are a couple of differences between Array
and ArrayList
. that you can find it from here Array Vs ArrayList.
Now as per your question about reference is, ArrayList and Array both stores the reference
of the object
only. none
of them stores the actual object
. actual objects are stored in the heap memory
.
for more details, you can check this StackOverflow answer.
Upvotes: 1