Search⌘ K

The Data Collection Bag

Explore the concept of an array-based bag in Java, an abstract collection that holds objects without ordering or duplicate restrictions. Understand its key behaviors such as adding, removing, and counting items. Learn how to design this data structure using CRC cards to represent class responsibilities and collaborations.

We'll cover the following...

The bag

Imagine a paper bag, a reusable cloth bag, or even a plastic bag. People use bags when they shop, pack lunch, or eat potato chips. Bags contain things. In everyday language, a bag is a kind of container. In Java, however, a container is an object whose class extends the standard class Container. Such containers are used in graphics programs. Rather than being considered a container, a bag in Java is a kind of collection.

What distinguishes a bag from other collections? A bag doesn’t do much more than contain its items. It doesn’t order them in a particular way, nor does it prevent duplicate items. Most of its behaviors are simple and could be performed by other kinds of collections.

While describing the behaviors that we want for the bag we’ll design in this chapter, let’s keep in mind that we are specifying a programming abstraction inspired by ...