Thursday, July 30, 2009

How to use Map.Entry in java?

I need to use Map.Entry .I don't want to have Objects in type of map.But I need something as in structure(in C). I prefer to use Map.Entry but it is an interface and I cannot make objects from it. how can I use it ?


Thanks in advance

How to use Map.Entry in java?
Struct in C is similar to a class in java.





Just create a new class, example:





public class MyClass{





//put whatever element u want here


private String firstElement;


private int secondElement;


private Map thirdElement;


...





//put getter and setter of the defined elements.


....


}








then u can create a new class :


MyClass testClass = new MyClass();





:)
Reply:If you do not like casting your class to Object each time you're using a Map, there are two things you can do:





1) Use Java 5 generics. A detailed description is linked in sources. The basic idea is instead of using something like:





Map myMap = new TreeMap();





use





Map myMap = new TreeMap%26lt;String,MyClass%26gt;();





and it all works like you'd expect it to. (Of course, if you're not indexing by Strings, feel free to substitute with whatever class your keys are.)





2) If you can't use Java 5 (i.e. JDK1.5), then your only recourse is to reimplement the Map, and Map.Entry. That would involve creating wrappers for all the methods, and is a LOT of work; seriously, unless it's a 100000 line project, you're better off just sticking with casting and Object.





class MyTreeMap implements Map {


private TreeMap map;


public MyTreeMap() {


map = new TreeMap(); return map;


}


public MyClass get(String key) {


return (MyClass) map.get(key);


}


// ... etc. for all Map methods


class Entry {


// ... similarly for Entry class... wrap all methods to pass


// on everything to the "map" variable, and return whatever


// they get back...


}


}


No comments:

Post a Comment