is it ok to do this... and generics

S

sparkles

sorry about the subject - i'm not quite sure what it is i'm asking is called

is there anything wrong with doing this...?

ArrayList al = new ArrayList();
al.add(new MyClass(1, 2, 3, 4)); <-----

or is it better to do this?

ArrayList al = new ArrayList();
MyClass class = MyClass(1, 2, 3, 4);
al.add(class);

also if the arraylist is instantiated using generics as such

ArrayList<MyClass> al = new ArrayList<MyClass>();

does that mean that al.get() will return a MyClass or do i still have to
cast it?

TIA
 
L

Lee Weiner

sorry about the subject - i'm not quite sure what it is i'm asking is called

is there anything wrong with doing this...?

ArrayList al = new ArrayList();
al.add(new MyClass(1, 2, 3, 4)); <-----

or is it better to do this?

ArrayList al = new ArrayList();
MyClass class = MyClass(1, 2, 3, 4);
al.add(class);

It's called an anonymous object (there is no named variable referencing the
object), and, no, there's nothing wrong with it if you have no other use for
the "class" variable, IMO.
also if the arraylist is instantiated using generics as such

ArrayList<MyClass> al = new ArrayList<MyClass>();

does that mean that al.get() will return a MyClass or do i still have to
cast it?

al.get() will return a MyClass object. There's no need to cast.

Lee Weiner
lee AT leeweiner DOT org
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,260
Messages
2,571,038
Members
48,768
Latest member
first4landlord

Latest Threads

Top