Java Programing laungage

java.util Projects

java.util Project 1

Associate a value with an object

In this page of the tutorials, we will be learn how to associate value with an object in Java util. Here, you will know how to associate the value for the separate code. Values regarding to the separate code are maintained as a record of the specific person.

Previous Home Next

Code Description

There are multiple methods and APIs had been used in the program.

IdentityHashMap()

This class is help to creating map interface to the Hash Table for comparison of the object value and object key. by this we can create the new map which is empty and has a default size.

put(Object object_name, Object object_value)

This method is used to associate values for the specific object in the IdentityHashMap. It is take the object name and value.

Set

This is the interface extends the Collection class. It does not contain duplicate items. Set implements all the general Collection methods but it does not allow to store the duplicate element in the set.

IdentityHashMap.EntrySet()

This method is used to returns the view of the set record in the created map.

Iterator

Iterators process all the elements of the Collection. This is the interface which is implemented for every Collections differently.

Example

package r4r;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class associatevaluetest {
public static void main(String[] args)throws IOException
{



try{
  String str;
  IdentityHashMap<Integer,String> map =
new IdentityHashMap<Integer,String>();
  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  System.out.print("Enter hash code for the first object: ");
  int a = Integer.parseInt(br.readLine());
  System.out.print("Enter text value for this code: ");
  map.put(new Integer(a), br.readLine());
  System.out.print("Enter hash code for the second object: ");
  int b = Integer.parseInt(br.readLine());
  System.out.print("Enter text value for this code: ");
  map.put(new Integer(b), br.readLine());
  System.out.print("Enter hash code for the third object: ");
  int c = Integer.parseInt(br.readLine());
  System.out.print("Enter text value for this code: ");
  map.put(new Integer(c), br.readLine());
  System.out.print("Enter hash code for the fourth object: ");
  int d = Integer.parseInt(br.readLine());
  System.out.print("Enter text value for this code: ");
  map.put(new Integer(d), br.readLine());
  System.out.println(map);
  Set set = map.entrySet();
  Iterator it = set.iterator();
  while(it.hasNext()){
  Map.Entry me = (Map.Entry)it.next();
  System.out.print(me.getKey() + ": ");
  System.out.println(me.getValue());
  }
  }
  catch(NumberFormatException ne){
  System.out.println(ne.getMessage() + " is not a legal value.");
  System.exit(0);
  }
  }
}

Previous Home Next