| Shape toys! |
Remember these toys? I'm easily entertained. I played with these for hours. I still do. Just kidding....but seriously.
These are the exact same idea as java generics. Generics are
like taking an opened topped box and putting one of these on top. Kinda like a shape filter. Without the filter, you don't know what's in the box. It could be practically anything. Snakes, birds, squares, stars. With the shape filter, you know that the only things in the box are things that fit through the shapes.
like taking an opened topped box and putting one of these on top. Kinda like a shape filter. Without the filter, you don't know what's in the box. It could be practically anything. Snakes, birds, squares, stars. With the shape filter, you know that the only things in the box are things that fit through the shapes.
Here is an example of using ArrayList without generics:
See the issue? You've got a String, an Integer, and an Object all in the same array. No way to know what you're about to get out.
Here's an example using generics to specify that the ArrayList will only hold Strings.
It's as simple as that! Running the above program with this change creates a compiler error because of the lines
Why should you care?
This may seem inconvenient in some ways because it limits what can be inside of your array, but this is much, much safer. Especially in situations where you might be getting an ArrayList back from a function you didn't write. Think about a function with this header:
Looking at this method, there's no way to tell if the employee numbers being returned as Strings, ints, Integers or anything else. But if the method header is
Right away you know what you're dealing with. Moral of the story: Use a shape filter, and you won't get bitten by a snake.
No comments:
Post a Comment