Java Reference
In-Depth Information
As you can observe, when you want to fetch an item from the list and assign it to a variable, this
variable must be declared as an Object . Even though you know that your first element belongs to
the Dog class, you will be unable to execute the following code:
//...
Object item = aList.get(0); // Get first item
item.bark();
Java will complain about the fact that there is no bark() method for the Object class. Is there a way
to specify that the item you retrieved is really of the class Dog ? The answer is yes, using type casting,
as mentioned in Chapter 2:
//...
Dog item = (Dog) aList.get(0); // Get first item and type cast it
item.bark();
Keep in mind, however, that type casting is generally an unsafe operation and should be avoided.
As such, it's best to keep your collections as specific as possible, and use multiple collections to hold
different items whenever necessary. Finally, in case you were wondering, it's also possible to define
your own classes using generics in Java, but this is a more advanced aspect of programming in Java I
will not cover in full.
autoBoxing once again
In the beginning of this chapter, you read about the concept of Autoboxing, which
is an automatic conversion made by the Java compiler between primitive types and
their corresponding wrapper classes. For example, converting a double to a Double
is called boxing, and converting a Double back to a double is called unboxing.
Back then, I stated that there was one typical use case where you should know
about autoboxing, and now—as I've discussed collections and generics—is the time
to mention this. Generics in Java are always provided as classes. This means that
primitive types cannot be used as generic types and you cannot declare a list as
follows:
ArrayList<int> aList = new ArrayList<int>();
Luckily, using the mechanism of autoboxing, you can just replace the primitive type
with its wrapper class, Integer , like so:
ArrayList<Integer> aList = new ArrayList<Integer>();
Other than keeping this in mind, you do not have to worry about the differences
between int —the primitive type—and Integer —its wrapper class, as Java will
handle all the rest for you. What about an array of integers? Then you just write:
ArrayList<int[]> aList = new ArrayList<int[]>();
continues
 
Search WWH ::




Custom Search