Search Java Programs

Wednesday, February 10, 2010

Java program for Associate keys with values

In this tutorial we are going to see how to associate keys with values. Here we are going to see how to create own methods for mapping the keys with values and how to get the value using Key.
public class AssociateExample
{

private Object[][] o;

private int in;

public AssociateExample(int length)
{
o = new Object[length][2];
}

public void put(Object key, Object value)
{
if (in >= o.length)
throw new ArrayIndexOutOfBoundsException();
o[in++] = new Object[] { key, value };
}

public Object get(Object key)
{
for (int i = 0; i < in; i++)
if (key.equals(o[i][0]))
return o[i][1];
throw new RuntimeException("Failed to find key");
}

public String toString()
{
String result = "";
for (int i = 0; i < in; i++)
{
result += o[i][0] + " : " + o[i][1];
if (i < in - 1)
result += "\n";
}
return result;
}

public static void main(String[] args)
{
AssociateExample connect = new AssociateExample(6);
connect.put("education", "business");
connect.put("globe", "warm");
connect.put("people", "refugees");
connect.put("politician", "god");
connect.put("god", "gone");
connect.put("water", "gold");
try
{
connect.put("extra", "object");
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println("Can't put new objects!..");
}
System.out.println(connect);
System.out.println(connect.get("god"));

}
}

Output:

Can't put new objects!..
education : business
globe : warm
people : refugees
politician : god
god : gone
water : gold
gone

No comments:

Post a Comment

Website Design by Mayuri Multimedia