How to Use User Define Object As Keys in Hashtable in Java


Here this example will explain how to use user defined objects as keys and fetch values. To do this, equals and hashcode methods will be required.

Source Code

1)

package com.beginner.examples;

public class Student {

	private String id;
	private String name;
	private Double score;
	private Integer age;

	public Student(String id, String name, Double score, Integer age) {

		this.id = id;

		this.name = name;

		this.score = score;

		this.age = age;
	}

	@Override
	public boolean equals(Object obj) {

		return this.id.equals(((Student) obj).id);

	}

	@Override
	public String toString() {
		return this.name;
	}

	@Override
	public int hashCode() {

		return this.name.hashCode();
	}

}

2)

package com.beginner.examples;

import java.util.Hashtable;

public class UseHashtableExamples {

	public static void main(String[] args) {
		
		//Create a HashTable object and specify the type of key value
		Hashtable  table = new Hashtable();
		
		//User-defined objects serve as keys
		table.put(new Student("0012", "Tom", 88.6, 10), "Tom");
		
		table.put(new Student("0013", "Jerry", 82.3, 10), "Jerry");
		
		Student s1 = new Student("0013", "Jerry", 82.3, 10);
		
		//Get the value
		String name = table.get(s1);
		
		System.out.println(name);
		

	}

}

Output:

Jerry

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments