Java Reference
In-Depth Information
The for-each loop executes only once because the 200 was popped off the top of the
stack, leaving only 100 . The output of the previous statements is
100
Use the Stack class for situations that require LIFO behavior.
Use lists when you work with ordered collections where duplicates are allowed and you
need control over where the items appear in the collection. If duplicates are not allowed, a
set might be more appropriate for your needs, as discussed in the next section.
Sets
The Collections Framework has several implementations of the Set interface, including
HashSet , LinkedHashSet , and TreeSet . Use a Set object when duplicates are not allowed in
your collection. The equals method is used to determine if elements are duplicated. All the
Set classes use generics. For example, the HashSet class is declared as
public class HashSet<E> extends AbstractSet<E>
implements Set<E>, Cloneable, Serializable
The E is a generic type that represents the data type of the elements that can be stored in
the HashSet .
To demonstrate using sets, suppose we have the following class called Product to
represent a product for sale. According to the equals method, two Product objects are
equal if they have the same id .
public class Product {
String description;
double price;
int id;
public Product(String d, double p, int i) {
description = d;
price = p;
id = i;
}
public boolean equals(Object obj) {
if(!(obj instanceof Product)) {
return false;
}
Search WWH ::




Custom Search