Path: csiph.com!news.mixmin.net!proxad.net!feeder1-2.proxad.net!usenet-fr.net!news.gegeweb.eu!gegeweb.org!news.nntp4.net!.POSTED!not-for-mail From: Michael Jung Newsgroups: comp.lang.java.programmer Subject: Re: Why does Java complain if you cast a Map but not an Object? Date: Sun, 23 Apr 2023 14:30:23 +0200 Message-ID: <87r0saaihs.fsf@golem.phantasia.org> References: <632f38ec-674f-44ad-b8d4-53aa32534c09n@googlegroups.com> <4ab3b92b-0570-439a-9022-5498dc95e9d3n@googlegroups.com> Mime-Version: 1.0 Content-Type: text/plain; charset=utf-8 Content-Transfer-Encoding: 8bit X-Trace: eJwlzU0KAyEMQOF1ewrJXkthaBlEmKsER2yKJqFGev3+zP7xPi7vEZjVlsDFolMZRlw95iyTLUGn59z0gWw4CIO8KsTzqUmtv2xHwwS363JfV4iuIzWfpWtDYhveJMEc5Xve+IBM/xC4i/sAnaoqwQ== User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/26.3 (gnu/linux) Cancel-Lock: sha1:k9Mo5YhZ/zLzZYhRwyTPrrhBAXE= sha1:AKsnBxygH3ug8IqO5+LXgVTeNEM= X-Abuse-Contact: "https://abuse.nntp4.net" Xref: csiph.com comp.lang.java.programmer:39950 Arne Vajhøj writes: > On 4/19/2023 2:19 PM, e.d.pro...@gmail.com wrote: >> On Wednesday, April 19, 2023 at 1:43:39 PM UTC-4, Arne Vajhøj wrote: >> So no warnings about casting one thing to another possibly compatible >> thing (Object to String) because the cast immediately throws >> exception if Object is not a String, but using containers (List, Map) >> it warns because the cast hides the error; it actually allows >> incompatible casting (List to List) and can print >> the resulting object, and crashes when you try to return an element >> into a typed variable. Of course we don't need to worry about >> immediate casting exceptions because it's Runtime. If you take a >> List and cast it to a List, you can call get(idx) >> and return the value into a variable declared as String and crash >> (but it compiles). If you return the value into a variable declared >> as Object, it works, so when you called .get(0) it didn't care that >> it wasn't a String until it tried to process the .substring. As long >> as you treat that result as Object, it's >> fine. System.out.println(test2(a2).get(0).getClass()); // >> List >> doesn't care that element is Integer > Yes. That is how I see it all work. Think of "Object" is the supertype of all objects and "?" as the (generic) subtype of all objects. When you cast Object to Map that is worth a warning because it is a downcast. Casting an arbitrary Map to Map is okay, because the Map *must* map some ? to (another) ?. Later, when you cast ? to MyObject that is an upcast and that is okay. The compiler apparently "loses" the reference that this specific instance of ? could already have been bound to a superclass. Maybe if you replace all "?" with "? extends Object" the compiler knows that the subtype could be Object itself and it issues the warning? It is not "because cast hides errors".