Programming Tutorials

Java program for Map

By: Saravanan in Java Tutorials on 2009-10-03  

In this Tutorial we are going to see how to implement Map with arraylist. This is an example of a Map. We must import some of the packages as below.

   import java.util.AbstractMap;
  import java.util.ArrayList;
  import java.util.HashSet;
  import java.util.Iterator;
  import java.util.List;
  import java.util.Set;

  public class MapExample extends AbstractMap
  {

   private List listk = new ArrayList();
   private List listv = new ArrayList();

   public Object put(Object key, Object value) 
   {
     Object result = get(key);
     if (!listk.contains(key))
     {
       listk.add(key);
       listv.add(value);
      }
      else
       listv.set(listk.indexOf(key), value);
      return result;
      }

    public Object get(Object key)
   {
     if (!listk.contains(key))
      return null;
    return listv.get(listk.indexOf(key));
    }

      public Set entrySet()
      {
        Set entries = new HashSet();
         Iterator ki = listk.iterator();
         Iterator vi = listv.iterator();
        while (ki.hasNext())
        entries.add(new Map11(ki.next(), vi.next()));
         return entries;
  }

  public String toString()
  {
    StringBuffer s = new StringBuffer("{");
    Iterator ki = listk.iterator(), vi = listv.iterator();
    while (ki.hasNext())
    {
      s.append(ki.next() + "=" + vi.next());
      if (ki.hasNext())
        s.append(", ");
    }
    s.append("}");
    return s.toString();
  }

  public static void main(String[] args)
   {
    MapExample m = new MapExample();
    m.put("Netscape", "Mountain View, CA");
    m.put("Adobe", "Mountain View, CA");
    m.put("Sun", "Mountain View, CA");
    m.put("Microsoft", "Redmond, WA");
    m.put("IBM", "White Plains, NY");
    m.put("O'Reilly", "Sebastopol, CA");
    m.put("Learning Tree", "Los Angeles, CA");
    System.out.println(m);

  }
} 


class Map11 implements Entry, Comparable
 {
  Object key, value;
  Map11(Object k, Object v)
  {
    key = k;
    value = v;
  }
  public Object getKey()
  {
   return key;
  }
  public Object getValue()
  {
   return value;
  }
  public Object setValue(Object v)
  {
    Object result = value;
    value = v;
    return result;
  }
  public boolean equals(Object o) {
    return key.equals(((Map11)o).key);
  }
  public int compareTo(Object rv) {
    return ((Comparable)key).compareTo(
      ((Map11)rv).key);
  }
}





Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in Java )

Latest Articles (in Java)