Main Content

Type checking, Java arrays and collections

Archive - Originally posted on "The Horse's Mouth" - 2010-04-23 10:33:37 - Graham Ellis

Java's arrays are "typed" - you declare them to contain a particular type of primitive, or a particular type of object (which also enables them to contain any object type which is extended from that declared type).

But, when you go beyond arrays and use the more flexible utility classes such as ArrayLists, Vectors, HashTables, etc, you are declaring a container that can hold any sort of object. So:
  ArrayList Allwords = new ArrayList();
and you "worry" the Java Compiler:
  [trainee@easterton cj]$ javac Utildemo.java
  Note: Utildemo.java uses unchecked or unsafe operations.
  Note: Recompile with -Xlint:unchecked for details.
  [trainee@easterton cj]$


You probably won't want to have this warning message crop up on every future compile (and, let's face it, Java is a real "maiden aunt" of a language when it comes to checking), so let's add in a request to make the checks in the declaration:
  ArrayList<String> Allwords = new ArrayList<String>();