Re: why people use "Map m= new HashMap()" or "List l = new ArrayList()"?
www wrote:
However, I still didn't get the answer. My old code is like:
You did get the answer to the question that you asked, many times over.
public class MyClass {
private Map<String, String> _map;
By convention, variable names should not include underscores unless they
represent compile-time constants.
public MyClass() {
_map = new HashMap<String, String>();
}
public Map getMap() {
return _map.clone(); //Oops! wrong! no clone() method for Map
}
}
Now, my new code is like:
public class MyClass {
private HashMap<String, String> _map;
public MyClass() {
_map = new HashMap<String, String>();
}
public HashMap getMap() {
You can still return a type Map, and you must not omit the generic declaration.
return ((HashMap)_map.clone()); //clone() is available for
HashMap
But you are applying the cast to the result of clone(), not the variable
'_map' here.
Also, in Java casting and generics don't mix well.
}
}
Do you see anything wrong with my new code?
Yes.
How about this (which I've compiled, but not run)?
public class MapCloner
{
private Map <String, String> stuff = new HashMap <String, String> ();
/** Get the <code>stuff</code> map.
* @return <code>Map < String, String ></code> stuff.
*/
public Map <String, String> getStuff()
{
return new HashMap <String, String> ( stuff );
}
// TODO methods to put values into the Map, etc., go here
/** Main method.
* @param args <code>String []</code> program arguments.
*/
public static void main( String [] args)
{
// TODO code application logic here
}
}
Like clone(), the HashMap(Map<? extends K,? extends V> m) constructor does a
shallow copy.
--
Lew