Forums Register Login

Heap Pollution

+Pie Number of slices to send: Send
Hi,

I was looking through JLS 3rd edition and found this interesting topic :

Heap Pollution

Can someone give a clear but ellaborate example in context of exactly what happens or what is meant by heap pollution? meaning, as the JLS says :
so if I've got:

List l = new ArrayList<Number>();
List<String> ls = l; // cause unchecked warning (as said in JLS, but i am thinking above statement would also give a warning, since its a raw type).

JLS goes on to say that :
This would cause heap pollution because you cannot infer the type at compile time and runtime, my question is, so if we cannot infer the type, then what? how does it affect the heap?

Sorry if the question sounds dumb.

Regards
Vyas, Anirudh
+Pie Number of slices to send: Send
I read the wikipedia explanation, and it's clear as mud. And what kind of word is "reification"? "Instantiation" is bad enough, and don't even get me started on "proactive" (nobody seems to simply take an active role anymore).

OK, returning blood pressure to normal - or as close as I get anymore:

At first glance, your code would appear to be a candidate for a compiler error, but actually not. The problem lies in reducing the object type down to a generic List then promoting it back up again to a type incompatible with the original declaration. In your example, that should produce a warning, but in the real world, the two statements might be sufficiently distant that the compiler can't deduce anything.

On the inside, what I think this means is that the generated code knows that "l" is a List in general, but isn't allowed to do any compile-time checking for anything more, and its run-time options are reduced as well.

Consider this:


Or



No harm done. The danger is if your original case is also possible (say, for example something like this:

+Pie Number of slices to send: Send
Consider this code, which compiles with unchecked warning but no errors



Line 4 produces ClassCastException.

Heap pollution occurs in line 3. After line 3 the list ls contains incorrect item (it is List<String> but contains an Integer).
ice is for people that are not already cool. Chill with this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 3441 times.
Similar Threads
generics
Generics
unchecked warning
Generics doubt
Generics - type argument inference
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 14:37:52.