Sunday 26 September 2010

Cloning

Cloning

Why clone?

Sometimes you need to make a copy of an object. Most of the time the fact that Java uses references to objects is a great advantage because you don't have to worry about making copies of objects, but sometimes you need a copy.

  • Protect against changes. You need a copy to hand to someone you don't trust to leave the object unchanged.
  • In place of new. The standard way to make new objects is to use the new operator, which calls a class constructor. A different way to think about creating multiple objects of a "class" is to create on prototype and create new objects by copying this prototype, typically by calling on a factory method to create new objects. This is useful if different kinds of objects are distinguished by different parameter values.

    For example, you might want several kinds of arrowheads - filled, empty, diamonds, barbed, etc. With a little planning, code can be written to draw all of these types, differing only in parameter values (isFilled, pointAngle, barbAngle). Different types of graphical objects can simply be created once, and cloned to make a new objects of that "class".

The clone() method - and why you might want to override it

The Object class defines a clone() method that makes a shallow copy of an object.

Protected not public. Even if a shallow copy was sufficient, and it's often not, a user can't get to it because it's protected and not public, so only subclasses can see it, but no users! You can make it available by overriding it in your class and making it public -- you can always make an overridden method more visible that it was in the parent class.

Deep vs. Shallow Copies in java

Deep vs. Shallow Copies

Assignment and copies

Assignment. The assignment operator (=) makes a copy of the "value". For a primitive type (int, double, etc) this simply copies the numeric value, but the assignment of a object copies only the reference (address in memory) of the object.

Sharing immutable objects

One object may have many references to it. If an object is immutable, ie can't be changed, it can safely be shared, and there is no reason to have more than one copy of it. The most common example of this is the String class. All string objects are immutable. This is very useful and is fast because there is no need to copy the contents of the string, but only the reference to it (typically 32 bits). If you need a mutable string, then you can use StringBuilder.

No way to tell if something is immutable

The careful reader of Java keywords may have noticed that there is a const keyword. Mysteriously, this keyword has no use. The intent was to use it to declare things to be unchangeable, but it turned out to be too hard to make this work in an absolutely safe manner. There is no way to know if objects of a class are immutable, except by reading the documentation.

The final keyword allows only one assignment to a variable, but doesn't protect the fields of the object that variable references.

Interfaces in java

Interfaces in java are the pure abstract classes in which functions are given...which are to be implemented by all the class implementing those interface.

Note that in java interface naming is like Iterable, etc...i.e ending with able many times.

Non-static or Member inner class

If a static member class is analogous to a class field or class method, a member class is analogous to an instance field or instance method.

By default, an inner class is non-static:
This fragment defines the class A which contains a non-static inner class B.

A non-static inner class can be instantiated only inside a non-static method of the outer class. This is because every instance of a non-static inner class must be associated with an instance of the outer class. In a sense, every instance of a non-static inner class exists ``inside'' an instance of the outer class. A single instance of the outer class may have associated with it more than one instance of the inner class.
Because an instance of a non-static inner class has an associated instance of the outer class, the methods of the inner class can access directly any of the members (fields or methods) of the outer class instance. For example, the f method defined above can access both x and y directly.
public class A
{
int y;

public class B
{
int x;
void f () {}
}
}
The Java keyword this  can be used in a non-static method to refer to the current object instance. Thus in the method f, this refers to an instance of the inner B class. Every non-static inner class is associated with an instance of A.this.

Use: An Enumeration Implemented as a Member Class
public class LinkedStack {
// Our static member interface; body omitted here...
public static interface Linkable { ... }

// The head of the list
private Linkable head;

// Method bodies omitted here
public void push(Linkable node) { ... }
public Linkable pop() { ... }

// This method returns an Enumeration object for this LinkedStack
public java.util.Enumeration enumerate() { return new Enumerator(); }

// Here is the implementation of the Enumeration interface,
// defined as a member class.

protected class Enumerator implements java.util.Enumeration {
Linkable current
;
// The constructor uses the private head 
    //field of the containing class
public Enumerator() { current = head; }
public boolean hasMoreElements() { return (current != null); }
public Object nextElement() {
if (current == null) throw new java.util.NoSuchElementException();
Object value = current;
current
= current.getNext();
return value;
}
}
}



Restrictions on Member Classes

There are three important restrictions on member classes:
  • A member class cannot have the same name as any containing class or package. This is an important rule, and one not shared by fields and methods.
  • Member classes cannot contain any static fields, methods, or classes (with the exception of constant fields declared both static and final). staticfields, methods, and classes are top-level constructs not associated with any particular object, while every member class is associated with an instance of its enclosing class. Defining a static top-level member within a non-top-level member class simply promotes confusion and bad programming style, so you are required to define all static members within a top-level or static member class or interface.
  • Interfaces cannot be defined as member classes. An interface cannot be instantiated, so there is no object to associate with an instance of the enclosing class. If you declare an interface as a member of a class, the interface is implicitly static, making it a static member class.

New Syntax for Member Classes

The most important feature of a member class is that it can access the instance fields and methods in its containing object. We saw this in theLinkedStack.Enumerator() constructor of above link list example:
public Enumerator() { current = head; }
In this example, head is a field of the LinkedStack class, and we assign it to the current field of the Enumerator class. The current code works, but what if we want to make these references explicit? We could try code like this:
public Enumerator() { this.current = this.head; }
This code does not compile, however. this.current is fine; it is an explicit reference to the current field in the newly created Enumerator object. It is thethis.head expression that causes the problem; it refers to a field named head in the Enumerator object. Since there is no such field, the compiler generates an error. To solve this problem, Java defines a special syntax for explicitly referring to the containing instance of the this object. Thus, if we want to be explicit in our constructor, we can use the following syntax:
public Enumerator() { this.current = LinkedStack.this.head; }
The general syntax is classname.this, where classname is the name of a containing class. Note that member classes can themselves contain member classes, nested to any depth. Since no member class can have the same name as any containing class, however, the use of the enclosing class name prepended to this is a perfectly general way to refer to any containing instance. This syntax is needed only when referring to a member of a containing class that is hidden by a member of the same name in the member class.

Accessing superclass members of the containing class

When a class shadows or overrides a member of its superclass, you can use the keyword super to refer to the hidden member. This super syntax can be extended to work with member classes as well. On the rare occasion when you need to refer to a shadowed field f or an overridden method m of a superclass of a containing class C, use the following expressions:
C.super.f
C.super.m()

This syntax was not implemented by Java 1.1 compilers, but it works correctly as of Java 1.2.

Specifying the containing instance

As we've seen, every instance of a member class is associated with an instance of its containing class. Look again at our definition of the enumerate() method in :
public Enumeration enumerate() { return new Enumerator(); }

When a member class constructor is invoked like this, the new instance of the member class is automatically associated with the this object. This is what you would expect to happen and exactly what you want to occur in most cases. Occasionally, however, you may want to specify the containing instance explicitly when instantiating a member class. You can do this by preceding the new operator with a reference to the containing instance. Thus, the enumerate() method shown above is shorthand for the following:
public Enumeration enumerate() { return this.new Enumerator(); }

Let's pretend we didn't define an enumerate() method for LinkedStack. In this case, the code to obtain an Enumerator object for a given LinkedStackobject might look like this:
LinkedStack stack = new LinkedStack();    // Create an empty stack
Enumeration e = stack.new Enumerator(); // Create an Enumeration for it
The containing instance implicitly specifies the name of the containing class; it is a syntax error to explicitly specify that containing class:
Enumeration e = stack.new LinkedStack.Enumerator();  // Syntax error

There is one other special piece of Java syntax that specifies an enclosing instance for a member class explicitly. Before we consider it, however, let me point out that you should rarely, if ever, need to use this syntax. It is one of the pathological cases that snuck into the language along with all the elegant features of inner classes.
As strange as it may seem, it is possible for a top-level class to extend a member class. This means that the subclass does not have a containing instance, but its superclass does. When the subclass constructor invokes the superclass constructor, it must specify the containing instance. It does this by prepending the containing instance and a period to the super keyword. If we had not declared our Enumerator class to be a protected member of LinkedStack, we could subclass it. Although it is not clear why we would want to do so, we could write code like the following:
// A top-level class that extends a member class
class SpecialEnumerator extends LinkedStack.Enumerator {
// The constructor must explicitly specify a containing instance
// when invoking the superclass constructor.
public SpecialEnumerator(LinkedStack s) { s.super(); }
// Rest of class omitted...
}

Scope Versus Inheritance for Member Classes

We've just noted that a top-level class can extend a member class. With the introduction of member classes, there are two separate hierarchies that must be considered for any class. The first is the classhierarchy, from superclass to subclass, that defines the fields and methods a member class inherits. The second is the containmenthierarchy, from containing class to contained class, that defines a set of fields and methods that are in the scope of (and are therefore accessible to) the member class.
The two hierarchies are entirely distinct from each other; it is important that you do not confuse them. This should not be a problem if you refrain from creating naming conflicts, where a field or method in a superclass has the same name as a field or method in a containing class. If such a naming conflict does arise, however, the inherited field or method takes precedence over the field or method of the same name in the containing class. This behavior is logical: when a class inherits a field or method, that field or method effectively becomes part of that class. Therefore, inherited fields and methods are in the scope of the class that inherits them and take precedence over fields and methods by the same name in enclosing scopes.
Because this can be quite confusing, Java does not leave it to chance that you get it right. Whenever there is a naming conflict between an inherited field or method and a field or method in a containing class, Java requires that you explicitly specify which one you mean. For example, if a member class B inherits a field namedx and is contained within a class A that also defines a field named x, you must use this.x to specify the inherited field and A.this.x to specify the field in the containing class. Any attempt to use the field x without an explicit specification of the desired instance causes a compilation error.
A good way to prevent confusion between the class hierarchy and the containment hierarchy is to avoid deep containment hierarchies. If a class is nested more than two levels deep, it is probably going to cause more confusion than it is worth. Furthermore, if a class has a deep class hierarchy (i.e., it has many superclass ancestors), consider defining it as a top-level class, rather than as a member class.


Inner classes in java

In Java it is possible to define one class inside another. A class defined inside another one is called an inner class . Java provides two kinds of inner classes--static and non-static.

Thursday 23 September 2010

blocking queue has the following characteristics:
  • methods to add an item to the queue, waiting for space to become available in the queue if necessary;
  • corresponding methods that take an item from the queue, waiting for an item to put in the queue if it is empty;
  • optional time limits and interruptibility on the latter calls;
  • efficient thread-safety: blocking queues are specifically designed to have their put() method called from one thread and the take() method from another— in particular, items posted to the queue will be published correctly to any other thread taking the item from the queue again; significantly, the implementations generally achieve this without locking the entire queue, making them highly concurrent components;
  • integration with Java thread pools: a flavour of blocking queue can be passed into the constructor of ThreadPoolExecutor to customise the behaviour of the thread pool.
These features make BlockingQueues useful for cases such as the following:
  • a server, where incoming connections are placed on a queue, and a pool of threads picks them up as those threads become free;
  • in a variety of parallel processes, where we want to manage or limit resource usage at different stages of the process.

Queues in Java 5: the Queue interface

Java 5 adds queues to the Collections framework. A queue is in some ways a sub-construct of a list, usually implemented as a linked list, with the following characteristics:
  • unlike a normal list, it is not random access: that is, you can't get or set the element at an arbitrary position in the list;
  • get and set operations always take place at the ends of the queue (generally, one "takes from the head" and "puts on the tail").
In a standard queue, the next item to be taken is the one at the head of the queue, i.e. the one that has been there the longest. When items are added to the queue, they are added to the tail. The item at the tail can only be accessed once all the items placed before it have been removed in order.

Why use a queue?

So you may well be thinking: why use a queue if it has these restrictions? Can't you just use a boring old ArrayList or LinkedList1? It turns out there are at least three main reasons:
  • in some cases, a queue is "conceptually what we want";
  • eliminating random access allows optimisations for concurrency;
  • Java's efficient BlockingQueue implementations can take some of the work out of the most typical use of queues.
Places where we "conceptually" want a queue are where we are dealing with a so-called producer-consumer pattern. That is, one thread "produces" a list of jobs for another thread to pick up. Of course, we could use an ordinary (synchronized) LinkedList if this was purely our motivation. However, it turns out that restricting access to the head and tail of the queue allows for further optimisation for concurrent access.

Queues with thread pools

One place, then, in which queues are useful is for the work queue of a thread pool. Java provides the ThreadPoolExecutor class; when constructing this class, you can pass in the queue that you want the thread pool to use. Or, you can construct your thread pool with one of the utility methods in the Executors class, in which case a default BlockingQueue will be used.

Queue implementations firstly share a new Queue interface, which has several methods for accessing the head and tail of the queue. Recall that items are always placed on the end or "tail" of the list, and always read from the beginning or "head" of the list.
OperationThrows exception
if not possible
Returns value
if not possible
Add item to tailadd()offer()
Remove item from headremove()poll()
"Peek" item at headelement()peek()
Methods specified by the Java Queue interface

Types of Queues

Java provides Queue implementations depending on a few key criteria:
  • thread-safety: if you don't require the queue to be accessed concurrently from multiple threads, then a plain LinkedList can be used as a Queue; the advantage of the other implementations is that they offer efficient thread-safety;
  • blocking or non-blocking: various blocking implementations add extra methods to put and remove items from the queue, blocking until the operation is possible, with an optional time limit;
  • bound or non-bound: sometimes it is useful to put an upper limit on the number of items that can fit in the queue, e.g. to prevent a thread pool from queueing up too many jobs when the machine is busy;
  • other special operations: Java provides an implementation that orders by priority, and another that applies a delay to queued items.
As of Java 6, the various queue classes are as follows:
Queue implementations as of Java 6
Blocking?Other criteriaBoundNon-bound
BlockingNoneArrayBlockingQueueLinkedBlockingQueue
Priority-based PriorityBlockingQueue
Delayed DelayQueue
Non-blockingThread-safe ConcurrentLinkedQueue
Non thread-safe LinkedList
Non thread-safe, priority-based PriorityQueue
One further type of queue not included above is the SynchronousQueue, which is effectively a zero-length queue (so that a thread adding an item to the queue will block until another thread removes the item).

Blocking queues

In general, the most interesting queue implementations are the various blocking queues, which allow efficient concurrent access and are useful for coordinating objects between threads, particularly in the so-called producer-consumer pattern. In Java, all blocking queue implementations implement the BlockingQueue interface, which we look at next.

Tuesday 21 September 2010

java.math.BigInteger

Unbounded range. To work with integers that are larger than 64 bits (the size of a long), use java.math.BigInteger. This class represents unbounded integers and provides a number of methods for doing arithmetic with them.
Overflow in standard arithmetic. The problem with arithmetic using ints (or longs) is that, if the value becomes too large, Java saves only the low order 32 (64 for longs) bits and throws the rest away. For example, we can use the maximum value that can be stored in an int as an example. Both of the following operations can't possibly fit into an int, but the arithmetic doesn't produce an error, it produces a result!

import java.math.BigInteger;

public class TestOverflow {
public static void main(String[] args) {
int bad = 2000000000; //Close to int max value.
System.out.println("bad = " + bad);
System.out.println("bad + 1 = " + (bad + 1));
System.out.println("bad * 3 = " + (bad * 3));
System.out.println("bad * 4 = " + (bad * 4));

BigInteger good = BigInteger.valueOf(2000000000);
System.out.println();
System.out.println("good = " + good);
System.out.println("good.add(BigInteger.ONE) = " + good.add(BigInteger.ONE));
System.out.println("good.multiply(BigInteger.valueOf(3)) = " + good.multiply(BigInteger.valueOf(3)));
System.out.println("good.multiply(BigInteger.valueOf(4)) = " + good.multiply(BigInteger.valueOf(4)));
}
 
Produces this output. If a result exceeds Integer.MAX_VALUE (2,147,483,647), the result will be wrong, but Java doesn't report an error! The BigInteger results are correct. But you do have to put up was some seriously ugly syntax.
bad = 2000000000 bad + 1 = 2000000001 bad * 3 = 1705032704 // Smaller? bad * 4 = -589934592 // Negative?!!! Overflowed into sign bit. good = 2000000000 good.add(BigInteger.ONE) = 2000000001 good.multiply(BigInteger.valueOf(3)) = 6000000000 good.multiply(BigInteger.valueOf(4)) = 8000000000 Omitted features. BigInteger methods ignored in this summary: bit operations, random numbers, and prime testing.

Constructors and Methods

Assume
BigInteger bi, bi1, bi2, bi3, bi4;
BigInteger[] bia; // array holding division result and remainder.
String s; int i; long lng; float f; double d;
Constructors, constants, and static factory methods
bi = new BigInteger(s);Create BigInteger with decimal value represented by decimal String s.
bi = BigInteger.ONE;Predefined value 1.
bi = BigInteger.ZERO;Predefined value 0.
bi = BigInteger.valueOf(lng);Use this factory method to create BigIntegers from numeric expressions. An int parameter will be automatically promoted to long.
Arithmetic operations
bi1bi2.abs();Returns BigInteger absolute value.
bi1bi2.add(bi3);Returns sum of bi2 and bi3.
bi1bi2.divide(bi3);Returns division of bi2 and bi3.
biabi2.divideAndRemainder(bi3);Returns array of two BigIntegers representing the result of division and remainder of bi2 and bi3.
bi1bi2.gcd(bi3);Returns greatest common divisor of bi2 and bi3.
bi1bi2.max(bi3);Returns maximum of bi2 and bi3.
bi1bi2.min(bi3);Returns minimum of bi2 and bi3
bi1bi2.mod(bi3);Returns remainder after dividing bi2 by bi3
bi1bi2.multiply(bi3);Returns product of bi2 and bi3.
bi1bi2.pow(bi3);Returns bi2 to the bi3 power.
bi1bi2.remainder(bi3);Returns remainder of dividing bi2 by bi3. May be negative.
ibi.signum();-1 for neg numbers, 0 for zero, and +1 for positive.
bi1bi2.subtract(bi3);Returns bi2 - bi3.
Conversion to other values
dbi.doubleValue();Returns double value equivalent of bi.
fbi.floatValue();Returns float value equivalent of bi.
ibi.intValue();Returns int value equivalent of bi.
lngbi.longValue();Returns long value equivalent of bi.
sbi.toString();Returns decimal string representation of bi.
sbi.toString(i);Returns string representation of bi in radix i.
Other
bbi1.compareTo(bi2);Returns negative number if bi1<bi2, 0 if bi1==bi2, or positive number if bi1>bi2.

 

Random number in java : Shuffling

Monday 20 September 2010

Hashmap in java

public class HashMapExample{
public static void main(String args[]){
// constructs a new empty HashMap with default initial capacity
HashMap hashMap = new HashMap();
/*
To specify initial capacity, use following constructor.
HashMap HashMap = new HashMap(100);
To create HashMap from map use following constructor
HashMap HashMap = new HashMap(Map myMap);
*/
hashMap.put( "One", new Integer(1) ); // adding value into HashMap
hashMap.put( "Two", new Integer(2) );
hashMap.put( "Three", new Integer(3) );
/*
IMPORTANT : We CAN NOT add primitives to the HashMap. We have to wrap it into one of the wrapper before adding.
*/
/*
To copy all key - value pairs from any Map to HashMap use putAll method.
Signature of putAll method is,
void putAll(Map m)
*/
//get number of keys present in the HashMap
System.out.println("HashMap contains " + hashMap.size() + " key value pair.");
/*
To check whether HashMap is empty or not, use isEmpty() method.
isEmpty() returns true is HashMap is empty, otherwise false.
/*
Finding particular value from the HashMap :
HashMap's containsValue method returns boolean depending upon the presense of the value in given HashMap
Signature of the containsValue method is,
boolean containsValue(Object value)
*/
if( hashMap.containsValue( new Integer(1) ) ){
System.out.println("HashMap contains 1 as value");
}else{
System.out.println("HashMap does not contain 1 as value");
}
/*
Finding particular Key from the HashMap :
HashMap's containsKey method returns boolean depending upon the presense of the key in given HashMap
Signature of the method is,
boolean containsKey(Object key)
*/
if( hashMap.containsKey("One") ){
System.out.println("HashMap contains One as key");
}else{
System.out.println("HashMap does not contain One as value");
}
/*
Use get method of HashMap to get value mapped to particular key.
Signature of the get method is,
Object get(Object key)
*/
Integer one = (Integer) hashMap.get("One");
System.out.println("Value mapped with key \"One\" is " + one);
/*
IMPORTANT:  get method returns Object, so we need to downcast it.
*/
/*
To get all keys stored in HashMap use keySet method.
Signature of the keysSet method is,
Set keySet()
*/
System.out.println("Retriving all keys from the HashMap");
Iterator iterator = hashMap.keySet().iterator();
while( iterator. hasNext() ){
System.out.println( iterator.next() );
}
/*
To get all values stored in HashMap use entrySet() method.
Signature of the entrySet() method is,
Set entrySet()
*/
System.out.println("Retriving all values from the HashMap");
iterator = hashMap.entrySet().iterator();
while( iterator. hasNext() ){
System.out.println( iterator.next() );
}
/*
To remove particular key - value pair from the HashMap use remove method.
Signature of remove methid is,
Object remove(Object key)
This method returns value that had mapped to the given key, otherwise null if mapping not found.
*/
System.out.println( hashMap.remove("One") + " is removed from the HashMap.");
}
}

Output Hashmap in java

/*
OUTPUT of the above given Java HashMap Example would be :
HashMap contains 3 key value pair.
HashMap contains 1 as value
HashMap contains One as key
Value mapped with key "One" is 1
Retriving all keys from the HashMap
Three
Two
One
Retriving all values from the HashMap
Three=3
Two=2
One=1
1 is removed from the HashMap.
*/

Output Hashtables in java

/*
OUTPUT of the above given Java Hashtable Example would be :
Hashtable contains 3 key value pair.
Hashtable contains 1 as value
Hashtable contains One as key
Value mapped with key "One" is 1
Retriving all keys from the Hashtable
One
Three
Two
Retriving all values from the Hashtable
1
3
2
1 is removed from the Hashtable.
*/

Const in java (Final)

Defining the constants:
'public static final' variables are constant.
The naming convention for static final variables is to have them in upper case and separate two words with an underscore. For example:
static final int NUMBER_OF_MONTHS = 12;
static final float PI = (float22 7;
If you want to make a static final variable accessible from outside the class, you can make it public too:
public static final int NUMBER_OF_MONTHS = 12;
public static final float PI = (float22 7;
 
Note:
  1. Using the final keyword to declare a variable.
  2. The final keyword specifies that the value of a variable is final and cannot be changed.
  3. It is a convention in Java to write constants in uppercase letters.
  4. Sometimes we have to use enums instead of these simple constants for better readability.
 

Enums in java

In prior releases, the standard way to represent an enumerated type was the int Enum pattern:
// int Enum Pattern - has severe problems!
public static final int SEASON_WINTER = 0;
public static final int SEASON_SPRING = 1;
public static final int SEASON_SUMMER = 2;
public static final int SEASON_FALL = 3;
But these are not type safe, and clearly naming them is bit of a problem.
See here more for details. So in Java 5, they introduced Enums.

Defining Enums
Eg.
enum Season { WINTER, SPRING, SUMMER, FALL } 
public enum Rank { DEUCE, THREE, FOUR, FIVE, SIX,
SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE }

public enum Suit { CLUBS, DIAMONDS, HEARTS, SPADES }
  
public enum Shape { RECTANGLE, CIRCLE, LINE } 
  
Note on Semicolon ( ; )
Enum embedded inside a class. Outside the enclosing class, elements are referenced as Outter.Color.RED, Outter.Color.BLUE, etc.
public class Outter {
public enum Color {
WHITE, BLACK, RED, YELLOW, BLUE
}
}

Declaring enum variables and using enum values

The enum class name can be use like any other class type in declarations. Usually enum values must be prefixed with the enum type name.

Shape drawing = Shape.RECTANGLE;   // Only a Shape value can be assigned.

Looping over all enum values with foreach loop

The static values() method of an enum type returns an array of the enum values. The foreach loop is a good way to go over all of them.

for ( Color c :Color.values() ) {
         System.out.print( c + " " );
}


Getting an integer equivalent of an enum value

Each enum value in an enum class has an associated default value, starting with zero for the first value and incrementing by one for each additional value. This may be accessed with the ordinal() method.
System.out.println(drawing.ordinal());     // Prints 0 for RECTANGLE.
 

Input (Convert string to enum)

The valueOf() method can be used to convert a string value to an enum value. Here is an example of reading in a Shape value from a Scanner object in.
drawing = Shape.valueOf(in.next());
 
or
drawing = Shape.valueOf("RECTANGLE");
 
The static methods valueOf() and values() are created at compile time and do not appear in source code. 
They do appear in Javadoc, though; 
 
Read more in Effective java for better practises.
 

Arraylist by example

import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.Collections;
import java.util.Random;

/**
* A List corresponds to an "ordered" group of elements where duplicates are
* allowed.
*
* An ArrayList is a good choice for simple sequences.
* It is an Array based implementation where elements of the List can be
* accessed directly through get() and set() methods.
*
* ArrayList's give great performance on get() and set() methods, but do not
* perform well on add() and remove() methods when compared to a LinkedList.
*/

public class ArrayListExample {


public void doArrayListExample() {

final int MAX = 10;
int counter = 0;

//Create 2 lists
List listA = new ArrayList();
List listB = new ArrayList();
//Store 10 ints in listA
for (int i = 0; i < MAX; i++) {
System.out.println(" - Storing Integer(" + i + ")");
listA.add(new Integer(i));
}
//Add strings to the listA
listA.add("Alex");

listA.add("Melody");

listA.add("Jeff");

listA.add("Alex");

//Using iterators
Iterator i = listA.iterator();
while (i.hasNext()) {
System.out.println(i.next());
}

//Using listIterator

counter = 0;
ListIterator li = listA.listIterator();
while (li.hasNext()) {
System.out.println("Element [" + counter + "] = " + li.next());
System.out.println(" - hasPrevious = " + li.hasPrevious());
System.out.println(" - hasNext = " + li.hasNext());
System.out.println(" - previousIndex = " + li.previousIndex());
System.out.println(" - nextIndex = " + li.nextIndex());
System.out.println();
counter++;
}


System.out.println();
System.out.println("+---------------------------------------------------------------------+");
System.out.println("| Retrieve objects in an ArrayList container using index. |");
System.out.println("+---------------------------------------------------------------------+");
System.out.println();

for (int j=0; j < listA.size(); j++) {
System.out.println("[" + j + "] - " + listA.get(j));
}


System.out.println();
System.out.println("+---------------------------------------------------------------------+");
System.out.println("| Search for a particular Object and return its index location. |");
System.out.println("+---------------------------------------------------------------------+");
System.out.println();

int locationIndex = listA.indexOf("Jeff");
System.out.println("Index location of the String \"Jeff\" is: " + locationIndex);


System.out.println();
System.out.println("+---------------------------------------------------------------------+");
System.out.println("| Search for an object and return the first and last (highest) index. |");
System.out.println("+---------------------------------------------------------------------+");
System.out.println();

System.out.println("First occurance search for String \"Alex\". Index = " + listA.indexOf("Alex"));
System.out.println("Last Index search for String \"Alex\". Index = " + listA.lastIndexOf("Alex"));


System.out.println();
System.out.println("+---------------------------------------------------------------------+");
System.out.println("| Extract a sublist from the main list, then print the new List. |");
System.out.println("+---------------------------------------------------------------------+");
System.out.println();

List listSub = listA.subList(10, listA.size());
System.out.println("New Sub-List from index 10 to " + listA.size() + ": " + listSub);


System.out.println();
System.out.println("+---------------------------------------------------------------------+");
System.out.println("| Sort the Sub-List created above. |");
System.out.println("+---------------------------------------------------------------------+");
System.out.println();

System.out.println("Original List : " + listSub);
Collections.sort(listSub);
System.out.println("New Sorted List : " + listSub);
System.out.println();


System.out.println();
System.out.println("+---------------------------------------------------------------------+");
System.out.println("| Reverse the Sub-List created above. |");
System.out.println("+---------------------------------------------------------------------+");
System.out.println();

System.out.println("Original List : " + listSub);
Collections.reverse(listSub);
System.out.println("New Reversed List : " + listSub);
System.out.println();


System.out.println();
System.out.println("+---------------------------------------------------------------------+");
System.out.println("| Check to see if the Lists are empty. |");
System.out.println("+---------------------------------------------------------------------+");
System.out.println();

System.out.println("Is List A empty? " + listA.isEmpty());
System.out.println("Is List B empty? " + listB.isEmpty());
System.out.println("Is Sub-List empty? " + listSub.isEmpty());


System.out.println();
System.out.println("+---------------------------------------------------------------------+");
System.out.println("| Clone the initial List. |");
System.out.println("| NOTE: The contents of the List are object references, so both |");
System.out.println("| of the List's contain the same exact object reference's. |");
System.out.println("+---------------------------------------------------------------------+");
System.out.println();

System.out.println("List A (before) : " + listA);
System.out.println("List B (before) : " + listB);
System.out.println("Sub-List (before) : " + listSub);
System.out.println();
System.out.println("Are List's A and B equal? " + listA.equals(listB));
System.out.println();
listB = new ArrayList(listA);
System.out.println("List A (after) : " + listA);
System.out.println("List B (after) : " + listB);
System.out.println("Sub-List (after) : " + listSub);
System.out.println();
System.out.println("Are List's A and B equal? " + listA.equals(listB));


System.out.println();
System.out.println("+---------------------------------------------------------------------+");
System.out.println("| Shuffle the elements around in some Random order for List A. |");
System.out.println("+---------------------------------------------------------------------+");
System.out.println();

System.out.println("List A (before) : " + listA);
System.out.println("List B (before) : " + listB);
System.out.println("Sub-List (before) : " + listSub);
System.out.println();
System.out.println("Are List's A and B equal? " + listA.equals(listB));
System.out.println();
Collections.shuffle(listA, new Random());
System.out.println("List A (after) : " + listA);
System.out.println("List B (after) : " + listB);
System.out.println("Sub-List (after) : " + listSub);
System.out.println();
System.out.println("Are List's A and B equal? " + listA.equals(listB));


System.out.println();
System.out.println("+---------------------------------------------------------------------+");
System.out.println("| Convert a List to an Array. |");
System.out.println("+---------------------------------------------------------------------+");
System.out.println();

Object[] objArray = listA.toArray();
for (int j=0; j < objArray.length; j++) {
System.out.println("Array Element [" + j + "] = " + objArray[j]);
}


System.out.println();
System.out.println("+---------------------------------------------------------------------+");
System.out.println("| Remove (clear) Elements from List A. |");
System.out.println("+---------------------------------------------------------------------+");
System.out.println();

System.out.println("List A (before) : " + listA);
System.out.println("List B (before) : " + listB);
System.out.println();
listA.clear();
System.out.println("List A (after) : " + listA);
System.out.println("List B (after) : " + listB);
System.out.println();

}


/**
* Sole entry point to the class and application.
* @param args Array of String arguments.
*/
public static void main(String[] args) {
ArrayListExample listExample = new ArrayListExample();
listExample.doArrayListExample();
}

}

Sunday 19 September 2010

Continue with label demo

 test:
        for (int i = 0; i <= max; i++) {
            int n = substring.length();
            int j = i;
            int k = 0;
            while (n-- != 0) {
                if (searchMe.charAt(j++!= substring.charAt(k++)) {
                    continue test;
                }
            }    
            foundIt = true;
            break test;
        }

Exceptions in java

Exceptions are 2 types.
1.Checked
2.Uncheked
All the exception for that compiler doesn't care are comes under unchecked exception i.e. ArithmaticException ArrayIndexOutofBoundexp etc
Exceptions which needs to be defined in throws clause of a method r checked exception ie.sevletException ClassNotFoundExp NoSuchFieldException etc

Thursday 16 September 2010

Making library of books

To have library we can have 2 components for sure:
1. Books
2. Person borrowing that books

So we need a person class
class Person
{
String name;
public Person (String n)
{
name = n;
}

public String details ()
{
return name;
}

public String toString()
{
return "name <"+name+">";
}
}
 
Person must take membership from library...so something has to be added to above
class Membership
{
public boolean canLoan(int onLoan)
{
return false;
}
}

class JuniorMember extends Membership
{
public boolean canLoan(int onLoan)
{
return onLoan<1;
}
public String toString()
{
return "Junior";
}
}

class StandardMember extends Membership
{
public boolean canLoan(int onLoan)
{
return onLoan<6;
}
public String toString()
{
return "Standard";
}
}

class OAPMember extends Membership
{
public boolean canLoan(int onLoan)
{
Calendar now = Calendar.getInstance();
int day = now.get(Calendar.DAY_OF_WEEK);
//if (day==Calendar.SATURDAY || day==Calendar.SUNDAY)
if (day == Calendar.THURSDAY)
return false;
return true;
}
public String toString()
{
return "OAP";
}
}
We have to add how many books person borrowed...so we have to add following function:
 So now person class become:
public class Person
{
String name;
Membership mem;
int books;
public Person (String n, Membership member)
{
name = n;
mem = member;
}

public boolean borrow(Book b)
{
if (b.canLoan() && mem.canLoan(books))
{
books++;
return true;
}
return false;
}

public String details ()
{
return name+":"+mem;
}

public String toString()
{
return "name <"+name+"> "+mem;
}
}

 

Extending books to loanable and reference books

class LoanBook extends Book
{
public LoanBook (String t, String a, int c1, int c2, float p)
{
super(t,a,c1,c2,p);
}

public boolean canLoan()
{
return true;
}

public String details ()
{
return "Loan: "+super.details();
}

public String toString()
{
return "loan: "+super.toString();
}
}

class ReferenceBook extends Book
{
public ReferenceBook (String t, String a, int c1, int c2, float p)
{
super(t,a,c1,c2,p);
}

public boolean canLoan()
{
return false;
}

public String details ()
{
return "Reference: "+super.details();
}

public String toString()
{
return "Ref: "+super.toString();
}
}



class Loan
{
Book book;
Person person;
Date date = new Date();

public Loan (Book b, Person p)
{
book = b;
person = p;
}

public String details ()
{
return book.details()+" loaned on "+date+" to "+person.details();
}

public String toString()
{
return "book "+book+" -> person"+person+" @date "+date;
}
}

public class Library
{
public static void main(String[] args)
{
Book b1 = new LoanBook ("Java I/O Programming","E.R.Harrold",123,45,18.99F);
Book b2 = new LoanBook ("Java in a Nutshell","D.Flanagan",123,25,12.99F);
Book b3 = new ReferenceBook ("The Java CLass Libraries","P.Chan & R.Lee",2123,10,35.00F);

System.out.println("Books");
System.out.println(b1);
System.out.println(b2);
System.out.println(b3);
System.out.println("");

System.out.println("People:");
Person james = new Person ("James Gosling");
System.out.println(james);
System.out.println("");

Loan l1 = makeLoan(james, b1);
Loan l2 = makeLoan(james, b2);
Loan l3 = makeLoan(james, b3);
}

private static Loan makeLoan(Person p, Book b)
{
Loan l=null;
if (b.canLoan())
{
l = new Loan(b,p);
System.out.println(l.details());
}
else
System.out.println("Cannot loan "+b.details()+" to "+p.details());
System.out.println("");
return l;
}


}

Book class 1

class Book
{
String title;
String author;
float price;
int cat, subCat;

public Book (String t, String a, int c1, int c2, float p)
{
title = t;
author = a;
price = p;
cat = c1;
subCat = c2;
}

public String details ()
{
return title+", "+author+" Category "+cat+"."+subCat+" value $"+price;
}

public String toString()
{
return "Title <"+title+"> Author <"+author+"> cat:"+cat+" subCat:"+subCat+" price:"+price;
}
}

Improving coding style into classes

Class and Interface declarations should be organized in the following manner: 
1. Class/Interface documentation. 
2. class or interface statement. 
3. Class (static) variables in the order public, protected, package (no access modifier), private. 
4. Instance variables in the order public, protected, package (no access modifier), private.
5. Constructors. 
6. Methods (no specific order). Reduce complexity by making the location of each class element predictable. 


Imported classes should always be listed explicitly.
import java.util.List; // NOT: import java.util.*; 
import java.util.ArrayList; 
import java.util.HashSet; 
Importing classes explicitly gives an excellent documentation value for the class at hand and makes the class easier to comprehend and maintain. Appropriate tools should be used in order to always keep the import list minimal and up to date.