[ Pobierz całość w formacie PDF ]
.import java.util.*;public class Queue {private LinkedList list = new LinkedList();public void put(Object v) { list.addFirst(v); }public Object get() {return list.removeLast();}public boolean isEmpty() {return list.isEmpty();}public static void main(String[] args) {Queue queue = new Queue();for(int i = 0; i < 10; i++)queue.put(Integer.toString(i));while(!queue.isEmpty())System.out.println(queue.get());}} ///:~You can also easily create a deque(double-ended queue) from a LinkedList.This is like a queue, but you canadd and remove elements from either end.[ Add Comment ]Set functionalitySet has exactly the same interfaceas Collection, so there isn’t any extra functionality like there iswith the two different Lists.Instead, the Set is exactly aCollection, it just has different behavior.(This is the ideal use ofinheritance and polymorphism: to express different behavior.) A Setrefuses to hold more than one instance of each object value (what constitutesthe “value” of an object is more complex, as you shall see).Set (interface)Each element that you add to theSet must be unique; otherwise the Set doesn’t add theduplicate element.Objects added to a Set must defineequals( ) to establish object uniqueness.Set has exactly thesame interface as Collection.The Set interface does not guaranteeit will maintain its elements in any particular order.HashSet*For Sets where fast lookup time isimportant.Objects must also definehashCode( ).TreeSetAn ordered Set backed by a tree.This way, you can extract an ordered sequence from aSet.The following example does notshow everything you can do with a Set, since the interface is the same asCollection, and so was exercised in the previous example.Instead, thisdemonstrates the behavior that makes a Set unique://: c09:Set1.java// Things you can do with Sets.import java.util.*;import com.bruceeckel.util.*;public class Set1 {static Collections2.StringGenerator gen =Collections2.countries;public static void testVisual(Set a) {Collections2.fill(a, gen.reset(), 10);Collections2.fill(a, gen.reset(), 10);Collections2.fill(a, gen.reset(), 10);System.out.println(a); // No duplicates!// Add another set to this one:a.addAll(a);a.add("one");a.add("one");a.add("one");System.out.println(a);// Look something up:System.out.println("a.contains(\"one\"): " +a.contains("one"));}public static void main(String[] args) {System.out.println("HashSet");testVisual(new HashSet());System.out.println("TreeSet");testVisual(new TreeSet());}} ///:~Duplicate values are added to theSet, but when it is printed you’ll see the Set has acceptedonly one instance of each value.[ Add Comment ]When you run this program you’llnotice that the order maintained by the HashSet is different fromTreeSet, since each has a different way of storing elements so they canbe located later.(TreeSet keeps them sorted, while HashSet uses ahashing function, which is designed specifically for rapid lookups.) Whencreating your own types, be aware that a Set needs a way to maintain astorage order, which means you must implement the Comparable interfaceand define the compareTo( ) method.Here’s anexample://: c09:Set2.java// Putting your own type in a Set.import java.util.*;class MyType implements Comparable {private int i;public MyType(int n) { i = n; }public boolean equals(Object o) {return(o instanceof MyType)&& (i == ((MyType)o).i);}public int hashCode() { return i; }public String toString() { return i + " "; }public int compareTo(Object o) {int i2 = ((MyType)o).i;return (i2 < i ? -1 : (i2 == i ? 0 : 1));}}public class Set2 {public static Set fill(Set a, int size) {for(int i = 0; i < size; i++)a.add(new MyType(i));return a;}public static void test(Set a) {fill(a, 10);fill(a, 10); // Try to add duplicatesfill(a, 10);a.addAll(fill(new TreeSet(), 10));System.out.println(a);}public static void main(String[] args) {test(new HashSet());test(new TreeSet());}} ///:~Theform for the definitions for equals( ) andhashCode( ) will be described later in this chapter.You must definean equals( ) in both cases, but the hashCode( ) isabsolutely necessary only if the class will be placed in a HashSet (whichis likely, since that should generally be your first choice as a Setimplementation).However, as a programming style you should always overridehashCode( ) when you override equals( ).This processwill be fully detailed later in this chapter.[ Add Comment ]In the compareTo( ), notethat I did not use the “simple and obvious” form returni-i2.Although this is a common programming error, it would only workproperly if i and i2 were “unsigned” ints (ifJava had an “unsigned” keyword, which it does not)
[ Pobierz całość w formacie PDF ]