I have created two maps as shown below. Can any one explain why the output of the program is like this and why deletecontent method allowed me to pass mymap2? Difference between creating mymap and mymap2
public class Candidate {
public static void main(String[] args) {
// TODO Auto-generated method stub
LinkedHashMap<Integer, String> mymap= new LinkedHashMap<Integer, String>();
mymap.put(1, "INDIA");
mymap.put(2, "USA");
mymap.put(3, "RUSSIA");
LinkedHashMap mymap2= new LinkedHashMap();
mymap2.put("1", "INDIA");
mymap2.put("2", "USA");
mymap2.put("3", "RUSSIA");
deleteContent(mymap);
deleteContent(mymap2);
print(mymap);
System.out.println("------------------");
print(mymap2);
}
private static void print(LinkedHashMap<Integer, String> mymap) {
for (Entry<Integer, String> e: mymap.entrySet()) {
System.out.println(e.getKey()+"-----"+ e.getValue());
}
}
private static void deleteContent(LinkedHashMap<Integer, String> mymap) {
// TODO Auto-generated method stub
mymap.remove("3");
}
}
output of the below program is
1-----INDIA
2-----USA
------------------
1-----INDIA
2-----USA
3-----RUSSIA
The output you put in your question is not the output this code actually produces, which is :
1-----INDIA
2-----USA
3-----RUSSIA
------------------
1-----INDIA
2-----USA
The second Map has String keys and String values. Therefore, only for the second Map mymap.remove("3");
removes an entry from the Map.
mymap.remove("3");
passed compilation, even though mymap
is a LinkedHashMap<Integer, String>
, since remove
accepts a parameter of type Object
.
deleteContent
allows you to pass a raw LinkedHashMap
type to it due to backwards compatibility. You might have old (pre-Java 5) methods that return raw types, so you are allowed to pass them to newer methods that expect parameterized types.
Well, 3
is not the same as "3"
(one is an Integer
and the other is a String
) - that's why the output is different - the first map has no key to remove.
That the code actually compiles is a surprise to me as well. I guess that's another reason for not using raw types anymore.
Also, for me the output is
1-----INDIA
2-----USA
3-----RUSSIA
------------------
1-----INDIA
2-----USA
not the other way around.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.