Monday, 20 September 2010

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.