The Department of Computer Science & Engineering
cse@buffalo
STUART C. SHAPIRO: CSE 116 B

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


Introduction to Collections

Reading
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).

Sets
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.

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

Sequences
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");

print(s2);
print(sb2);

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 <shapiro@cse.buffalo.edu>