dcsimg
Maintain Order Insertion For HashMap/HashTable
2 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Nimesh_Patel
Posted On:   Wednesday, November 20, 2002 03:10 PM

I want to use a collection(Key-value) object and maintain the order in which I insert. So when I retrieve information back I have the FIFO order maintained. Any suggestions ?

Re: Maintain Order Insertion For HashMap/HashTable

Posted By:   Aad_Nales  
Posted On:   Saturday, December 28, 2002 03:54 AM

use the LinkedHashMap from JDK 1.4



Aad

Re: Maintain Order Insertion For HashMap/HashTable

Posted By:   Philippe_Fery  
Posted On:   Thursday, December 12, 2002 01:17 AM

Hope this will help you...



package CCM.fifoMap;
import java.util.*;

/**
*
* @author Philippe Fery
* @version 1.0
*/
public class FIFOMap {
private HashMap map;
private ArrayList order;

public FIFOMap() {
map = new HashMap();
order = new ArrayList();
}

public void put(Object key, Object value){
if(!map.containsKey(key)){
System.out.println("New pair K-V");
order.add(key);
}else{
System.out.println("K exists, V modified, insertion at end of queue");
order.add(order.remove(order.indexOf(key)));
}
map.put(key, value);
}

public Object pop(){
Object o = null;
if(order.size()>0){
Object key = order.remove(0);
o = map.remove(key);
System.out.println("Removing last object: Key="+key+" Value="+o);
}else{
System.out.println("The map is empty: can't remove any object!");
}
return o;
}

public Object get(Object key){
Object value = null;
if(order.contains(key)){
value = map.get(key);
}
System.out.println("You get " + value + " with key " + key.toString());
return value;
}

public Object get(int index){
Object o = null;
if(order.size()>index){
Object key = order.get(index);
o = map.get(key);
System.out.println("Index exists: getting index <"+index+"> and returning "+o.toString());
}else{
System.out.println("Index <"+index+"> doesn't exist: returning NULL");
}
return o;
}
}






package CCM.fifoMap;

/**
*
* @author Philippe FERY
* @version 1.0
*/
public class FIFOMapTester {

public FIFOMapTester() {
}

public static void main (String args[]) {
FIFOMap map = new FIFOMap();
map.put("A","Alex");
map.put("P","Phil");
map.get("A");
map.put("G","GĂ©rald");
map.put("L","Laurent S");

map.put("L","Laurent VDB");

map.pop();
map.get(0);
map.get(1);
map.get(2);
map.get(3);
map.get(4);
map.get(5);
}
}



;-)
About | Sitemap | Contact