October 2, 2014
Hot Topics:
RSS RSS feed Download our iPhone app

Objects and Collections: ArrayLists

  • September 11, 2006
  • By Matt Weisfeld
  • Send Email »
  • More Articles »

Compile-Time vs. Run-Time

In Listing 4, you saw that the compiler actually issues an error when the code attempted to add an integer to an ArrayList that had a generic specification of a String. The major benefit here was that the compiler caught this and not the run-time environment. Why is this such a major advantage to software developers? Consider the code in Listing 5.

Listing 5: TestArrayList.java

import java.util.ArrayList;
import java.util.Iterator;

class TestArrayList{

   public static void main(String[] args){

      ArrayList myList = new ArrayList();

      myList.add("One");
      myList.add("Two");

      myList.add(3);

      Iterator i = myList.iterator();
      while (i.hasNext()) {
         System.out.println( (String) i.next());
      }
   }
}

In this example, the generic specification has been eliminated; however, you are using a cast to insure that only Strings are printed.

System.out.println( (String) i.next());

When you compile this code, you get the expected warnings.


C:\column26>"C:\Program Files\Java\jdk1.5.0_06\bin\javac"
   -Xlint -classpath . TestArrayList.java
TestArrayList.java:10: warning: [unchecked] unchecked call to
   add(E) as a member of the raw type java.util.ArrayList
   myList.add("One");
        ^
TestArrayList.java:11: warning: [unchecked] unchecked call to
   add(E) as a member of the raw type java.util.ArrayList
   myList.add("Two");
        ^
TestArrayList.java:13: warning: [unchecked] unchecked call to
   add(E) as a member of the raw type java.util.ArrayList
   myList.add(3);
        ^
3 warnings
C:\column26>

The key term here is warnings. They are not errors, thus, the compiler completes and the application can now be executed. However, when you do execute this code, you have a problem, as seen below.


C:\column26>"C:\Program Files\Java\jdk1.5.0_06\bin\java"
   -classpath . TestArrayList
One
Two
Exception in thread "main" java.lang.ClassCastException:
   java.lang.Integer at TestArrayList.main(TestArrayList.java:17)
C:\column26>

Rather than receiving a compiler error, and then having to fix it before the application is released, you now have a program crash. Instead of the problem being dealt with early in the development cycle, you now have a serious problem that actual users have to deal with. Crashes occurring after release of an application are infinitely more expensive than attending to these problems prior to the release. Designing code to catch potential problems early is one of the basic tenets of Object-Oriented development. In this case, the development system itself, Java SE 1.5, now has the infrastructure in place to enforce certain type checking.

Iterator vs. Foreach

You have already used the Iterator interface in Listing 2. However, the SDK now provides yet another way to work your way through a List—the Foreach statement.

Note: Even though this statement does not actually use the keyword Foreach (actually the keyword for is used), it is called the Foreach statement to fall in line with similar statements in other languages).

The syntax for the Foreach statement is as follows:

for (String d : myList)
   System.out.println(d);
}

The design of the Foreach is intended to make it a lot easier to use than the Iterator. It is interesting to note that the Iterator itself was an improvement over an earlier technique called an Enumerator.

Listing 6 walks through the list using both an Iterator and a Foreach statement.

Listing 6: TestArrayList.java

import java.util.ArrayList;
import java.util.Iterator;

class TestArrayList{

   public static void main(String[] args){

      ArrayList<String> myList = new ArrayList<String>();

      myList.add("One");
      myList.add("Two");

      System.out.println("Using an iterator");

      Iterator i = myList.iterator();
      while (i.hasNext()) {
         System.out.println(i.next());
      }
      System.out.println("\nUsing Foreach");

      for (String: myList) {
         System.out.println(pos);
      }
   }
}

When you execute this program, you can see that the output is identical.


C:\column26>"C:\Program Files\Java\jdk1.5.0_07\bin\java"
   -classpath . TestArrayList

Using an iterator
One
Two

Using Foreach
One
Two
C:\column26>

The colors identifying parts of the following code fragment will help in understanding the syntax of the Foreach statement. In this case, the generic is <String> and the name of the list is myList. The use of the identifiers must be consistent.

ArrayList<String> myList = new ArrayList<String>();

for (String i : myList) {
   System.out.println(i);
}

It is expected that the use of Iterators will diminish as Java SE 1.5 gains widespread use. However, just as with the discussion on Vectors in the previous article, developers still need to understand the use of Iterators because Iterators will be encountered in code wriiten prior to the adoption of the Foreach statement.

More ArrayList Methods

Now that you have looked at some of the more interesting aspects of using an ArrayList, you can explore some of the other syntax for an ArrayList. For the most part, the design decisions made when using ArrayLists are similar to those of a Vector.

You have seen that, once the ArrayList has been created, you can walk though the list with a Foreach statement and process all the elements in the list. However, you also can update specific locations within the list by using the set() method as seen in listing 7. Note that, when this application is run, four distinct items are added to the myList collection. The set() method then is used to update the element at location 1, replacing the string "One" by "1".

myList.set(1,"1");

The first parameter specifies the location in the list and the second parameter contains the actual value that the element will be set to. Be careful not to confuse the number '1', which represents the location of the ArrayList, and the parameter "1", which represents a string argument. The similarity is intentional to make you think about what the arguments actually are.

Listing 7: TestArrayList.java

import java.util.ArrayList;
import java.util.Iterator;

class TestArrayList{

   public static void main(String[] args){

      ArrayList<String> myList = new ArrayList<String>();

      myList.add("Zero");
      myList.add("One");
      myList.add("Two");
      myList.add("Three");

      System.out.println("\nInitial List");

      for (String pos : myList) {
         System.out.println(pos);
      }

      myList.set(1,"1");

      System.out.println("\nUpdated List");

      for (String pos : myList) {
         System.out.println(pos);
      }
   }
}

When you execute this program, you can see that the element in location 1 of myList has been successfully updated.


C:\column26>"C:\Program Files\Java\jdk1.5.0_07\bin\java"
   -classpath . TestArrayList

Initial List
Zero
One
Two
Three

Updated List
Zero
1
Two
Three
C:\column26>




Page 2 of 3



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Sitemap | Contact Us

Rocket Fuel