• A collection is an object that groups multiple elements into a single unit.. • Very useful.[r]
Trang 14/7/2018 http://sites.google.com/site/tranlectures 1
CÔNG NGHỆ JAVA
CH13 JAVA COLLECTIONS
Quang Dieu Tran PhD.
http://sites.google.com/site/tranlectures
Trang 2Readings and References
• References
– "Collections", Java tutorial
Trang 3Java 2 Collections
• A collection is an object that groups multiple
elements into a single unit
• Very useful
– store, retrieve and manipulate data
– data structures and methods written by hotshots in the field
• Joshua Bloch, who also wrote the Collections tutorial
Trang 4Collections Framework
• Unified architecture for representing and
manipulating collections
• A collections framework contains three things
– Interfaces
Trang 5Collections Framework Diagram
•Interfaces, Implementations, and Algorithms
•From Thinking in Java, page 462
Trang 6Collection Interface
• Defines fundamental methods
– int size();
– boolean isEmpty();
– boolean contains(Object element);
– boolean add(Object element); // Optional
– boolean remove(Object element); // Optional
– Iterator iterator();
• These methods are enough to define the basic
behavior of a collection
• Provides an Iterator to step through the elements in the Collection
Trang 7Iterator Interface
• Defines three fundamental methods
– Object next()
– boolean hasNext()
– void remove()
• These three methods provide access to the
contents of the collection
• An Iterator knows position within collection
• Each call to next() “reads” an element from the
collection
– Then you can use it or remove it
Trang 8Iterator Position
Trang 9Example - SimpleCollection
public class SimpleCollection {
public static void main(String[] args) {
Collection c;
c = new ArrayList();
System.out.println(c.getClass().getName());
for (int i=1; i <= 10; i++) {
c.add(i + " * " + i + " = "+i*i);
} Iterator iter = c.iterator();
while (iter.hasNext())
System.out.println(iter.next());
}
}
Trang 10List Interface Context
Collection
List