The Department of Computer Science & Engineering

CSE 116
Introduction To Computer Science for Majors 2
Lecture B
Lecture Notes
Stuart C. Shapiro
Spring, 2003

Introduction to Collections

Riley, Chapter 2

Generic Collections
"A collection represents a group of objects, known as its elements." [Sun's Collection API doc]. See that doc for a description of the Collection ADT (Abstract Data Type).

HashSet is the implementation of a minimal set.

Try adding something twice and removing it once. Is it there?

Note: BeanShell, but not compiler, allows HashSets of primitive values.

Like sets, but an element can be in a bag some number of times.
See CharBag code and documentation.

Like bags, but the elements are ordered.
StringBuffers are sequences of chars most similar to HashSets of chars and to CharBags.

Mutable and Immutable Objects
Mutable objects can be modified.
Immutable objects cannot be modified, but a method can return an object just like this except for some small change.

For example Strings are immutable sequences of chars, while StringBuffers are mutable sequences of chars.
Compare String's concat(String str) to StringBuffer's append(String str), by trying in the BeanShell

s1 = new String("Original");
sb1 = new StringBuffer("Original");

s2 = s1;
sb2 = sb1;

s1 = s1.concat(" and modified");
sb1 = sb1.append(" and modified");


Mutators need not return this, but if they do, they can be composed (see text, page 68).
Mutable objects avoid creating extra objects.
Mutators may cause a variable to "change", even though it has not been referenced. (See sb2 above.)

First Previous Next

Copyright © 2003 by Stuart C. Shapiro. All rights reserved.

Stuart C. Shapiro <>