On 4/19/2023 11:16 AM,
[email protected] wrote:
@SuppressWarnings("unchecked")
public static Map<MyObject,MyObject> testObjectUnchecked(Object in) {
return (Map<MyObject,MyObject>) in; // warning
}
public static Map<MyObject,MyObject> testObjectChecked(Object in) {
return testMap(in); // no warning
}
public static Map<MyObject,MyObject> testMap(Object in) {
if (in instanceof Map) {
Map<?,?> m1 = (Map<?,?>)in;
Map<MyObject,MyObject> m2 = new HashMap<>();
for (Entry<?,?> e : m1.entrySet()) {
m2.put((MyObject)e.getKey(),(MyObject)e.getValue()); // no warning
}
return m2;
}
return Collections.<MyObject,MyObject>emptyMap();
}
I think it makes sense.
(MyObject)e.getKey() and (MyObject)e.getValue() will work
fine if they are a MyObject and throw a ClassCastException
if they are not a MyObject.
(Map<MyObject,MyObject>)in is worse:
- it will work if it is a Map<MyObject,MyObject>
- it will throw a ClassCastException it is not a Map
- it will seemingly work but likely cause a ClassCastException
at some later point if it is a Map<X,Y> but not a
Map<MyObject,MyObject>
Try this example using List instead of Map:
import java.util.ArrayList;
import java.util.List;
public class ToWarnOrNotToWarn {
private static String test1(Object o) {
try {
return (String)o;
} catch(ClassCastException ex) {
System.out.println(o.getClass().getName() + " is not a
String");
return null;
}
}
private static List<String> test2(Object o) {
try {
return (List<String>)o;
} catch(ClassCastException ex) {
System.out.println(o.getClass().getName() + " is not a List<String>");
return null;
}
}
public static void main(String[] args) {
Object o1 = "ABC";
System.out.println(test1(o1));
Object o2 = 123;
System.out.println(test1(o2));
System.out.println(test2(true));
List<String> a1 = new ArrayList<String>();
a1.add("ABC");
System.out.println(test2(a1));
System.out.println(test2(a1).get(0).substring(0, 1));
List<Integer> a2 = new ArrayList<Integer>();
a2.add(123);
System.out.println(test2(a2));
System.out.println(test2(a2).get(0).substring(0, 1));
}
}
result:
ABC
java.lang.Integer is not a String
null
java.lang.Boolean is not a List<String>
null
[ABC]
A
[123]
Exception in thread "main" java.lang.ClassCastException:
java.lang.Integer cannot be cast to java.lang.String
at ToWarnOrNotToWarn.main(ToWarnOrNotToWarn.java:36)
the warning on test2 is justified because the cast in test2 cause
a ClassCastException in main.
Arne
--- SoupGate-Win32 v1.05
* Origin: fsxNet Usenet Gateway (21:1/5)