Pages

Aug 21, 2012

Collections and Generics




Overriding hashCode() and equals() (Objective 6.2)
  1. equals(), hashCode(), and toString() are public.
  2. Override toString() so that System.out.println() or other
  3. methods can see something useful, like your object's state.
  4. Use == to determine if two reference variables refer to the same object.
  5. Use equals() to determine if two objects are meaningfully equivalent.
  6. If you don't override equals(), your objects won't be useful hashing keys.
  7. If you don't override equals(), different objects can't be considered equal.
  8. Strings and wrappers override equals() and make good hashing keys.
  9. When overriding equals(), use the instanceof operator to be sure you're evaluating an appropriate class.
  10. When overriding equals(), compare the objects' significant attributes.
  11. Highlights of the equals() contract:
    1. Reflexive: x.equals(x) is true.
    2. Symmetric: If x.equals(y) is true, then y.equals(x) must be true.
    3. Transitive: If x.equals(y) is true, and y.equals(z) is true,
    4. then z.equals(x) is true.
    5. Consistent: Multiple calls to x.equals(y) will return the same result.
    6. Null: If x is not null, then x.equals(null) is false.
  12. If x.equals(y) is true, then x.hashCode() == y.hashCode() is true.
  13. If you override equals(), override hashCode().
  14. HashMap, HashSet, Hashtable, LinkedHashMap, & LinkedHashSet use hashing.
  15. An appropriate hashCode() override sticks to the hashCode() contract.
  16. An efficient hashCode() override distributes keys evenly across its buckets.
  17. An overridden equals() must be at least as precise as its hashCode() mate.
  18. To reiterate: if two objects are equal, their hashcodes must be equal.
  19. It's legal for a hashCode() method to return the same value for all instances (although in practice it's very inefficient).
  20. Highlights of the hashCode() contract:
    1. Consistent: multiple calls to x.hashCode() return the same integer.
    2. If x.equals(y) is true, x.hashCode() == y.hashCode() is true.
    3. If x.equals(y) is false, then x.hashCode() == y.hashCode() can be either true or false, but false will tend to create better efficiency.
  21. transient variables aren't appropriate for equals() and hashCode().
Collections (Objective 6.1)
  1. Common collection activities include adding objects, removing objects, verifying object inclusion, retrieving objects, and iterating.
  2. Three meanings for "collection":
    1. collection Represents the data structure in which objects are stored 
    2. Collection java.util interface from which Set and List extend
    3. Collections A class that holds static collection utility methods
  3. Four basic flavors of collections include Lists, Sets, Maps, Queues:
    1. Lists of things Ordered, duplicates allowed, with an index.
    2. Sets of things May or may not be ordered and/or sorted; duplicates not allowed.
    3. Maps of things with keys May or may not be ordered and/or sorted; duplicate keys are not allowed.
    4. Queues of things to process Ordered by FIFO or by priority.
  4. Four basic sub-flavors of collections Sorted, Unsorted, Ordered, Unordered.
    1. Ordered Iterating through a collection in a specific, non-random order.
    2. Sorted Iterating through a collection in a sorted order.
  5. Sorting can be alphabetic, numeric, or programmer-defined.

Key Attributes of Common Collection Classes (Objective 6.1)
  1. ArrayList: Fast iteration and fast random access.
  2. Vector: It's like a slower ArrayList, but it has synchronized methods.
  3. LinkedList: Good for adding elements to the ends, i.e., stacks and queues.
  4. HashSet: Fast access, assures no duplicates, provides no ordering.
  5. LinkedHashSet: No duplicates; iterates by insertion order.
  6. TreeSet: No duplicates; iterates in sorted order.
  7. HashMap: Fastest updates (key/values); allows one null key, many null values.
  8. Hashtable: Like a slower HashMap (as with Vector, due to its synchronized methods). No null values or null keys allowed.
  9. LinkedHashMap: Faster iterations; iterates by insertion order or last accessed; allows one null key, many null values.
  10. TreeMap: A sorted map.
  11. PriorityQueue: A to-do list ordered by the elements' priority.

Using Collection Classes (Objective 6.3)
  1. Collections hold only Objects, but primitives can be autoboxed.
  2. Iterate with the enhanced for, or with an Iterator via hasNext() & next().
  3. hasNext() determines if more elements exist; the Iterator does NOT move.
  4. next() returns the next element AND moves the Iterator forward.
  5. To work correctly, a Map's keys must override equals() and hashCode().
  6. Queues use offer() to add an element, poll() to remove the head of the queue, and peek() to look at the head of a queue.
  7. As of Java 6 TreeSets and TreeMaps have new navigation methods like floor() and higher().
  8. You can create/extend "backed" sub-copies of TreeSets and TreeMaps.

Sorting and Searching Arrays and Lists (Objective 6.5)
  1. Sorting can be in natural order, or via a Comparable or many Comparators.
  2. Implement Comparable using compareTo(); provides only one sort order.
  3. Create many Comparators to sort a class many ways; implement compare().
  4. To be sorted and searched, a List's elements must be comparable.
  5. To be searched, an array or List must first be sorted.

Utility Classes: Collections and Arrays (Objective 6.5)
  1. Both of these java.util classes provide
    1. A sort() method. Sort using a Comparator or sort using natural order.
    2. A binarySearch() method. Search a pre-sorted array or List
    3. Arrays.asList() creates a List from an array and links them together.
    4. Collections.reverse() reverses the order of elements in a List.
    5. Collections.reverseOrder() returns a Comparator that sorts in reverse.
    6. Lists and Sets have a toArray() method to create arrays.

Generics (Objective 6.4)
  1. Generics let you enforce compile-time type safety on Collections (or other classes and methods declared using generic type parameters).
  2. An ArrayList<Animal> can accept references of type Dog, Cat, or any other subtype of Animal (subclass, or if Animal is an interface, implementation).
  3. When using generic collections, a cast is not needed to get (declared type) elements out of the collection. With non-generic collections, a cast is required:
    List<String> gList = new ArrayList<String>();
    List list = new ArrayList();
    // more code
    String s = gList.get(0); // no cast needed
    String s = (String)list.get(0); // cast required
  4. You can pass a generic collection into a method that takes a non-generic collection, but the results may be disastrous. The compiler can't stop the method from inserting the wrong type into the previously type safe collection.
  5. If the compiler can recognize that non-type-safe code is potentially endangering something you originally declared as type-safe, you will get a compiler warning. For instance, if you pass a List<String> into a method declared as
     void foo(List aList) { aList.add(anInteger); }
    You'll get a warning because add() is potentially "unsafe".
  6. "Compiles without error" is not the same as "compiles without warnings." A compilation warning is not considered a compilation error or failure.
  7. Generic type information does not exist at runtime—it is for compile-time safety only. Mixing generics with legacy code can create compiled code that may throw an exception at runtime.
  8. Polymorphic assignments applies only to the base type, not the generic type parameter. You can say
    List<Animal> aList = new ArrayList<Animal>(); // yes
    You can't say
    List<Animal> aList = new ArrayList<Dog>(); // no
  9. The polymorphic assignment rule applies everywhere an assignment can be made. The following are NOT allowed:
    void foo(List<Animal> aList) { } // cannot take a List<Dog>
    List<Animal> bar() { } // cannot return a List<Dog>
  10. Wildcard syntax allows a generic method, accept subtypes (or supertypes) of the declared type of the method argument:
    void addD(List<Dog> d) {} // can take only <Dog>
    void addD(List<? extends Dog>) {} // take a <Dog> or <Beagle>
  11. The wildcard keyword extends is used to mean either "extends" or "implements." So in <? extends Dog>, Dog can be a class or an interface.
  12. When using a wildcard, List<? extends Dog>, the collection can be accessed but not modified.
  13. When using a wildcard, List<?>, any generic type can be assigned to the reference, but for access only, no modifications.
  14. List<Object> refers only to a List<Object>, while List<?> or List<? extends Object> can hold any type of object, but for access only.
  15. Declaration conventions for generics use T for type and E for element:
    public interface List<E> // API declaration for List
    boolean add(E o) // List.add() declaration
  16. The generics type identifier can be used in class, method, and variable declarations:
    class Foo<t> { } // a class
    T anInstance; // an instance variable
    Foo(T aRef) {} // a constructor argument
    void bar(T aRef) {} // a method argument
    T baz() {} // a return type
  17. The compiler will substitute the actual type.
  18. You can use more than one parameterized type in a declaration:

    public class UseTwo<T, X> { }
  19. You can declare a generic method using a type not defined in the class:

    public <T> void makeList(T t) { }

    is NOT using T as the return type. This method has a void return type, but to use T within the method's argument you must declare the <T>, which happens before the return type.

regards,
TechDexters Support Team
Hyderabad.


for Feedback and Support simply drop a mail in
techdexters{at}gmail.com
Remember to replace the {at} with @ in the email addresses

2 comments:

  1. Thanks to the team. Pretty good post. But it is much appreciated if you can avoid plagiarised content from other websites .

    http://my.safaribooksonline.com/book/certification/scjp/9780071591065/generics-and-collections/ch07lev1sec1

    We wait for good articles exclusively written by you . I hope this blog should not be a one of millions of blogs containing copied text from other websites. It should be unique.

    Hope you can take it as a suggestion .

    ReplyDelete
    Replies
    1. Thanks for the Suggestion, We already mentioned in references in
      http://techdexters.blogspot.in/2012/07/ocpj-exam-objectives-and-training.html
      that we are also using other sources of information.

      But your point is well taken and we are going to change the way in which our future posts are made. Hope your support and suggestions will continue

      regards,
      TechDexters Support Team
      Hyderabad.

      Delete