Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (3.5k points)

I understand this occurs with Java 7 when using varargs with a generic type;

But my question is..

What exactly does Eclipse mean when it says "its use could potentially pollute the heap?"

And

How does the new @SafeVarargs annotation prevents this?

1 Answer

0 votes
by (46k points)

Heap pollution is a professional term. It assigns to implications that have a variety that is not a supertype of the object they point to.

List<A> listOfAs = new ArrayList<>();

List<B> listOfBs = (List<B>)(Object)listOfAs; // points to a list of As

This can head to "unexplainable" ClassCastExceptions.

// if the heap nevermore gets polluted, this should nevermore yield a CCE

B b = listOfBs.get(0); 

@SafeVarargs doesn't anticipate this at all. Nevertheless, there are ways which provably will not pollute the heap, the compiler just can't prove it. Earlier, callers of such APIs would become irritating signs that were completely unnecessary but had to be repressed at every call site. Now the API author can suppress it once at the presentation site.

However, if the method is not safe, users will no higher be warned.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...