It has been a few years since programming in Java, so I decided to consult an old, reliable source. In "Introduction to Java Programming" by Liang, pg. 798, an ArrayList
is scheduled like so:
Collection<String> collection = new ArrayList<String>();
The author then goes about using (only) the add()
method and creates an uses an Iterator
of collection
.
Now, I like using a generic class declaration whenever possible (coming from, now, a C and C++ background) because if I change my mind about the type I want to use for some solution, I can change just one line of code. Ideally, I would be able to declare a Collection<some_type> my_collection
(whether a member or local variable), and later define it to be any type which extends the Collection
class.
But, when I try to do the following,
Collection<String> my_collection;
and then later,
my_collection = ArrayList<String>();
I get compilation errors: namely, the compiler cannot find the get()
and remove()
symbols (or at least not the versions of the overloaded methods that I believe I am calling). For example,
[...].java:48: error: incompatible types: boolean cannot be converted to Process
otherAlg.addJob(wait_queue.remove(0));
^
NOTE: the type Process is "fully-vetted" and is not the issue here.
Also,
[...].java:72: error: cannot find symbol
return wait_queue.get(0);
^
Sure: I can "fix" the issue by declaring whatever type I am going to initialize in the first place, but what is the deal? Why the inconsistency between what Liang states and what I would assume to be possible, and what is actually practical (at least as far as my compiler is concerned)?