10
Collections Chapter 12

Chapter 12

Embed Size (px)

DESCRIPTION

 

Citation preview

Page 1: Chapter 12

Collections

Chapter 12

Page 2: Chapter 12

12Java Collection

FrameworksThe Java collection framework is a set of utility classes and interfaces.

Designed for working with collections of objects

A collection is a group of objects, each of which is known as an element in the collection.

Page 3: Chapter 12

12

Types of CollectionsSimple Collections

Sets have no duplicate elements.

Lists are ordered collections that can have duplicate elements.

MapsMap uses key/value pairs to associate an object (the value) with a key.

Both sets and maps can be sorted or unsorted.

Page 4: Chapter 12

12

The Collection InterfaceRoot interface of collection classes

Common methods defined in Collection:

add()

contains()

isEmpty()

iterator()

remove()

size()

Page 5: Chapter 12

12

The ArrayListArrayList is a concrete implementation of the List interface.

A concrete implementation is a class that can be instantiated.

Page 6: Chapter 12

12

ArrayList vs. an ArrayAn ArrayList has several advantages:

Can be resized dynamically as more objects are added

Elements can be removed from an ArrayList

Simpler to use than an array

Page 7: Chapter 12

12

Controlling ArrayList sizeImportant methods:

size() returns the number of elements

ensureCapacity() sets the capacity of the ArrayList to a certain number of elements

trimToSize() trims an ArrayList to only the number of elements it currently holds to reduce memory requirements

Page 8: Chapter 12

12

Using CollectionsAlthough objects in a collection do not have to be of the same type:

It is not good practice to mix object types in a collection.

You must check object type and cast to appropriate class if heterogeneous collections are used.

Page 9: Chapter 12

12Adding Elements to a

Collectionadd() method is overloaded

myList.add(myObject) adds myObject to end of collection

myList.add(3, myObject) inserts myObject at offset 3 in a collection

Page 10: Chapter 12

12Replacing and Removing

ElementsTo replace and remove elements in an ArrayList:set() method replaces an element at a specified position

remove() method removes an element at a specified position