Thursday, June 28, 2012

Online Java Simple Editor

Here is the simple and user friendly Online Java Editor/IDE.  - Compilr
Below here we can see the sample code which is ready to RUN.














After running the sample code, we can the output on console



Wednesday, June 27, 2012

How HashMap works in Java

A collection allows key+value pair and
HashMap accept null while Hashtable doesn't.
HashMap is not synchronized, hashMap is fast, etc.,
Hashtable based implementation of the Map interface. This implementation provides all of the optional map operations, and permits null values and the null key. (The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls.) This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.

Do you Know how HashMap works in Java
or
How does get () method of HashMap works in Java

HashMap works on principle of hashing, we have put () and get () method for storing and retrieving data from HashMap. When we pass an object to put () method to store it on HashMap, it's implementation calls hashcode() method by applying that hashcode on its own hashing funtion it identifies a bucket location for storing key+value pair, important part here is HashMap stores both key+value in bucket which is essential to understand the retrieving logic.

What will happen if two different objects have same hashcode?

Remember, equals and hashCode() contract that two unequal object in Java very much can have equal hashcode.
"Since hashcode () is same, bucket location would be same and collision occurs in hashMap,
Since HashMap use a linked list to store in bucket, value object will be stored in next node of linked list.
How will you retrieve if two different objects have same hashcode?

get() method uses keys hashcode to find bucket location and retrieves value object.
In the case of collision that there are two objects are stored in same bucket, by traversal in linked list until it will find the value object.

















 Collision resolution -

1. Chaining :

Hash collision resolved by chaining.





2. Open addressing :

Hash collision resolved by linear probing (interval=1).

Hashtable
HashMap
Introduced with JDK 1.0 version, the starting version of Java
Introduced with JDK 1.2
Part of legacy classes (the data structures of JDK 1.0 are known as legacy classes)
Methods of Hashtable are synchronized by default
Methods are not synchronized by default
Does not permit null values (trying to add, throwsNullPointerException)
Permits null values (either key or value)
Enumeration interface is used for iterating keys
Iterator is used for iterating the keys
Enumerator is not fail-fast
Iterator is fail-fast
Safe for multithreaded applications
Better for non-threaded applications
Low performance due to synchronization
High performance
Hashtable is serialized
HashMap is not serialized



Friday, June 22, 2012

User Defined Immutable Class - in short


/**
 * Code snippet to make user defined class as Immutable.
 *
 * Don't provide "setter" methods — methods that modify fields or objects referred to by fields.
 * Make all fields final and private.
 * Don't allow subclasses to override methods. The simplest way to do this is to declare the class as final.
 * A more sophisticated approach is to make the constructor private and construct instances in factory methods.
 * If the instance fields include references to mutable objects, don't allow those objects to be changed:
Don't provide methods that modify the mutable objects.
Don't share references to the mutable objects. Never store references to external,
mutable objects passed to the constructor; if necessary, create copies, and store references to the copies.
Similarly, create copies of your internal mutable objects when necessary to avoid returning the originals in your methods.
 */
package com;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author Thanooj
 *
 */

final class MyImmutableClass {

private final String firstName;
private final String lastName;
private List namesList;

public MyImmutableClass(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
this.namesList = new ArrayList();
this.namesList.add(this.firstName);
this.namesList.add(this.lastName);
}

public MyImmutableClass(String afirstName, String aLastName, String agender) {
this.firstName = afirstName;
this.lastName = aLastName;
this.namesList = new ArrayList();
if (agender.equalsIgnoreCase("MISS")) {
this.namesList.add("Miss.");
} else if (agender.equalsIgnoreCase("MISSES")) {
this.namesList.add("Misses.");
} else if (agender.equalsIgnoreCase("M")
|| agender.equalsIgnoreCase("MALE")) {
this.namesList.add("Mr.");
} else {
// nothing TO DO
}
this.namesList.add(this.firstName);
this.namesList.add(this.lastName);
}

public final String getFirstName() {
return firstName;
}

public final String getLastName() {
return lastName;
}

public final List getNamesList() {
/**
* Returns an unmodifiable view of the specified list. This method
* allows modules to provide users with "read-only" access to internal
* lists. if still we try to add elements into this List then it will
* throw an Exception - java.lang.UnsupportedOperationException at java
* .util.Collections$UnmodifiableCollection.add(Collections.java:1018)
*/
return Collections.unmodifiableList(namesList);
}

@Override
public String toString() {
StringBuilder nameBuilder = new StringBuilder();
for (String name : namesList)
nameBuilder = nameBuilder.append(name + " ");
return nameBuilder.toString();
}

}

public class ImmutableObjects {

/**
* @param args
*/
public static void main(String[] args) {

MyImmutableClass myImmutableClassOne = new MyImmutableClass("Srirama",
"Raghu", "M");
System.out.println(myImmutableClassOne);
MyImmutableClass myImmutableClassTwo = new MyImmutableClass("seeta",
"Raghu", "MISSES");
System.out.println(myImmutableClassTwo);
MyImmutableClass myImmutableClassThree = new MyImmutableClass(
"Lakhmana", "Raghu");
System.out.println(myImmutableClassThree);

  List names = myImmutableClassOne.getNamesList();
/**
* trying to add an element to an UnmodifiableCollection.
*/
names.add("throwAnException");

}

}
                                                           // Output :

Wednesday, June 13, 2012

write a Marker interface

package com.example;
interface MarkerInterface {}
Here you have one. Just copypaste it into com/example/MarkerInterface.java, compile and use it!
Here's an usage example:

class SomeClass implements MarkerInterface {
    // ...
}

But, 
You cannot create a marker interface that will have meaning to the JVM, like the java.io.Serializable interface does. However you could create a marker interface that you check for in your own code using instanceof.
However using marker interfaces in this manner is generally discourage now that we have annotations. Marking class methods and fields in various ways for later processing at compile time using the Annotation Processing Tool (apt) or at runtime using reflection is what annotations were created for.
So rather than creating a marker interface and using it like so:
class MyClass implements MyMarkerInterface {
}
You should probably create an annotation and use it like so:
@MyAnnotation
class MyClass {
}
 
---------------------------
The JRE wouldn't know anything about your marker 
interface, so any special treatment would have to happen in the code you
 write. Probably in sections such as 
"if (someObject instanceof 
ExampleMarker) { ... }".

 

 You shouldn't create marker interfaces, though. 
That's what annotations are used for these days.
                             

Tuesday, June 12, 2012

Garbage Collection - finalize()

Syntax (JDK 1.3)
protected void finalize() throws Throwable {}
  • every class inherits the finalize() method from java.lang.Object
  • the method is called by the garbage collector when it determines no more references to the object exist
  • the Object finalize method performs no actions but it may be overridden by any class
  • normally it should be overridden to clean-up non-Java resources ie closing a file
  • if overridding finalize() it is good programming practice to use a try-catch-finally statement and to always call super.finalize() (JPL pg 47-48). This is a saftey measure to ensure you do not inadvertently miss closing a resource used by the objects calling class

protected void finalize() throws Throwable { try {

close  (); // close open files} finally { super.finalize(); }
}


any exception thrown by finalize() during garbage collection halts the finalization but is otherwise ignored
  • finalize() is never run more than once on any object