It appears you have not yet registered with DEVPPL. To register please click here... (it's fast, easy and free!)

Forum

Log In Sponsors
Board index Programming Java Forum

short question for new learner

short question for new learner

Postby Jose S on Tue May 08, 2007 6:08 pm

Hi, I am a new learner and have a question on creating objects of classes. Let start. Normally I always create an object of a class like the following code:

Car myCar = Car();

But I don't understand in some programs I saw which is similar to the following code.

List<String> contents = new ArrayList<String>();

What is the reason that we don't create like...ArrayList<String> contents = new ArrayList<String>(); could anyone pls clearify me?
Jose S
 
Posts: 4
Joined: Tue May 08, 2007 5:50 pm

Postby meongmania on Wed May 09, 2007 5:52 am

the

List contents = new ArrayList();

means that you r trying to create a new instance of ArrayList and defining the type of the object as List type. It also means that the class ArrayList inherits the List class. You can do that to other type of classes that inherits the List class suchas

- ArrayList
- LinkedList

it's actually an implementation of polymorphism...
meongmania
 
Posts: 16
Joined: Tue Dec 19, 2006 2:58 am

Postby skoiloth on Wed May 09, 2007 11:03 am

It's called "programming to an interface"

If you write "HashSet x = new HashSet();",
and your functions all take "HashSet" as arguments... then you have 2 problems:

1) What if later you decide that it is more efficient to use a different set (eg. TreeSet)?
You would have to rename your code all over the place.

2) What if you accidentally begin to rely on HashSet-specific methods?
(that is, methods that only HashSet has, but no other Set has).
Then later, if you want to change to something like TreeSet which doesn't have that method,
then you may have to do major rewrite of your code
such that it can work without that specific function!

Another way to put it is: chances are your code only cares that it is a Set.
Chances are your code doesn't care that it is a "HashSet".
So... it is logically preferred to reduce your dependency as much as possible.
skoiloth
 
Posts: 6
Joined: Wed May 09, 2007 9:51 am

Postby Jose S on Wed May 09, 2007 1:42 pm

Thank for both of you. I ve got much better idea now.
Jose S
 
Posts: 4
Joined: Tue May 08, 2007 5:50 pm


Who is online

Users browsing this forum: No registered users and 1 guest