I have made a Student class and it in not getting initialized with LinkedHashMap. Giving compile time error :
The type LinkedHashMap is not generic;
it cannot be parameterized with arguments <Student, Integer>.
CODE :
StudentLinkedMap :
public class LinkedHashMap {
public static void main(String[] args) {
Map <Student,Integer> students = new LinkedHashMap<Student,Integer>();
Student s1 = new Student(1,2,"Dhwani","Pandya");
Student s2 = new Student(2,2,"Priyam ","Parekh");
Student s3 = new Student (3,2,"Sucheta","Shrivastava");
Student s4 = new Student(3,6,"Nirali","Rokadia");
Student s5 = new Student(2,6,"Kajari","Agrawal");
students.put(s1,2);
students.put(s2,4);
students.put(s3,6);
students.put(s4,5);
students.put(s5,7);
for(Map.Entry lhs:students.entrySet()){
System.out.println(lhs.getKey()+ " "+ lhs.getValue());
}
}
}
Student Class:
public class Student {
private int rollno;
private String firstname;
private String lastname;
private int std;
public Student(int rollno, int std,String firstname, String lastname){
this.firstname=firstname;
this.lastname=lastname;
this.rollno=rollno;
this.std=std;
}
@Override
public String toString(){
return ("\troll no="+ this.rollno + "\tstandard="+
this.std+"\tfirstname="+this.firstname+"\tlastname="+this.lastname);
}
}
azro
54.3k9 gold badges38 silver badges75 bronze badges
asked Sep 9, 2017 at 13:58
user8512831user8512831
1 Answer 1
You have named your class LinkedHashMap
so the name shadows java.util.LinkedHashMap
. You can either change the name of your class, or use the fully qualified class name.
Map<Student,Integer> students = new java.util.LinkedHashMap<>();
answered Sep 9, 2017 at 13:59
-
after making the changes gives the error - LinkedHashMap cannot be resolved to a typeuser8512831– user851283109/09/2017 14:02:05Commented Sep 9, 2017 at 14:02
-
But i am getting the same 6 outputs - roll no=2 standard=6 firstname=Kajari lastname=Agrawal 2 roll no=2 standard=6 firstname=Kajari lastname=Agrawal 4 roll no=2 standard=6 firstname=Kajari lastname=Agrawal 6 roll no=2 standard=6 firstname=Kajari lastname=Agrawal 5 roll no=2 standard=6 firstname=Kajari lastname=Agrawal 7user8512831– user851283109/09/2017 14:06:00Commented Sep 9, 2017 at 14:06
-
That is a runtime error, seems like your compiler error is fixed. You are using
Student
as a key to theMap
, but you aren't overridinghashCode
... do so (and don't forget to overrideequals
as well).Elliott Frisch– Elliott Frisch09/09/2017 14:15:48Commented Sep 9, 2017 at 14:15 -
. why is overriding hashcode and equals so importantuser8512831– user851283109/09/2017 14:27:26Commented Sep 9, 2017 at 14:27
-
Because a
Map
(orSet
) doesn't allow duplicate keys, so the first thing it does is get the hash of instances to determine where to store it. Once it has that it compares with any values already there, if they're equal it stores the new instance and evicts the old one.Elliott Frisch– Elliott Frisch09/09/2017 14:32:05Commented Sep 9, 2017 at 14:32
lang-java