...

View Full Version : HashMap, ArrayList etc



otnj2ee
02-20-2008, 10:59 PM
I saw many times for the decalration of a reference in the following ways:

Map modelMap = new HashMap();

--NOTICE: it declared as Map not the HashMap

List testList= new ArrayList();

--NOTICE: it declared as List not the ArrayList

etc.


Why not declare them as HashMap map, or ArrayList list? Instead, use the parent Class (Map, List, etc)?


Thanks

Scott

sobrien79
02-21-2008, 02:57 PM
Map is an interface and HashMap is a concrete class that uses that interface. The main point is so that it provides a common set of functionality despite the implementation. There is ArrayList and LinkedList which have different methods of storing the values internally but when you put it in a variable of its parent type then you can be sure that you have certain ways of accessing those values ignoring how they are stored.

Here's a couple of sites about the topic.
http://en.wikipedia.org/wiki/Design_Patterns
http://www.artima.com/lejava/articles/designprinciples.html

anasthesia
02-23-2008, 08:24 PM
One of the main reasons is to take advantage of Polymorphism..

To get a better understanding, consider the following example:

-- Fixture code:

abstract class Star
{
private String name;
public Star(String name)
{
this.name = name;
}
@Override
public String toString()
{
return "Your star is: " + this.name;
}
}

final class Oprah extends Star
{
public Oprah()
{
super("Oprah Winfrey");
}
}
final class Matt extends Star
{
public Matt()
{
super("Matt Deamon");
}
}
final class Bill extends Star
{
public Bill()
{
super("Bill Gates");
}
}

Here is case 1:


public class CustomizableStar
{
private Star star;

public Star getStar()
{
return star;
}
public void setStar(Star star)
{
this.star = star;
System.out.println(star);
}

public static void main(String[] args)
{
CustomizableStar myStar = new CustomizableStar();
//If I feel that Oprah is a real star, I can set her as a star.
myStar.setStar(new Oprah());

//Or now, If I think that MattDeamon better fits into this category, I can set:
myStar.setStar(new Matt());

//Or now if someone else thinks that BillGates is their star,
myStar.setStar(new Bill());

/**
* Idea is simple, setStar is customizable according to what you think 'star' is/should be.
*/
}
/**
* Output:
* Your star is: Oprah Winfrey
Your star is: Matt Deamon
Your star is: Bill Gates
*
*/
}

Now consider Case 2:

public class MyStar
{
private Oprah star;

public Oprah getStar()
{
return star;
}
public void setStar(Oprah star)
{
this.star = star;
System.out.println(star);
}

public static void main(String[] args)
{
MyStar myStar = new MyStar();
/* Only star I can set now is Oprah
* If in future, I ever feel that oprah is not my star anymore, I will have to live with the
* fact that I am bound to only oprah!
*/
myStar.setStar(new Oprah());
}

}



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum