Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.java.programmer > #39948

Re: Why does Java complain if you cast a Map but not an Object?

From Arne Vajhøj <arne@vajhoej.dk>
Newsgroups comp.lang.java.programmer
Subject Re: Why does Java complain if you cast a Map but not an Object?
Date 2023-04-19 15:23 -0400
Organization A noiseless patient Spider
Message-ID <u1pf3r$5ksa$1@dont-email.me> (permalink)
References <632f38ec-674f-44ad-b8d4-53aa32534c09n@googlegroups.com> <u1p97t$4nqi$1@dont-email.me> <4ab3b92b-0570-439a-9022-5498dc95e9d3n@googlegroups.com>

Show all headers | View raw


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:
> 
>> System.out.println(test2(a2)); 
>> System.out.println(test2(a2).get(0).substring(0, 1));
> 
> 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<Integer> to List<String>) 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<Integer> and cast it to a List<String>, 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<String>
> doesn't care that element is Integer

Yes. That is how I see it all work.

Arne

Back to comp.lang.java.programmer | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread


Thread

Why does Java complain if you cast a Map but not an Object? "e.d.pro...@gmail.com" <e.d.programmer@gmail.com> - 2023-04-19 08:16 -0700
  Re: Why does Java complain if you cast a Map but not an Object? Arne Vajhøj <arne@vajhoej.dk> - 2023-04-19 13:43 -0400
    Re: Why does Java complain if you cast a Map but not an Object? "e.d.pro...@gmail.com" <e.d.programmer@gmail.com> - 2023-04-19 11:19 -0700
      Re: Why does Java complain if you cast a Map but not an Object? Arne Vajhøj <arne@vajhoej.dk> - 2023-04-19 15:23 -0400
        Re: Why does Java complain if you cast a Map but not an Object? Michael Jung <miju@golem.phantasia.org> - 2023-04-23 14:30 +0200

csiph-web