Cover by Jennifer Greene, Andrew Stellman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

O'Reilly logo

Chapter 8. Enums and Collections; Storing lots of data

image with no caption

When it rains, it pours.

In the real world, you don’t get to handle your data in tiny little bits and pieces. No, your data’s going to come at you in loads, piles, and bunches. You’ll need some pretty powerful tools to organize all of it, and that’s where collections come in. They let you store, sort, and manage all the data that your programs need to pore through. That way, you can think about writing programs to work with your data, and let the collections worry about keeping track of it for you.

Strings don’t always work for storing categories of data

Suppose you have several worker bees, all represented by Worker classes. How would you write a constructor that took a job as a parameter? If you use a string for the job name, you might end up with code that looks like this:

image with no caption

You could probably add code to the Worker constructor to check each string and make sure it’s a valid bee job. However, if you add new jobs that bees can do, you’ve got to change this code and recompile the Worker class. That’s a pretty short-sighted solution. What if you have other classes that need to check for the types of worker bees they can be? Now you’ve got to duplicate code, and that’s a bad path to go down.

What we need is a way to say, “Hey, there are ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required