View RSS Feed

Advanced Java

Generic Map in Java

Rate this Entry
by , 02-18-2012 at 03:49 PM (1037 Views)
It is possible to generify java.util.Map. Instances of Map in such cases could be of a specific type. Instances of that type in that case could be only inserted as well read, from that Map.
Java Code: This is the code to explain Generic Map
Map<Integer, String> set = new HashMap<Integer, String>;
This Map just can now accept string instances to be as values and Integer instances to be as Keys.

Accessing a Generic Map

Following code could be used for addition of String to generic map.
Java Code: This is the code to explain addition of String to generic map
Map<Integer, String> map = new HashMap<Integer, String>;
Integer key1   = new Integer(123);
String  value1 = "value 1";
map.put(key1, value1);
String value1_1 = map.get(key1);
Iterating a Generic Map

Over generic map, following code would iterate:
Java Code: This is the code to explain iteration over generic map
Map<Integer, String> map = new HashMap<Integer, String>;
Iterator<Integer> keyIterator   = map.keySet().iterator();
while(keyIterator.hasNext()){
  Integer aKey   = iterator.next();
  String  aValue = map.get(aKey);
}

Iterator<String>  valueIterator = map.values().iterator();
while(valueIterator.hasNext()){
  String aString = valueIterator.next();
}

Submit "Generic Map in Java" to Facebook Submit "Generic Map in Java" to Digg Submit "Generic Map in Java" to del.icio.us Submit "Generic Map in Java" to StumbleUpon Submit "Generic Map in Java" to Google

Tags: generic map Add / Edit Tags
Categories
Generics

Comments