Programming Tutorials

(追記) (追記ここまで)

Java program for Associate keys with values

By: Saravanan in Java Tutorials on 2010年01月01日 [フレーム]

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



(追記) (追記ここまで)


Add Comment

JavaScript must be enabled for certain features to work
* Required information
1000

Comments

No comments yet. Be the first!
(追記) (追記ここまで)
(追記) (追記ここまで)

AltStyle によって変換されたページ (->オリジナル) /