I am trying to understand how Generics work and I have this piece of code to display the entries of newDetails a class with these kind of parameters Map. This is my code.
public class Map<Key,Value> {
private Map<Key, Value> entry;
public Map(){
entry = new HashMap<Key,Value>();
}
public void putEntry(Key k, Value id){
entry.put(k, id);
}
public void printMe(){
System.out.println();
for (Map.Entry<Key, Value> x: entry.entrySet()){
System.out.print(x+" ");
}
}
}
Chocolates Class
public class Chocolates<T> {
private List<T> listOfChocolate = new ArrayList<T>();
public Chocolates(T choc){
listOfChocolate.add(choc);
}
public void addChocolate(T getChoc){
listOfChocolate.add(getChoc);
}
public List<T> getLists(){
return listOfChocolate;
}
}
Main method
public static void main(String[] arg){
Map<Chocolates<String>, Integer> newDetails = new Map<Chocolates<String>, Integer>();
Chocolates<String> choco = new Chocolates<String>();
newDetails.putEntry((new Chocolates<String>("Cadbury")), 1);
newDetails.putEntry((new Chocolates<String>("Hersheys")), 2);
newDetails.printMe();
}
Whenever I try to ran the program it just display this one
generics.Chocolates@9931f5=1 generics.Chocolates@19ee1ac=2
How do I display the actual entries like Cadbury 1 then Hersheys 2?
Also is there any way I can improve the main method or some parts of the program because I always create a new object whenever I add a new entry. Originally what I wanted to do is create a Generics version of this code:
Map<List<String>, Integer> newDetails = new HashMap<List<String>, Integer>();
As someone told me that its alot better to implement that line of code in a Generics Class. Any suggestions? Thanks
EDIT 2
I edited Maps Class printMe Method as Nambari have requested
public void printMe(){
System.out.println();
for (Map.Entry<Key, Value> x: entry.entrySet()){
System.out.print(x.getKey()+" "+x.getValue());
}
}
The output is:
generics.Chocolates@9931f5 1generics.Chocolates@19ee1ac 2
But if I add this line as suggested by Joao
public String toString(){
return listOfChocolate.toString();
}
output is :
[Hersheys] 2[Cadbury] 1
Thanks everyone for your help!
Override
Object#toStringin theChocolateclass: