Friday, April 12, 2013

Java Collections



Java.util

Collections can store only objects in Java. Primitive types can not be added to a collection, so it is necessary to use the wrapper classes such as Integer and Double instead of primitives.

There are three elements that make up collections.
·        Interfaces  define the methods that each type of collection must implement
·        Implementations  actual classes such as Hashtable and Vector
·        Algorithms  methods that store, retrieve, and manipulate elements in a collection

There are four properties that collections may or may not possess, as shown in Table. These are the properties you must know to differentiate collection types.

Property

Description

Sorted
Ascending order, sorted naturally using the equals() object method. An example is a Membership list.
Ordered/Unordered
Collection keeps an order determined by where the object is placed in the collection. For example, a deck of cards is ordered.
Allows duplicates
Duplicate objects can be added to the collection. An example is a collection of hockey cards.
Uses keys
A key object is used to reference the stored object. For example, names of people are stored by social insurance number.


Collection Interfaces and Classes
The interfaces in the collections framework are the foundation of collections. By using these interfaces, collections can be passed into other methods regardless of the details of a particular collection.
There are six interfaces that make up the core collections framework. Some of these interfaces extend other interfaces to form a hierarchy
                             

Notice Map and SortedMap do not extend the Collection interface. Map and SortedMap are still known as collections, even though in strict Java terms they are not Collection types.








Each of the interfaces also has an abstract class that has some of the methods already programmed. For example, the Collection interface has a class called AbstractCollection, and the Set interface has a class called AbstractSet.







We will now examine the interfaces individually.

Iterator methods

A simple explanation of an iterator is an object that contains methods that allow a programmer to iterate through the data one element at a time.Iterator enables you to cycle through a collection, obtaining or removing elements.

List al = new ArrayList();
      // add elements to the array list
      al.add("A");
      al.add("B");
      al.add("C");

// Use iterator to display contents of al
Iterator itr = al.iterator();
while(itr.hasNext()) {
         Object element = itr.next();
}
Iterator iterator()
The iterator() method returns an Iterator object from the collection. The methods in the Iterator interface are as follows:
boolean hasNext()
This returns true if the iteration has more elements.
Object next()
The preceding returns the next element in the iteration.
void remove()
This removes from the underlying collection the last element returned by the iterator.

ListIterator extends Iterator to allow bidirectional traversal of a list, and the modification of elements.

ListIterator litr = al.listIterator();
while(litr.hasNext()) {
   Object element = litr.next();
   litr.set(element + "+");
}
while(litr.hasPrevious()) {
   Object element = litr.previous();
}  

Set

A Set is unique because it does not allow duplicate objects to enter the collection of elements. The Set interface contains all of the methods of the Collection interface  and does not add any new methods. The difference is the add() and addAll() methods check for duplication of objects using the equals() method on each object.
The only functional class in the Java API that directly implements the Set interface is HashSet, as you can see in the Figure. Let’s look at the HashSet class in use.
import java.util.*;
class SetTest {
     public static void main (String [] args) {
            Set<String> hs = new HashSet<String>();
          hs.add("Hockey Game");
          hs.add("Poker");
          hs.add("Solitaire");
          hs.add("Hockey Game");
          System.out.println(hs);
     }
}

Sorted Set

The SortedSet interface is similar to the Set interface, except that the elements in the set are stored in ascending order. Once again, the elements are nonduplicating. The SortedSet interface includes all of the methods of Set because it extends Set, but also adds a few more to take advantage of the fact that it is sorted.
The TreeSet class is the only class to implement this interface directly. Let’s examine the TreeSet class in some code.
import java.util.*;
class SortedSetTest {
     public static void main (String [] args) {
          SortedSet set = new TreeSet();
          set.add("Hockey Game");
          set.add("Chess");
          set.add("Checkers");
          set.add("Blackjack");
          System.out.println(set);
          SortedSet end = set.tailSet("Checkers");
          System.out.println(end);
     }
}

List

A List is ordered. This allows a List to maintain an order as objects are added and removed from the collection. This is not the same as sorted! Sorted objects form a hierarchy based on how the objects compare to each other, such as alphabetical sorting.



Note: An ordered collection maintains the order of the elements based on the sequence you put stuff into/remove them from the collection. A sorted collection keeps the elements sorted based on a sort criteria.
 
A List can also contain duplicate entries of objects. The List interface adds several methods, all of which deal with the List collection being ordered. The added methods contain an index or index numbers that are used to specify a certain ordered object in the List.
There are three functional classes that implement the List interface.
·        LinkedListobjects are queued at the beginning of the list and removed from the end. Often used when buffering operations.
·        Vectora growable array of objects.
·        ArrayListThis class is roughly equivalent to Vector, except that it is unsynchronized.

  LinkedList ArrayList
get(int index)  O(n) (with n/4 steps on average) O(1) <--- main benefit of ArrayL
add(E element)  O(1) O(1) amortized, but O(n) worst-case
add(int index, E element)  O(n) (with n/4 steps on average), but O(1) when index = 0 O(n) (with n/2 steps on average)
remove(int index)  O(n) (with n/4 steps on average) O(n) (with n/2 steps on average)
Iterator.remove()  O(1). <--- main benefit of LinkedList<E> O(n) (with n/2 steps on average)
ListIterator.add(E element) O(1) This is one of the main benefits of LinkedList<E> O(n) (with n/2 steps on average)

 

 

Map

The Map interface does not extend the Collection interface (see figure), so in strict terms it is not a Collection type. In general terms, however, it is part of the collections architecture.
A Map stores objects that are identified by unique keys. A map may not store duplicate keys. It can, however, store duplicate objects. Objects are stored in Map collections in no particular order.
There are two common collections that directly implement the Map interface, as we saw in Figure:
·        Hashtable
·        HashMap
The HashMap class is roughly equivalent to Hashtable, except that it is not synchronized for threads and it permits null values to be stored.
import java.util.*;
class HashMapTest {
     public static void main (String [] args) {
          Map hm = new HashMap();
          hm.put("Game1","Tic Tac Toe");
          hm.put(null, "Chess");
          hm.put("Game3", "Checkers");
          hm.put("Game3", "Hockey Game");
          hm.put("Game4", "Chess");
          System.out.println(hm);
          String title = (String)hm.get("Game3");
          System.out.println(title);
     }
}

Sorted map

SortedMap is similar to Map, except the objects are stored in ascending order according to their keys. Like Map, there can be no duplicate keys and the objects themselves may be duplicated. One very important difference with SortedMap objects is that the key may not be a null value. SortedMap objects are, of course, sorted and it would be impossible to try to sort with a null value as a comparator.
TreeMap is the only core API class to implement this interface directly, so let’s examine this in some code.
import java.util.*;
class TreeMapTest {
     public static void main (String [] args) {
          Map titles = new TreeMap();
          titles.put(new Integer(2),"Tic Tac Toe");
          titles.put(new Integer(3), "Checkers");
          titles.put(new Integer(1), "Hockey Game");
          titles.put(new Integer(4), "Chess");
          System.out.println(titles);
     }
}


 
Sorted
Ordered
Uses Keys
No Duplicates
Set
 
 
 
X
SortedSet
X
 
 
X
List
 
X
 
 
Map
 
 
X
 
SortedMap
X
 
X


Now that you have a better idea of collections, here are some possible attributes for a collection, followed by the correct collection interface.

Non-duplicating, unordered collection
Set
Duplicating, ordered collection
List
Duplicating, ordered collection with keys
Map
Non-duplicating, sorted collection
SortedSet
Duplicating collection sorted by keys
SortedMap

·         Set can store only unique objects, not duplicates.
·         A List keeps the objects indexed in a definite order.
·        A Map stores objects according to keys.
·        SortedSet stores objects in ascending order without duplicates.
·        SortedMap stores objects in ascending order using keys.
·        SortedSet can’t contain objects that are null.
·        SortedMap can’t contain keys that are null.
·        HashSet implements the Set interface.
·        TreeSet implements the SortedSet interface.
·        LinkedList, Vector, and ArrayList implement List.
·        HashMap and Hashtable implement the Map interface.
·        TreeMap implements the SortedMap interface.

Interfaces and Abstract Classes


Interface
In its most common form, an interface is a group of related methods with empty bodies.
A bicycle's behavior, if specified as an interface, might appear as follows:
interface Bicycle { 
    //  wheel revolutions per minute
    void changeCadence(int newValue); 
    void changeGear(int newValue); 
    void speedUp(int increment); 
    void applyBrakes(int decrement);
}

Implementing an interface allows a class to become more formal about the behavior it promises to provide. Interfaces form a contract between the class and the outside world, and this contract is enforced at build time by the compiler. If your class claims to implement an interface, all methods defined by that interface must appear in its source code before the class will successfully compile.

class ACMEBicycle implements Bicycle { 
    // remainder of this class 
    // implemented as before
}

Interfaces are similar to abstract classes but all methods are abstract and all properties are static final. Interfaces can be inherited (ie. you can have a sub-interface). As with classes the extends keyword is used for inheritence.Java does not allow multiple inheritance for classes (ie. a subclass being the extension of more than one superclass). An interface is used to tie elements of several classes together. Interfaces are also used to separate design from coding as class method headers are specified but not their bodies. This allows compilation and parameter consistency testing prior to the coding phase. Interfaces are also used to set up unit testing frameworks.
Abstract class

An abstract class is a class that is declared abstract—it may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be subclassed.
An abstract method is a method that is declared without an implementation (without braces, and followed by a semicolon), like this:
abstract void moveTo(double deltaX, double deltaY);
If a class includes abstract methods, the class itself must be declared abstract, as in:
public abstract class GraphicObject {
   // declare fields
   // declare non-abstract methods
   abstract void draw();
}
When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent class. However, if it does not, the subclass must also be declared abstract.

What is the difference between an Interface and an Abstract class?


An abstract class can have instance methods that implement a default behavior. An Interface can only declare constants and instance methods, but cannot implement default behavior and all methods are implicitly abstract.
An interface has all public members and no implementation. An abstract class is a class which may have the usual flavors of class members (private, protected, etc.), but has some abstract methods.
An interface is a nonfunctional class that can contain constants and method declarations but no functional methods. It may seem, logically, if there is no functionality it might as well be a bunch of  statements. Interfaces are used when a class must behave like more than one type of object; in effect, it inherits methods and data from more than one super-class.
Interfaces are a way for the compiler to ensure that an object being used in a method has all the needed methods

When an Abstract Class Implements an Interface

In the section on Interfaces, it was noted that a class that implements an interface must implement all of the interface's methods. It is possible, however, to define a class that does not implement all of the interface methods, provided that the class is declared to be abstract. For example,
abstract class X implements Y {
  // implements all but one method of Y
}

class XX extends X {
  // implements the remaining method in Y
}
In this case, class X must be abstract because it does not fully implement Y, but class XX does, in fact, implement Y.



Java coding concepts

Coding concepts:

• Apply OO concepts like inheritance, polymorphism and encapsulation.
• Program to interfaces not to implementations.
• Use of relevant design patterns.
• Use of Java collections API and exceptions correctly.
• Stay away from hard coding values.

Saturday, August 28, 2010

What is a framework?

Last week a friend of mine who is attending a course on web application asked me what is a fremwork? Here is what I tried to explain him:

A framework is a generic architecture which build an infrastructure to develop applications in an specific technology. In simple words it is a set of basic classes and interfaces which build the infrastructure of an application.

Based on this definition it’s easy to think that using a framework is like using an API, when there is a big difference between these two. An API, e.g. Java, the classes are used by developer to do specified functionality: in this case our code call the existing code to do some function but the control of the application flow is by our code.
But using a framework means following an specific architecture; to be more precise extending the framework classes a/o implementing it’s interfaces. In this case the components of the framework have the control of the application flow.

A framework does several things:
• it makes it easier to work with complex technologies
• it ties together a bunch of discrete objects/components into something more useful
• it forces the team (or just me) to implement code in a way that promotes consistent coding, fewer bugs, and more flexible applications
• everyone can easily test and debug the code, even code that they didn't write

Maybe the best defintion is from the authors of Design Patterns:
"When you use a toolkit, you write the main body of the application and call the code you want to reuse. When you use a framework, you reuse the main body and write the code it calls."
"Not only can you build applications faster as a result, but the applications have similar structures. They are easier to maintain, and they seem more consistent o their users. On the other hand, you lose some creative freedom, since many design decisions have been made for you."
"If applications are hard to design, and toolkits are harder, then frameworks are hardest of all. ...Any substantive change to the framework's design would reduce its benefits considerably, since the framework's main contribution to an application is the architecture it defines. Therefore it's imperative to design the framework to be as flexible and extensible as possible."

In conclusion a framework is considered as part of an exisiting software where inserting your code; based on the rule "don't call us we call you". The framework classes will call your application code.