CIS 35A: Introduction to Java Programming

Home | Green Sheet | Lectures | Assignments | FAQ | Grades

Collections

Collections and Generics
Java collections
Comparison of arrays and collections

How arrays and collections are similar

  • Like an array, a collection is an object that can store multiple occurrences of other objects.
  • Some collection types (such as ArrayList) use arrays internally to store data.
  • An array is a Java language feature. Collections are classes in the Java API.
  • Collection classes have methods that perform operations that arrays don't provide.
  • Arrays are fixed in size. Collections are variable in size.
  • Arrays can store primitive types. Collections can't.
  • Indexes are almost always required to process arrays. Collections are usually processed without using indexes.

Code that uses an array

String[] codes = new String[3];
codes[0] = "mcb2";
codes[1] = "java";
codes[2] = "jsps";
for (int i = 0; i < codes.length; i++)
    System.out.println(codes[i]);

Code that uses a collection

ArrayList<String> codes = new ArrayList<String>();
codes.add("mcb2");
codes.add("java");
codes.add("jsps");
for (String s : codes)
    System.out.println(s);
Previous | Comparison of arrays and collections | Java collection framework | Collection classes | Generics | Homogeneous list | Next