Adding instances of a class to an Arraylist in java
I have 10 instances of the class movie which I wish to add to an Arraylist named Catalogue1
in a class containing a main method I write the following
ArrayList catalogue1= new ArrayList ()
//the class movie is defined in another class
Movie movie1= new Movie ()
Movie movie2= new Movie ()
Catalogue.Add (1, movie1)
What is wrong? Should I define somewhere what kind 开发者_开发问答of Objects this arraylist named catalogue should contain?
Thank you in advance
If that is your verbatim code there are two immediate problems. First your ArrayList variable is "catalogue1" but you are attempting to add an item to "Catalogue", which doesn't exist. Secondly you are adding an item at position 1, which would be out of bounds, since the arraylist is empty. So I would change the code (adding generics as mentioned by Carl's comment:
ArrayList<Movie> catalogue1 = new ArrayList<Movie>();
Movie movie1= new Movie();
Movie movie2= new Movie();
catalogue1.add(movie1); //equivalently: catalogue.add(0, movie1);
catalogue1.add(movie2);
List<Movie> catalogue = new ArrayList<Movie>(10);
catalogue.add(movie1);
catalogue.add(movie2);
...
catalogue.add(movie10);
is how you would do it with generics.
Also note, that generally the practice is to use the interface (List
) instead of the concrete implementation (ArrayList
) when declaring, so that later if you decide that a LinkedList
or perhaps some special MovieList
is preferable for the actual implementation then you have less to fix.
Oh-HO:
Also, your add
as written won't work - it should throw an IndexOutOfBoundsException
. The special List version of add requires that a position already exists (or is 0) before you can add there. So if you want to use that add:
catalogue.add(0,movie10);
catalogue.add(0,movie9);
...
catalogue.add(0,movie1);
if you want them in 1-10 order.
There are several problems here. First of all, if you need to add at the beginning of the list, you need to add at index 0, not 1. Furthermore, if you have JVM 1.5+, you should be using generics.
List catalogue = new ArrayList<Movie>();
..
...
catalogue.add(movie1);
catalogue.add(movie2);//or (0,movie2)
There are some simple typos in your code:
ArrayList catalogue1 = new ArrayList();
Movie movie1= new Movie();
Movie movie2= new Movie();
// Catalogue.Add (1, movie1)
catalogue1.add(movie1);
catalogue1.add(movie2);
As you can see from the code above the two problems you had are:
- The
add()
method of ArrayList starts with a lower-casea
and you used an upper-caseA
. Java identifiers are case sensitive. - You were calling the
add()
method on an object named:Catalogue
but you named your ArrayList:catalogue1
.
精彩评论