Java Reference
In-Depth Information
«interface»
java.lang.Iterable<E>
+
iterator(): Iterator<E>
Returns an iterator for the elements in this collection.
«interface»
java.util.Collection<E>
+
add(o: E): boolean
+
addAll(c: Collection<? extends E>): boolean
+
clear(): void
+
contains(o: Object): boolean
+
containsAll(c: Collection<?>): boolean
+
equals(o: Object): boolean
+
hashCode(): int
+
isEmpty(): boolean
+
remove(o: Object): boolean
+
removeAll(c: Collection<?>): boolean
+
retainAll(c: Collection<?>): boolean
+
size(): int
+
toArray(): Object[]
Adds a new element
o
to this collection.
Adds all the elements in the collection
c
to this collection.
Removes all the elements from this collection.
Returns true if this collection contains the element
o
.
Returns true if this collection contains all the elements in
c
.
Returns true if this collection is equal to another collection
o
.
Returns the hash code for this collection.
Returns true if this collection contains no elements.
Removes the element
o
from this collection.
Removes all the elements in
c
from this collection.
Retains the elements that are both in
c
and in this collection.
Returns the number of elements in this collection.
Returns an array of
Object
for the elements in this collection.
«interface»
java.util.Iterator<E>
+
hasNext(): boolean
+
next(): E
+
remove(): void
Returns true if this iterator has more elements to traverse.
Returns the next element from this iterator.
Removes the last element obtained using the next method.
F
IGURE
20.2
The
Collection
interface contains the methods for manipulating the elements in a collection, and you
can obtain an iterator object for traversing elements in the collection.
.UnsupportedOperationException
, a subclass of
RuntimeException
.
This is a good design that you can use in your project. If a method has no meaning in
the subclass, you can implement it as follows:
unsupported operations
public void
someMethod() {
throw new
UnsupportedOperationException
(
"Method not supported"
);
}
Listing 20.1 gives an example to use the methods defined in the
Collection
interface.
L
ISTING
20.1
TestCollection.java
1
import
java.util.*;
2
3
public class
TestCollection {
4
public static void
main(String[] args) {
5 ArrayList<String> collection1 =
new
ArrayList<>();
6 collection1.add(
"New York"
);
7 collection1.add(
"Atlanta"
);
8 collection1.add(
"Dallas"
);
9 collection1.add(
"Madison"
);
create an array list
add elements
Search WWH ::
Custom Search