Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.java.programmer > #36528
| From | Eric Sosman <esosman@comcast-dot-net.invalid> |
|---|---|
| Newsgroups | comp.lang.java.programmer |
| Subject | Re: Generics and downcasts |
| Date | 2017-04-24 22:08 -0400 |
| Organization | A noiseless patient Spider |
| Message-ID | <odmat6$i11$1@dont-email.me> (permalink) |
| References | <generics-20170424231405@ram.dialup.fu-berlin.de> |
On 4/24/2017 6:23 PM, Stefan Ram wrote:
> Naftalin and Wadler write that
>
> List<String> words = new ArrayList<String>();
> words.add("Hello ");
> words.add("world!");
> String s = words.get(0)+words.get(1);
> assert s.equals("Hello world!");
>
> is compiled to the same Bytecode as
>
> List words = new ArrayList();
> words.add("Hello ");
> words.add("world!");
> String s = ((String)words.get(0))+((String)words.get(1))
> assert s.equals("Hello world!");
>
> and then write:
>
> Cast-iron guarantee: the implicit casts added by the
> compilation of generics never fail.
>
> This, of course, immediatly leads to the question:
>
> Since the downcasts added during the compilation of
> the above generic code can never fail and since they
> add run-time costs, can't they be omitted?
No.
> Maybe the purpose of these downcasts is to add
> additional safety for the case of some parts of a
> program not using generics. (I.e., in the presence of
> "unchecked" warning.)
Exactly. Consider the situation when generics were new: It
would be quite common for a List<T> to be manipulated by code that
worked with an unadorned List. Might that other code insert a
non-T in its List? Yes, obviously. So, when the originating code
fetches things from what it thinks is a List<T>, it is in fact
fetching them from a plain old List -- and who knows whether the
things in that List are T's or non-T's?
The sharing of a List<T> with a method that uses plain List
is surely less common nowadays than it was in the past, yet I am
morally certain that it occurs. (And if the `checkcast' operation
were omitted, you can be Absolutely Sure there would soon be
malware taking advantage of it, putting an EvilString into a
List<String> and going "mwah-haah-haaaa!" when an unsuspecting
user of the List<String> did list.get(0).hashCode() and gave
away the keys to the kingdom ...).
> A program might define a /private/ generic class and make
> sure that /all/ accesses to this class use generics, yet it
> still has to pay the price of those downcasts!
It would be instructive if you were to share your measurements
of the "price." (You've made them of course. Of course?)
--
esosman@comcast-dot-net.invalid
Thirteen hundred sixty-seven days to go.
Back to comp.lang.java.programmer | Previous | Next | Find similar | Unroll thread
Re: Generics and downcasts Eric Sosman <esosman@comcast-dot-net.invalid> - 2017-04-24 22:08 -0400
csiph-web