Monday, May 19, 2008

HashMap : Basics


package datastructure.delme;
import java.util.*;

class SimpleClass {
private String desc;
public SimpleClass(String s) {
desc=s;
}
public String getDesc() {
return desc;
}
@Override
public String toString() {
return "description is "+desc;
}
}

public class DelMeCollection {
public static void main(String[] args) {
System.out.println("in main");
SimpleClass s1 = new SimpleClass("one");
SimpleClass s2 = new SimpleClass("two");
SimpleClass s3 = new SimpleClass("three");
SimpleClass s4 = new SimpleClass("four");

HashMap hm = new HashMap();
hm.put("1",s1);
hm.put("2",s2);
hm.put("3",s3);
hm.put("4",s4);
Iterator hmKeyItr = hm.keySet().iterator();
while(hmKeyItr.hasNext())
{
String tempKey= (String)hmKeyItr.next();
System.out.println(tempKey+" val is "+hm.get(tempKey));
}

Iterator hmValItr = hm.values().iterator();
while(hmValItr.hasNext())
{
SimpleClass tempVal = (SimpleClass)hmValItr.next();
System.out.println(" val is "+tempVal);
}

for (Map.Entry entry: hm.entrySet())
{
System.out.println(entry.getKey() + " -> " + entry.getValue());
}


}
}



also tried UPCASTING
the following gave error


HashMap < string , object > hm = new HashMap < string , simpleclass >();
HashMap < string , simpleclass > hm = new HashMap < string , object >();
HashMap < string , simpleclass > hm = new HashMap < object , sipleclass >();
HashMap < object , simpleclass > hm = new HashMap< string , simpleclass >();



Moreover java.util.HashMap

Note that this implementation is not synchronized. If multiple threads access this map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more mappings; merely changing the value associated with a key that an instance already contains is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the map. If no such object exists, the map should be "wrapped" using the Collections.synchronizedMap method. This is best done at creation time, to prevent accidental unsynchronized access to the map:

Map m = Collections.synchronizedMap(new HashMap(...));

Friday, May 16, 2008

Clear the Screen In Java 5

Ask your friend to write a simple command line utility in java that gives a set of options like ...

1. Press 1 to add element to LinkedList
2. Press 2 to Delete an element in LinkedList
3. Press 3 to traverse the LinkedList
4. Press 4 to exit

Enter Your Choice : _


When user choses one of the above mentioned options ,
First , the screen should be cleared off
Second , the corresponding details (if any) should be asked ( like eneter value to add / delete )
Third , perform the action
Fourth , ReDisplay the above menu

To complete the above program you need to write a method like...


public void clearTheScreen( ) {
....
}


or may be


public boolean clearTheScreen( ) {
....
// return true if screen deleted else false
}


How to complete this method ??

hhhmmmm lets "BRAIN STORM"

"first" reply may be...
Runtime.getRuntime.exec("cls");

No you say ...
System-specific tasks such as these may be performed via Runtime.exec( )
it allows you to perform certain system-specific tasks BUT with very little control.

Actually, this won't work. Yes, the 'cls' command is invoked, *but* it is
invoked in a new process ['command.com' or 'cmd.exe' is exected creating a
new process], and *does not* clear the Java application's console.

If your friend is intelligent may argue ...
But if they can implement "beep", and they do, they should be able to implement "cls" too.
But you are MORE intelligent , you say
That's because BELL is a standard ASCII character (code 7) and it's
pretty much standard that any terminal/console would render it by beeping.


The "second" reply may be
System.out.print("\n\n\n\n\n\n\n\n\n\n\n\n");

and you say ... its obviously incorrect ( BTW your friend is stupid if he mentions this option ) ,
as it scrolls the menu above so that its not visible to user NOT clean the screen.


"third" reply may be
I heard about this method:
System.out.print((char)27 + "[2J");

Dont get scared probably your friend probably was good DOS progarmmr at some time as + "[2J" is the ANSI escape sequence for clearing the screen.
However, it doen't work unless "ansi.sys" is loaded and very few WinXP user's have this.

If your friend is a Windows geek he may say

Yes, we can add the following command in the c:\windows\system32\config.nt.
device=c:\windows\system32\ansi.sys
This will load the ansi.sys

But that wont work buddy ... you may try it yourself .. and besides
Thats Platform dependent !! and Java is platform independent right ?
so take a "Chill Pill dude"

"fourth" may be ( if your friends guesses this .. he is really good with java / linux )
Printing out the form-feed character will clear the screen
System.out.print("\f");
It works but only on linux , not on windows ... But java code should be platform independent

Your friend : " So WHAT SHOULD I DO ??? "
You ( with a smile ) : Write Java Native Interface [JNI] routines which tap into the relevant operating system functionality
Your Friend : " ?? WHY ?? "
You : Unfortunately these tasks are inherently operating system-specific, and cannot be implemented in any standard way across platforms. Some platforms, in fact, don't even understand the concepts of 'screen', or 'cursor', so wouldn't even have any use for classes that implemented these abstractions. Even the 'standard' C and C++ languages which, like Java, aim for platform independance, do not implement such functionality.

Most intelligent of your friend may say ...
( you know the Phd types )

Maybe a nested class could be added to 'System', containing all the
system-specific console-management routines, something like:

class System
{
...
public class Console
{
...
public static native void cls();
public static native void setCurPos(int row, int col);
public static native String inputString();
public static native double inputNumeric();
...
}
...
}

You could then do something like:

System.Console.cls();


and YOU calmly reply ...
Amego !! It would defeat the purpose of platform-independance, since not all
platforms have the concept of a "console".


Real solution ??
Write JNI ( platform dependent way ) OR
Look at jcurses on sourceforge. ( but using this is an overkill )
http://sourceforge.net/projects/javacurses/

NeXt ... ask your friend .. to write a code to Accept input [say a single keystroke] without pressing ENTER and let me know how it goes ;o)

Contradiction
Contradicting my self ... Recently discovered that with Java 6 , Its very much possible ...
In Java 6 a better way of interacting with the command prompt was introduced, the java.io.Console class.
Together with the utility class java.util.Scanner introduced in Java 5 this new API can be used to develop more advanced Java console applications.

For more detaisl checkout
http://java.dzone.com/news/console-applications-java-6
http://java.sun.com/javase/6/docs/api/java/io/Console.html

Java Sort

http://mindprod.com/jgloss/sort.html

Thursday, May 15, 2008

Java Hashing

lets start with hashing in general and how does java implement same and what are the drawbacks ( if any )

hashing is a process of generating an index or address ( which is of smaller length) basing on ur data . A good hash function is the one which generates distinct addresses for distinct file names.

As a simple example of the using of hashing in databases, a group of people could be arranged in a database like this:
Abernathy, Sara Epperdingle, Roscoe Moore, Wilfred Smith, David (and many more sorted into alphabetical order)
Each of these names would be the key in the database for that person's data. A database search mechanism would first have to start looking character-by-character across the name for matches until it found the match (or ruled the other entries out). But if each of the names were hashed, it might be possible (depending on the number of names in the database) to generate a unique four-digit key for each name. For example:
7864 Abernathy, Sara 9802 Epperdingle, Roscoe 1990 Moore, Wilfred 8822 Smith, David (and so forth)
A search for any name would first consist of computing the hash value (using the same hash function used to store the item) and then comparing for a match using that value. It would, in general, be much faster to find a match across four digits, each having only 10 possibilities, than across an unpredictable value length where each character had 26 possibilities.

The hashing algorithm is also called hash function


Uses of hashing
(i) Hashes play a role in security systems where they're used to ensure that transmitted messages have not been tampered with. The sender generates a hash of the message, encrypts it, and sends it with the message itself. The recipient then decrypts both the message and the hash, produces another hash from the received message, and compares the two hashes. If they're the same, there is a very high probability that the message was transmitted intact.

(ii) Hashing is also a common method of accessing data records.

Java and hashing
Every Java object has a hashCode() and an equals() method. While the Java language does not provide direct support for associative arrays -- arrays that can take any object as an index -- the presence of the hashCode() method in the root Object class clearly anticipates the ubiquitous use of HashMap (and its predecessor, Hashtable). Under ideal conditions, hash-based containers offer both efficient insertion and efficient retrieval; supporting hashing directly in the object model facilitates the development and use of hash-based containers.

if two objects are equal according to the equals() method, they must have the same hashCode() value (although the reverse is not generally true).

Why override equals() and hashCode()?

What would happen if a class did not override equals() and hashCode()? Nothing, if we never used an that class as a key in a HashMap or other hash-based collection. However, if we were to use such a classes object for a key in a HashMap, we would not be able to reliably retrieve the associated value, unless we used the exact same classes instance in the get() call as we did in the put() call. This would require ensuring that we only use a single instance of the Integer object corresponding to a particular integer value throughout our program. Needless to say, this approach would be inconvenient and error prone.

There are some restrictions placed on the behavior of equals() and hashCode(), which are enumerated in the documentation for Object. In particular, the equals() method must exhibit the following properties:
· Symmetry: For two references, a and b, a.equals(b) if and only if b.equals(a)
· Reflexivity: For all non-null references, a.equals(a)
· Transitivity: If a.equals(b) and b.equals(c), then a.equals(c)
· Consistency with hashCode(): Two equal objects must have the same hashCode() value
· For any non-null reference value x, x.equals(null) must return false.

public boolean equals(Object o) {
if (o == null)
return false;
...
}

public boolean equals(Object o) {
if (!(o instanceof MyType))
return false; // also return null if o is null .. no spl check required
...
}

Building hashing into the root object class of the Java class library was a very sensible design compromise -- it makes using hash-based containers so much easier and more efficient. However, several criticisms have been made of the approach to and implementation of hashing and equality in the Java class library. The hash-based containers in java.util are very convenient and easy to use, but may not be suitable for applications that require very high performance. While most of these will never be changed, it is worthwhile to keep in mind when you're designing applications that rely heavily on the efficiency of hash-based containers. These criticisms include:

Too small a hash range. Using int, instead of long, for the return type of hashCode() increases the possibility of hash collisions.


Bad distribution of hash values. The hash values for short strings and small integers are themselves small integers, and are close to the hash values of other "nearby" objects. A more well-behaved hash function would distribute the hash values more evenly across the hash range.


No defined hashing operations. While some classes, such as String and List, define a hash algorithm to be used in combining the hash values of its constituent elements into a single hash value, the language specification does not define any approved means of combining the hash values of multiple objects into a new hash value.

Difficulty writing equals() when extending an instantiable class that already overrides equals(). The "obvious" ways to define equals() when extending an instantiable class that already overrides equals() all fail to meet the symmetry or transitivity requirements of the equals() method. This means that you must understand the structure and implementation details of classes you are extending when overriding equals(), and may even need to expose private fields in the base class as protected to do so, which violates principles of good object-oriented design.

Basically what happens is when hashCode returns a number then its searched for in collection and gets a list, and then it uses equals( ) to search in bucket that it got.

Equals( ) defines logical equality

Recipie for a equals( ) method

1. Use the == operator to check if the argument is a reference to this object.
If so, return true. This is just a performance optimization, but one that is worth
doing if the comparison is potentially expensive.
2. Use the instanceof operator to check if the argument is of the correct
type. If not, return false. Typically, the correct type is the class in which the
method occurs. Occasionally, it is some interface implemented by this class.
Use an interface if the class implements an interface that refines the equals
contract to permit comparisons across classes that implement the interface. The
collection interfaces Set, List, Map, and Map.Entry have this property.
3. Cast the argument to the correct type. Because this cast was preceded by an
instanceof test, it is guaranteed to succeed.
4. For each “significant” field in the class, check to see if that field of the argument
matches the corresponding field of this object. If all these tests succeed,
return true; otherwise, return false.
5. When you are finished writing your equals method, ask yourself three
questions: Is it symmetric, is it transitive, and is it consistent?

Here is the contract, copied from the java.lang.Object specification:
n Whenever it is invoked on the same object more than once during an execution
of an application, the hashCode method must consistently return the
same integer, provided no information used in equals comparisons on the
object is modified. This integer need not remain consistent from one execution
of an application to another execution of the same application.
n If two objects are equal according to the equals(Object) method, then calling
the hashCode method on each of the two objects must produce the same
integer result.
n It is not required that if two objects are unequal according to the equals(Object)
method, then calling the hashCode method on each of the two objects
must produce distinct integer results. However, the programmer should be
aware that producing distinct integer results for unequal objects may improve
the performance of hash tables.

References
http://java.sun.com/docs/books/effective/chapters.html
http://www.owasp.org/index.php/Hashing_Java

Java Iterator

Iterator also has a method remove( ) , when its called it will remove from source the last item retrieved from next( )

If remove is called twice in succesion without a call to next in between IllegalStateException is thrown can get Concurrent MOdification exceptiion if someone else is modifying the collection

according to http://java.sun.com/j2se/1.4.2/docs/api/java/util/Iterator.html#remove()
The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other than by calling this method.


import java.util.*;
public class DelMeCollection {
public static List l = new ArrayList(25);
static class ListIterateThread extends Thread {
public void run( ){
System.out.println("thread started ");
Iterator listItr = l.iterator();
System.out.println("got the iterator ");
try {
while(listItr.hasNext())
System.out.println("val is "+listItr.next());
} catch(Exception e ) {
System.out.println("some exception "+e);
// wonder why no concurrent modification exception
}
}
}

public static void main(String[] args) {
System.out.println("inside main THREAD");
ListIterateThread lt= new ListIterateThread();
List l = new ArrayList(25);
lt.start();
l.add("1"); System.out.println("added 1");
l.add("2"); System.out.println("added 2");
l.add("3"); System.out.println("added 3");
l.add("4"); System.out.println("added 4");
l.add("5"); System.out.println("added 5");


l.add("11"); System.out.println("added 11");
l.add("12"); System.out.println("added 12");
l.add("13"); System.out.println("added 13");
l.add("14"); System.out.println("added 14");
l.add("15"); System.out.println("added 15");

try {
Thread.currentThread().sleep(5);
} catch (InterruptedException e) {
System.out.println("exception "+e);
}

l.add("21"); System.out.println("added 21");
l.add("22"); System.out.println("added 22");
l.add("23"); System.out.println("added 23");
l.add("24"); System.out.println("added 24");
l.add("25"); System.out.println("added 25");

l.add("31"); System.out.println("added 31");
l.add("32"); System.out.println("added 32");
l.add("33"); System.out.println("added 33");
l.add("34"); System.out.println("added 34");
l.add("35"); System.out.println("added 35");

}
}


Got Output


inside main THREAD
added 1
added 2
added 3
added 4
thread started
added 5
got the iterator
added 11
added 12
added 13
added 14
added 15
added 21
added 22
added 23
added 24
added 25
added 31
added 32
added 33
added 34
added 35


If you want to iterate through "Filtered Collection" try this

Java Collections

Framework consisits of three parts
  1. interfaces -
  2. implementation - of above interfaces
  3. algorithms - general applicable to either interfaces / implementation
Interfaces
  1. Collection - A collection represents a group of objects, known as its elements. may or may not have duplicate elements .. defines no order. JDK has no direct implementation of this interface.
  2. List - defines order , may have dup
  3. Set - no dup
  4. SortedSet - set with order
  5. Map - not part of hierarchy , just store key value pairs

Implementations
Keeping the two concepts ( interface & implementation) seperate can help you write code like
List l = new ....{ }

You can change implementation when your business condition require you to do so

<>

LinkedList is gr8 if u want to add/remove data from middle , if you want indexed access then ArrayList is better

  • All implementations are unsynchronised
  • All implementations offer fail fast iterators
  • All implementations are serializable and cloneable
  • All implementations support having null elements

Algorithm
the Collections class has methods that allow you to perform action on these data
This class consists exclusively of static methods that operate on or return collections.
Has static variables like EMPTY_LIST , EMPTY_MAP , EMPTY_SET
methods like binarySearch , min , max , reverse

java.util.Collection
All general-purpose Collection implementation classes (which typically implement Collection indirectly through one of its subinterfaces) should provide two "standard" constructors: a void (no arguments) constructor, which creates an empty collection, and a constructor with a single argument of type Collection, which creates a new collection with the same elements as its argument.

Adding Elements Framework consisits of three parts
(i) interfaces -
(ii) implementation - of above interfaces
(iii) algorithms - general applicable to either interfaces / implementation

Interfaces
  • Collection - A collection represents a group of objects, known as its elements. may or may not have duplicate elements .. defines no order. JDK has no direct implementation of this interface.
  • List - defines order , may have dup
  • Set - no dup
  • SortedSet - set with order
  • Map - not part of hierarchy , just store key value pairs

Implementations
Keeping the two concepts ( interface & implementation) seperate can help you write code like
List l = new ....{ }
You can change implementation when your business condition require you to do so



















































INTERFACE

HASH TABLE

RESIZABLE ARRAY

BALANCED TREE

LINKED LIST

HISTORICAL

SET
Hah Set
TreeSet


SORTEDSET


TreeSet


LIST

ArrayList
LinkedList

MAP


HashMap



WeakHashMap



TreeMap


Vector



Stack



HashTable



Properties



SORTEDMAP


TreeMap



LinkedList is gr8 if u want to add/remove data from middle , if you want indexed access then ArrayList is better

  • All implementations are unsynchronised
  • All implementations offer fail fast iterators
  • All implementations are serializable and cloneable
  • All implementations support having null elements

Algorithm
the Collections class has methods that allow you to perform action on these data
This class consists exclusively of static methods that operate on or return collections.
Has static variables like EMPTY_LIST , EMPTY_MAP , EMPTY_SET
methods like binarySearch , min , max , reverse

java.util.Collection
All general-purpose Collection implementation classes (which typically implement Collection indirectly through one of its subinterfaces) should provide two "standard" constructors: a void (no arguments) constructor, which creates an empty collection, and a constructor with a single argument of type Collection, which creates a new collection with the same elements as its argument.

Adding Elements
public boolean add(Object a) -- can only throw UnsupportedOperation exception , not nullpointerExcep
public boolean addAll(Collection c)

Removing Elements
public void clear()
public boolean remove(Object elem)
public boolean removeAll(Collection c)
if original was {1,5,3,8,1,8,2,4,1,3,7,6}
and passed list is {1,7}
every instance of 1 nad 7 will be removed
you get {5,3,8,8,2,4,3,6}

public boolean retainAll(Collection c)
opposite of remove

public Iterator iterator()

finding elements
public boolean contains(Object elem)
public boolean containsAll(Collection c)

checking size
public int size()
public boolean isEmpty()

copy and cloning collection
public Object[] toArray( )
public Object[] toArray(Object[] a)
consults the passed collection in terms of return type and size
if collections.siz() <= a.size() ... elements are returned in array and returned

Collection c = ....
String array[] = new String[c.size()];
array = (String[])c.toArray(array);


check for equality
public boolean equals(Object o)
Note besides Object.equals() interface also has this method to imphasize the fact that need to override Its not necessary to override the Object.equals( ) The general contract for the Object.equals method states that equals must be symmetric (in other words, a.equals(b) if and only if b.equals(a)). The contracts for List.equals and Set.equals state that lists are only equal to other lists, and sets to other sets. Thus, a custom equals method for a collection class that implements neither the List nor Set interface must return false when this collection is compared to any list or set. -- dont try to add colection to itself

List l = new ArrayList(6);
l.add("1");
System.out.println("added 1");
l.add("2");
System.out.println("added 2");
l.add(l);
System.out.println("KABOOM !!");
Iterator listItr = l.iterator();
while(listItr.hasNext())
System.out.println("val is "+listItr.next());

I got the output

added 1
added 2
KABOOM !!
val is 1
val is 2
val is [1, 2, (this Collection)]


collection VS Collection VS Collections

Java Garbage Collection

A garbage collector is responsible for
  • allocating memory
  • ensuring that any referenced objects remain in memory, and
  • recovering memory used by objects that are no longer reachable from references in executing code.

Space is allocated by a large space called heap. The JVM's heap stores all objects created by an executing Java program. Objects are created by Java's "new" operator, and memory for new objects is allocated on the heap at run time.

In addition to freeing unreferenced objects, a garbage collector may also combat heap fragmentation. Heap fragmentation occurs through the course of normal program execution. New objects are allocated, and unreferenced objects are freed such that free blocks of heap memory are left in between blocks occupied by live objects

Code for System.gc is as follows

public static void gc() {
Runtime.getRuntime().gc();
}


System.gc() is just more convinient to call/use

freeMem = Runtime.getRuntime().freeMemory();
System.gc();
System.out.println("free memory after running gc(): " + freeMem);


Interesting links
http://chaoticjava.com/posts/garbage-collection-the-comic-panel/
http://chaoticjava.com/posts/how-does-garbage-collection-work/
http://chaoticjava.com/posts/parallel-and-concurrent-garbage-collectors/
http://chaoticjava.com/posts/gc-tips-and-memory-leaks/