is it ok to do this... and generics

Discussion in 'Java' started by sparkles, Mar 29, 2005.

  1. sparkles

    sparkles Guest

    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
     
    sparkles, Mar 29, 2005
    #1
    1. Advertising

  2. sparkles

    Lee Weiner Guest

    In article <4249d175$>, sparkles <> wrote:
    >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
     
    Lee Weiner, Mar 29, 2005
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Juergen Berchtel
    Replies:
    1
    Views:
    6,033
    John C. Bollinger
    May 20, 2005
  2. puzzlecracker

    tutorial on generics and threads and io

    puzzlecracker, Jan 29, 2006, in forum: Java
    Replies:
    7
    Views:
    832
    Paulus de Boska
    Jan 31, 2006
  3. Frank Fredstone
    Replies:
    1
    Views:
    411
    =?ISO-8859-1?Q?Tobias_Schr=F6er?=
    Sep 19, 2006
  4. kelvSYC
    Replies:
    2
    Views:
    456
    Piotr Kobzda
    Apr 4, 2007
  5. Soul
    Replies:
    0
    Views:
    532
Loading...

Share This Page