 |
AppletTalk.com Java discussions newsgroups
|
| View previous topic :: View next topic |
| Author |
Message |
Guest
|
Posted: Mon Mar 26, 2007 9:00 pm Post subject: Newbie question |
|
|
<br><font size=2 face="sans-serif">There is a particular concept that I
am having a bit of trouble understanding regarding creating new instances
of a class. I will use the ArrayList class as an example, but could
be any class. For example:</font>
<br>
<br><font size=2 face="sans-serif">List myList1 = new ArrayList();</font>
<br><font size=2 face="sans-serif">ArrayList myList2 = new ArrayList()?</font>
<br>
<br><font size=2 face="sans-serif">What would be the difference between
myList1 and myList2? Or, when would it be appropriate to use one
method over the other? My understanding is that myList2 could be
used anywhere an instance of type List would be expected, correct?</font> |
|
| Back to top |
|
 |
Lew Guest
|
Posted: Tue Mar 27, 2007 5:01 am Post subject: Re: Newbie question |
|
|
fugtruck (AT) yahoo (DOT) com wrote:
| Quote: |
There is a particular concept that I am having a bit of trouble
understanding regarding creating new instances of a class. I will use
the ArrayList class as an example, but could be any class. For example:
List myList1 = new ArrayList();
ArrayList myList2 = new ArrayList()?
What would be the difference between myList1 and myList2? Or, when
would it be appropriate to use one method over the other? My
understanding is that myList2 could be used anywhere an instance of type
List would be expected, correct?
|
The difference is that ArrayList inherits from List. 'myList1' only has access
to methods known to List, and could at different times point to Lists that are
not ArrayLists. 'myList2' is known to be an ArrayList, so it has access to any
methods or characteristics not be known to List but present in ArrayList.
The specific type should work fine for most places where you'd use a List.
However, it wouldn't make sense to use an ArrayList variable when you don't
need the extra type knowledge; it would be more reasonable to use a variable
of type List where you don't need to know the specific implementation. You use
the specific type in expressions where the specific type knowledge is vital.
For example, the ArrayList get(int) function is generally faster than the
LinkedList implementation. If your code used that method a lot you might
consider declaring the variable ArrayList to guarantee that performance.
The rule of thumb is to declare a variable as the most general type (highest
up the inheritance tree) you can use but no more so - prefer interfaces to
classes.
-- Lew |
|
| Back to top |
|
 |
|
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum
|
|