Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint

Wildcards to the rescue

It looks unusual, but there is a way to create a method argument that can accept an ArrayList of any Animal subtype. The simplest way is to use a wildcard—added to the Java language explicitly for this reason.

image with no caption

So now you’re wondering, “What’s the difference? Don’t you have the same problem as before? The method above isn’t doing anything dangerous—calling a method any Animal subtype is guaranteed to have—but can’t someone still change this to add a Cat to the animals list, even though it’s really an ArrayList<Dog>? And since it’s not checked again at runtime, how is this any different from declaring it without the wildcard?”

And you’d be right for wondering. The answer is NO. When you use the wildcard <?> in your declaration, the compiler won’t let you do anything that adds to the list!


  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint