Friday, April 22, 2016

java : Why doesn't Map extend Collection? #interview

Why doesn't Map extend Collection?
This was by design. We feel that mappings are not collections and collections are not mappings. Thus, it makes little sense for Map to extend the Collection interface (or vice versa).

If a Map is a Collection, what are the elements? The only reasonable answer is "Key-value pairs", but this provides a very limited (and not particularly useful) Map abstraction. You can't ask what value a given key maps to, nor can you delete the entry for a given key without knowing what value it maps to.

Collection could be made to extend Map, but this raises the question: what are the keys? There's no really satisfactory answer, and forcing one leads to an unnatural interface.

Maps can be viewed as Collections (of keys, values, or pairs), and this fact is reflected in the three "Collection view operations" on Maps (keySet, entrySet, and values). While it is, in principle, possible to view a List as a Map mapping indices to elements, this has the nasty property that deleting an element from the List changes the Key associated with every element before the deleted element. That's why we don't have a map view operation on Lists.

Java : Overloading vs Overriding


Monday, April 11, 2016

HashMap, TreeMap and LinkedHashMap

╔══════════════╦═════════════════════╦═══════════════════╦══════════════════════╗
║   Property   ║       HashMap       ║      TreeMap      ║     LinkedHashMap    ║
╠══════════════╬═════════════════════╬═══════════════════╬══════════════════════╣
║              ║  no guarantee order ║ sorted according  ║                      ║
║   Order      ║ will remain constant║ to the natural    ║    insertion-order   ║
║              ║      over time      ║    ordering       ║                      ║
╠══════════════╬═════════════════════╬═══════════════════╬══════════════════════╣
║  Get/put     ║                     ║                   ║                      ║
║   remove     ║         O(1)        ║      O(log(n))    ║         O(1)         ║
║ containsKey  ║                     ║                   ║                      ║
╠══════════════╬═════════════════════╬═══════════════════╬══════════════════════╣
║              ║                     ║   NavigableMap    ║                      ║
║  Interfaces  ║         Map         ║       Map         ║         Map          ║
║              ║                     ║    SortedMap      ║                      ║
╠══════════════╬═════════════════════╬═══════════════════╬══════════════════════╣
║              ║                     ║                   ║                      ║
║     Null     ║       allowed       ║    only values    ║       allowed        ║
║ values/keys  ║                     ║                   ║                      ║
╠══════════════╬═════════════════════╩═══════════════════╩══════════════════════╣
║              ║   Fail-fast behavior of an iterator cannot be guaranteed       ║
║   Fail-fast  ║ impossible to make any hard guarantees in the presence of      ║
║   behavior   ║           unsynchronized concurrent modification               ║
╠══════════════╬═════════════════════╦═══════════════════╦══════════════════════╣
║              ║                     ║                   ║                      ║
║Implementation║      buckets        ║   Red-Black Tree  ║    double-linked     ║
║              ║                     ║                   ║       buckets        ║
╠══════════════╬═════════════════════╩═══════════════════╩══════════════════════╣
║      Is      ║                                                                ║
║ synchronized ║              implementation is not synchronized                ║
╚══════════════╩════════════════════════════════════════════════════════════════╝


why and when to override hashcode and equals method ?

It is not always necessary to override hashcode and equals. But if you think you need to override one, then you need to override both of them.
Collections such as HashMap and HashSet use the hashcode value of an object to determine how the object should be stored in the collection, and the hashcode is used again to help locate the object in the collection.
Hashing retrieval is a two-step process.
  1. Find the right bucket (using hashCode())
  2. Search the bucket for the right element (using equals() )

What happens when we override only one of them :

Override only hashCode
Imagine you have this
MyClass first = new MyClass("a","first");
MyClass second = new MyClass("a","second");
If you only override hashCode then when you call myMap.put(first,someValue) it takes first, calculates its hashCode and stores it in a given bucket. Then when you call myMap.put(second,someOtherValue) it should replace first with second as per the Map Documentation because they are equal (according to our definition).
But the problem is that equals was not redefined, so when the map hashes second and iterates through the bucket looking if there is an object k such that second.equals(k) is true it won't find any as second.equals(first) will be false.
Override only equals
If only equals is overriden, then when you call myMap.put(first,someValue) first will hash to some bucket and when you call myMap.put(second,someOtherValue) it will hash to some other bucket (as they have a different hashCode). So, although they are equal, as they don't hash to the same bucket, the map can't realize it and both of them stay in the map.

Below is the sample example code :

public class MyClass {

    private final String importantField;
    private final String anotherField;

    public MyClass(final String equalField, final String anotherField) {
        this.importantField = equalField;
        this.anotherField = anotherField;
    }

    public String getEqualField() {
        return importantField;
    }

    public String getAnotherField() {
        return anotherField;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result
                + ((importantField == null) ? 0 : importantField.hashCode());
        return result;
    }

    @Override
    public boolean equals(final Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        final MyClass other = (MyClass) obj;
        if (importantField == null) {
            if (other.importantField != null)
                return false;
        } else if (!importantField.equals(other.importantField))
            return false;
        return true;
    }

}

Wednesday, March 11, 2015

How HashMap works in java #interview

A map is an object that maps keys to values and HashMap works on the "principle of hashing".

Hashing is a way to assigning a unique code for any variable/object after applying any formula/algorithm on its properties.
Hash function should return the same hash code each and every time, when function is applied on same or equal objects. In other words, two equal objects must produce same hash code consistently.

hashCode() and equals() methods have been defined in Object class which is parent class for java objects. For this reason, all java objects inherit a default implementation of these methods.

Usage of hashCode() and equals()

hashCode() method is used to get a unique integer for given object. This integer is used for determining the bucket location, when this object needs to be stored in some HashTable like data structure. By default, Object’s hashCode() method returns and integer representation of memory address where object is stored.

equals() method, as name suggest, is used to simply verify the equality of two objects. Default implementation simply check the object references of two objects to verify their equality.
  • Entry Class in HashMap 
    • HashMap has an inner class Entry.Entry class has key and value mapping stored as attributes. Key has been marked as final and two more fields are there: next and hash.
      Before going into put() method’s implementation, it is very important to learn that instances of Entry class are stored in an array. HashMap class defines this variable as:



      transient Entry[] table;
      put() method of HashMap
      Parameters:

          key key with which the specified value is to be associated
          value value to be associated with the specified key
      Returns:
          the previous value associated with key, or null if there was no mapping for key. (A null return can also indicate that the map previously associated null with key.)


      Step 1: key object is checked for null. If key is null, value is stored in table[0] position. Because hash code for null is always 0.
      Step 2
      : hash value is calculated using key’s hash code by calling its hashCode() method.This hash value is used to calculate index in array for storing Entry object .
      Step 3
      : indexFor(hash, table.length) function is called to calculate exact index position for storing the Entry object.
      Step 4:
      Now, as we know that two unequal objects can have same hash code value, how two different objects will be stored in same array location [called bucket].
      Answer is LinkedList. If you remember, Entry class had an attribute “next”. This attribute always points to next object in chain. This is exactly the behavior of LinkedList.
      • So, in case of collision, Entry objects are stored in LinkedList form. When an Entry object needs to be stored in particular index, HashMap checks whether there is already an entry?? If there is no entry already present, Entry object is stored in this location.
      • If there is already an object sitting on calculated index, its next attribute is checked. If it is null, and current Entry object becomes next node in LinkedList. If next variable is not null, procedure is followed until next is evaluated as null.
      • What if we add the another value object with same key as entered before. Logically, it should replace the old value. How it is done? Well, after determining the index position of Entry object, while iterating over LinkedList on calculated index, HashMap calls equals method on key object for each Entry object. All these Entry objects in LinkedList will have similar hash code but equals() method will test for true equality. If key.equals(k) will be true then both keys are treated as same key object. This will cause the replacing of value object inside Entry object only.
       
      get() method of HashMap

      Now we have got the idea, how key-value pairs are stored in HashMap. Next big question is : what happens when an object is passed in get method of HashMap? How the value object is determined?

      Answer we already should know that the way key uniqueness is determined in put() method , same logic is applied in get() method also. The moment HashMap identify exact match for the key object passed as argument, it simply returns the value object stored in current Entry object.

      If no match is found, get() method returns null.

      code is same as put() method till if (e.hash == hash && ((k = e.key) == key || key.equals(k))), after this simply value object is returned.


      *Hash tables deal with collisions in one of two ways*

      1. By having each bucket contain a linked list of elements that are hashed to that bucket. This is why a bad hash function can make lookups in hash tables very slow.
      2. If the hash table entries are all full then the hash table can increase the number of buckets that it has and then redistribute all the elements in the table. The hash function returns an integer and the hash table has to take the result of the hash function and mod it against the size of the table that way it can be sure it will get to bucket. so by increasing the size it will rehash and run the modulo calculations which if you are lucky might send the objects to different buckets.

      Java uses both option 1 and 2 in its hash table implementations.

      source: grepcode, HowtodoinJava ,Stackoverflow






Monday, February 16, 2015

How System.out.println() actually works in java ? #interview

System is a class name( class name begin with capital letter according to naming convention).
System is a final class,  and among it's functionality, are standard input, standard output and error output streams.

 out is a (public static final) variable of type PrintStream declared in the System class. PrintStream is another class.

Out is a static final member of the System class, and it's type is PrintStream. It is your standard output stream, that is ready to accept the output data to be sent to a console or any other destination.

 println() is an overloaded method defined in the PrintStream class.


So System class would be something like

class System
{
public static final PrintStream out;
//other things
}

and the PrintStream class

 class PrintStream
{
//variables defined
public void println()
{
//things it does
}

}


Java Reflection and its usage. #interview

The name reflection is used to describe code which is able to inspect other code in the same system (or itself).
Reflection is a key mechanism to allow an application or framework to work with code that might not have even been written yet! Reflection allows instantiation of new objects, invocation of methods, and get/set operations on class variables dynamically at run time without having prior knowledge of its implementation.

For example: say you have an object of an unknown type in Java, and you would like to call a 'doSomething' method on it if one exists. Java's static typing system isn't really designed to support this unless the object conforms to a known interface, but using reflection, your code can look at the object and find out if it has a method called 'doSomething' and then call it if you want to.

imagine the object in question is foo
Method method = foo.getClass().getMethod("doSomething", null);
method.invoke(foo, null);
One very common use case in Java is the usage with annotations. JUnit 4, for example, will use reflection to look through your classes for methods tagged with the @Test annotation, and will then call them when running the unit test.


Reflection is important since it lets you write programs that does not have to "know" everything at compile time, making them more dynamic, since they can be tied together at runtime. The code can be written against known interfaces, but the actual classes to be used can be instantiated using reflection from configuration files.

Usage :Java reflection is useful while writing frameworks and all, spring seems to use it.
Reflection is usually slower then statically compiled methods, you loose compile time type safety.
Everywhere you want to be able to dynamically plug in classes into your code. Lot's of object relational mappers use reflection to be able to instantiate objects from databases without knowing in advance what objects they're going to use. Plug-in architectures is another place where reflection is usefull. Being able to dynamically load code and determine if there are types there that implement the right interface to use as a plugin is important in those situations

Classloader in java and working. #interview

The Java Classloader is a part of the JRE that dynamically loads Java classes into the JVM. Usually classes are only loaded on demand. The Java run time system does not need to know about files and file systems because of classloaders.
Each Java class must be loaded by a class loader.


When the JVM is started, three class loaders are used:
(1) Bootstrap class loader:It loads the core Java libraries located in the <JAVA_HOME>/jre/libdirectory. Bootstrap class loade part of the core JVM and written in native code.
(2) Extensions class loader:It loads the code in the extensions directories (<JAVA_HOME>/jre/lib/ext, or any other directory specified by the java.ext.dirs system property)
(3)System class loader:It loads code found on java.class.path, which maps to the CLASSPATH.
Whenever a new JVM is started the bootstrap classloader is responsible to load key Java classes (from java.lang package) and other runtime classes to the memory first. The bootstrap classloader is a parent of all other classloaders. Consequently, it is the only one without a parent.
Next comes the extension classloader. It has the bootstrap classloader as parent and is responsible for loading classes from all .jar files kept in the java.ext.dirs path–these are available regardless of the JVM’s classpath.
The third and most important classloader from a developer’s perspective is the system classpath classloader, which is an immediate child of the extension classloader. It loads classes from directories and jar files specified by the CLASSPATH environment variable, java.class.path system property or -classpath command line option.





overloading the main method in Java? #interview

As all of you are familiar with concept of polymorphism/overloading and overriding methods in Java. In case need more polymorphism rules refer Click here...


You can overload the main() method, but only public static void main(String[] args) will be used when your class is launched by the JVM.
For example:
public class Test1 {
    public static void main(String[] args) {
        System.out.println("main(String[] args)");
    }

    public static void main(String arg1) {
        System.out.println("main(String arg1)");
    }

    public static void main(String arg1, String arg2) {
        System.out.println("main(String arg1, String arg2)");
    }
}
That will always print main(String[] args) when you run java Test1 ... from the command line, even if you specify one or two command-line arguments.
You can call the main() method yourself from code, of course - at which point the normal overloading rules will be applied.

Friday, November 14, 2014

public static void main in java


.
Why the word static is used in “public static void main(String arg[])” ?
When we enter the command “java HelloWorld psg”. Internally this command is converted to HelloWorld.main(“psg”).
We are trying to invoke the main function using class name. We are trying to invoke the main function without creating an object of HelloWorld class. Due to this reason we have to declare the main function as static.
.
Why the word void is used in “public static void main(String arg[])” ?
This means the main function does not return anything.
.
Why the word main is used in “public static void main(String arg[])” ?
When we enter the command “java HelloWorld psg”. Internally this command is converted to HelloWorld.main(“psg”).
The JVM will definitely will look for a main function in HelloWorld class.
Hence the method name must be “main”.

Thursday, November 28, 2013

What are the essential skills of a Java/J2EE or Enterprise Java developer?

According to me if you are seeking to be a really effective JEE Developer, these are the following skills I would recommend.
Technical

  • Knowledge of OOPs concepts.
  • Basic knowledge of how JVM works and concepts like hashing.
  • At least one framework( Struts or Spring).
  • JSP and one scripting language(Javascript,/JQuery). I would advise you to get a good grip on HTML/XHTML fundamentals too. Clients nowadays are very particular about UI design.
  • EJB( knowledge of CORBA would be a bonus).
  • At least one application server( Weblogic/Websphere/JBoss) you should be having some knowledge about.
  • Web Services, considering many organizations are switching to it, as a better alternative to EJB's.
  • One ORM tool like Hibernate.
  • Knowledge of one configuration management tool like CVS/SVN/Mantis/Accurev.
  • Knowledge of any build tool like ANT/Maven.
  • Unit testing tools like JUnit.
  • Good idea about open source tools available on the Net.
  • Knowledge of design patterns.

Overall, a really good JEE developer should be having a holistic knowledge of the whole application development process. The good old days, when candidates who just knew how to program Hello World in Java, were recruited, are gone.

Non Technical 

  • Communication skills is a must, you will be interacting with clients, your managers, QA team, and effective communication will go a long way, especially in a networked environment.
  • Good presentation skills, these would come in handy, when you seek to do a walk through with the client or  explain a new tool to the team.
/Deepak Pandey

Creating mirror of BST