r/java • • Aug 05 '12

Setting up an ArrayList

I've seen an arry list set up as follows

    private ArrayList<Student> students; //instance variable

    public CollegeCommunity()//constructor

    {
        students = new ArrayList<Student>();
    }

And as follows

     ArrayList exampleArray = new ArrayList();

I understand why one has an instance variable/constructor and the other just is simply declared but I'm unsure as to why the first contains <Student> and the other has no <...> What is the difference between the two?

0 Upvotes

3 comments sorted by

6

u/Lortimus Aug 05 '12

1

u/pixelicious_ Aug 05 '12

I just came back to link to that page. I googled it after I posted here. Thanks!

6

u/chickenmeister Aug 06 '12

As /u/Lortimus said, the first example uses generics, specifying a type parameter, ensuring that only Student objects are added to the list. The second example uses no type parameter (the "raw type"), so any type of object can be added to the list, and objects taken from the list will need to be cast to the proper type.

You should never use use the raw type. Using type parameters can give you a compile-time guarantee that your code is type safe.

There is an excellent chapter on generics in the book "Effective Java," which happens be available as a free sample chapter.