Write POJO class as a key to hashmap???

Answer Posted / shiv prakash

Class must be final
Class must implement Comparable interface(compareTo() method)
Must override hashCode() and equals() methods
Class must implement Serializable interface

For example- all wrapper classes-Integer, Number, Character, and String

Own class
package com;

import java.io.Serializable;

public final class FinalPerson implements Serializable, Comparable<FinalPerson>{

private static final long serialVersionUID = 1L;

private final Integer personId;

private final String name;

private final String city;

private final String gender;

public FinalPerson(final Integer personId, final String name, final String city, final String gender) {
this.personId = personId;
this.name = name;
this.city = city;
this.gender = gender;
}


public Integer getPersonId() {
return personId;
}


public String getCity() {
return city;
}

public String getGender() {
return gender;
}

public String getName() {
return name;
}

@Override
public String toString() {

return "Person- name:"+this.getName()+", City:"+this.getCity()+",gender:"+this.getGender();
}


public int compareTo(FinalPerson p) {

return this.getName().compareTo(p.getName());
}

@Override
public boolean equals(Object obj) {
FinalPerson p = (FinalPerson)obj;
return this.getPersonId().equals(p.getPersonId());
}

@Override
public int hashCode() {
int hash = 7;
hash = 31* hash + this.getPersonId();
return hash;
}



}

Is This Answer Correct ?    6 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

What is the difference between an if statement and a switch statement?

905


What is a local block?

911


What does flagged out mean?

821


What are the advantages of user defined functions?

770


How many unicode characters are there?

813


What is command line used for?

848


What are the methods available in a class?

839


What is :: operator in java 8?

811


How do I enable java in safari?

794


How dead lock situation occurs in java and how you can identify it?

764


What is the difference between the reader/writer class hierarchy and the inputstream/outputstream class hierarchy in java programming?

867


What is data structure in java?

754


How is java created?

740


What are the types of strings?

801


What is the difference between the boolean & operator and the && operator in java programming?

795