I have little problem with java. i am not able to get accurate result. what's wrong with this code please help me out from this code your own objects as keys in Maps or in Sets. To use your own objects as keys in Maps or in Sets.code not executing correctly..
what is use of hashcode and equals in java.
Code:
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
class Person {
private int id;
private String name;
public Person(int id, String name) {
this.id = id;
this.name = name;
}
public String toString() {
return "{ID is: " + id + "; name is: " + name + "}";
}
}
public class App {
public static void main(String[] args) {
//creating person object
Person p1 = new Person(0, "Bob");
Person p2 = new Person(1, "Sue");
Person p3 = new Person(2, "Mike");
Person p4 = new Person(1, "Sue");
Map<Person, Integer> map = new LinkedHashMap<Person, Integer>();
//putting on map
map.put(p1, 1);
map.put(p2, 2);
map.put(p3, 3);
map.put(p4, 1);
//displaying the result
for(Person key: map.keySet()) {
System.out.println(key + ": " + map.get(key));
}
//using set
Set<Person> set = new LinkedHashSet<Person>();
//adding on set
set.add(p1);
set.add(p2);
set.add(p3);
set.add(p4);
//displaying the result
System.out.println(set);
}
}
Expected Output:
{ID is: 0; name is: Bob}: 1
{ID is: 1; name is: Sue}: 1
{ID is: 2; name is: Mike}: 3
[{ID is: 0; name is: Bob}, {ID is: 1; name is: Sue}, {ID is: 2; name is: Mike}]