Java program for Associate keys with values
By: Saravanan Printer Friendly Format
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
Comment on this tutorial
- Data Science
- Android
- AJAX
- ASP.net
- C
- C++
- C#
- Cocoa
- Cloud Computing
- HTML5
- Java
- Javascript
- JSF
- JSP
- J2ME
- Java Beans
- EJB
- JDBC
- Linux
- Mac OS X
- iPhone
- MySQL
- Office 365
- Perl
- PHP
- Python
- Ruby
- VB.net
- Hibernate
- Struts
- SAP
- Trends
- Tech Reviews
- WebServices
- XML
- Certification
- Interview
categories
Subscribe to Tutorials
Related Tutorials
Program using concept of byte long short and int in java
Update contents of a file within a jar file
Tomcat and httpd configured in port 8080 and 80
Count number of vowels, consonants and digits in a String in Java
Student marks calculation program in Java
Calculate gross salary in Java
Calculate average sale of the week in Java
Vector in Java - Sample Program
MultiLevel Inheritance sample in Java