Labels

.NET Job Questions About Java Absract class Abstract class Abstract Class and Interface Aggregation ajax aop apache ofbiz Apache ofbiz tutrial Association authentication autocad basics batch Binary Tree bootstrap loader in java build Builder design pattern C++ Job Questions caching CallableStatement in java certifications Chain of responsibility Design pattern charts check parentheses in a string Classes classloader in java classloading concept code quality collage level java program Composition concurrency Concurrency Tutorial Converting InputStream to String Core Java core java concept core java interview questions Core Java Interview Questions Core Java Questions core java tutorial CyclicBarrier in Java data structures database Database Job Questions datetime in c# DB Db2 SQL Replication deserialization in java Design Patterns designpatterns Downloads dtd Eclipse ejb example/sample code exception handling in core java file handling injava File I/O vs Memory-Mapped Filter first program in spring flex Garbage Collection Generics concept in java grails groovy and grails Guice Heap hibernate Hibernate Interview Questions how-to IBM DB2 IBM DB2 Tutorial ide immutable Interceptor Interface interview Interview Questions for Advanced JAVA investment bank j2ee java JAVA Code Examples Java 7 java changes java class loading JAVA Classes and Objects Java Classloader concept Java classloading concept java cloning concept java collection Java collection interview questions Java Collections java concurrency Java CountDownLatch java definiton Java design pattern Java EE 5 Java EE 6 Java Exceptions Java file Java Garbage Collection Java generics Java Glossary java hot concept java immutable concept Java Interface Java interview Question java interview question 2012 java interview question answer Java Interview Questions Java Interview Questions and Answers java interview topic java investment bank Java Job Questions java multithreading java multithreading concept java new features Java Packages java proxy object java questions Java Serialization Java serialization concept java serialization interview question java session concept java string Java Swings Questions java synchronization java threading Java Threads Questions java tutorial java util; java collections; java questions java volatile java volatile interview question Java Wrapper Classes java.java1.5 java.lang.ClassCastException JavaNotes javascript JAX-WS jdbc JDBC JDBC Database connection jdk 1.5 features JDK 1.5 new features Concurrent HashMap JMS interview question JMS tutorial job JSESSIONID concept JSESSIONID interview Question JSF jsp JSP Interview Question JSP taglib JSTL with JSP Junit Junit Concept Junit interview question.Best Practices to write JUnit test cases in Java JVM Linux - Unix tutorial Marker Interfaces MD5 encryption and decryption messaging MNC software java interview question musix NCR java interview question Networking Job Questions news Object Serialization Objects ojdbc14.jar OOP Oracle Oracle SQL Query for two timestamp difference orm own JavaScript function call in Apache ofbiz Packages Palm Apps patterns pdf persistence Portal Portlet Spring Integration Prime number test in java programs Rails Reboot remote computers REST Ruby Sample application schema SCJP security Senior java developer interviews servlet3 servlets session tracking singleton design pattern Spring Spring 2.5 Framework spring ebook Spring framework concept spring MVC spring pdf Spring Security Spring Security interview questions SQL SQL performance SQL Query to create xml file Sql Query tuning ssis and ssrs StAX and XML string concept string immutable string in java strings struts Struts2 Struts2 integration synchronization works in java Technical Interview testing tips Tomcat top Tutorial Volatile in deep Volatile working concept web Web Developer Job Questions web services weblogic Weblogic Application Server websphere what is JSESSIONID xml XML parsing in java XML with Java xslt


Showing posts with label Java Collections. Show all posts
Showing posts with label Java Collections. Show all posts

Wednesday, 24 July 2013

How does HashMap works

HashMap has a number of "buckets" which it uses to store key-value pairs in. Each bucket has a unique number - that's what identifies the bucket. When you put a key-value pair into the map, the hashmap will look at the hash code of the key, and store the pair in the bucket of which the identifier is the hash code of the key. For example: The hash code of the key is 235 -> the pair is stored in bucket number 235. (Note that one bucket can store more then one key-value pair).


When you lookup a value in the hashmap, by giving it a key, it will first look at the hash code of the key that you gave. The hashmap will then look into the corresponding bucket, and then it will compare the key that you gave with the keys of all pairs in the bucket, by comparing them with equals().
Now you can see how this is very efficient for looking up key-value pairs in a map: by the hash code of the key the hashmap immediately knows in which bucket to look, so that it only has to test against what's in that bucket.
Looking at the above mechanism, you can also see what requirements are necessary on thehashCode() and equals() methods of keys:
  • If two keys are the same (equals() returns true when you compare them), their hashCode()method must return the same number. If keys violate this, then keys that are equal might be stored in different buckets, and the hashmap would not be able to find key-value pairs (because it's going to look in the same bucket).
  • If two keys are different, then it doesn't matter if their hash codes are the same or not. They will be stored in the same bucket, but the hashmap will use equals() to tell them apart.
References:

    Friday, 5 July 2013

    What is the difference between Enumeration and Iterator?


    The functionality of Enumeration interface is duplicated by the Iterator interface. Iterator has a remove() method while Enumeration doesn't. Enumeration acts as Read-only interface, because it has the methods only to traverse and fetch the objects, where as using Iterator we can manipulate the objects also like adding and removing the objects.

    So Enumeration is used when ever we want to make Collection objects as Read-only.


    What method should the key class of Hashmap override?


    The methods to override are equals() and hashCode().


    Can you limit the initial capacity of vector in java?


    Yes you can limit the initial capacity. We can construct an empty vector with specified initial capacity

    public vector(int initialcapacity)


    What is difference between array & arraylist?


    An ArrayList is resizable, where as, an array is not. ArrayList is a part of the Collection Framework. We can store any type of objects, and we can deal with only objects. It is growable. Array is collection of similar data items. We can have array of primitives or objects. It is of fixed size. We can have multi dimensional arrays.

    Array: can store primitive ArrayList: Stores object only

    Array: fix size ArrayList: resizable

    Array: can have multi dimensional

    Array: lang ArrayList: Collection framework

    What are differences between Enumeration, ArrayList, Hashtable and Collections and Collection?


    Enumeration: It is series of elements. It can be use to enumerate through the elements of a vector, keys or values of a hashtable. You can not remove elements from Enumeration.

    ArrayList: It is re-sizable array implementation. Belongs to 'List' group in collection. It permits all elements, including null. It is not thread -safe.

    Hashtable: It maps key to value. You can use non-null value for key or value. It is part of group Map in collection.

    Collections: It implements Polymorphic algorithms which operate on collections.

    Collection: It is the root interface in the collection hierarchy.

    How can we use hashset in collection interface?


    This class implements the set interface, backed by a hash table (actually a HashMap instance). It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. This class permits the Null element.

    This class offers constant time performance for the basic operations (add, remove, contains and size), assuming the hash function disperses the elements properly among the buckets.


    Which implementation of the List interface provides for the fastest insertion of a new element into the middle of the list?


    a. Vector
    b. ArrayList
    c. LinkedList
    d. None of the above

    ArrayList and Vector both use an array to store the elements of the list. When an element is inserted into the middle of the list the elements that follow the insertion point must be shifted to make room for the new element. The LinkedList is implemented using a doubly linked list; an insertion requires only the updating of the links at the point of insertion. Therefore, the LinkedList allows for fast insertions and deletions.


    What is the Properties class?


    The properties class is a subclass of Hashtable that can be read from or written to a stream. It also provides the capability to specify a set of default values to be used.


    What is the Map interface?


    The Map interface is used associate keys with values.

    What’s the difference between a queue and a stack?


    Stack is a data structure that is based on last-in-first-out rule (LIFO), while queues are based on First-in-first-out (FIFO) rule.


    What is the Set interface?


    The Set interface provides methods for accessing the elements of a finite mathematical set. Sets do not allow duplicate elements.


    How can we access elements of a collection?


    We can access the elements of a collection using the following ways:
    1.Every collection object has get(index) method to get the element of the object. This method will return Object.
    2.Collection provide Enumeration or Iterator object so that we can get the objects of a collection one by one.


    What is the List interface?


    The List interface provides support for ordered collections of objects.


    What is the Collections API?


    The Collections API is a set of classes and interfaces that support operations on collections of objects.
    Example of classes: HashSet, HashMap, ArrayList, LinkedList, TreeSet and TreeMap.
    Example of interfaces: Collection, Set, List and Map.


    What is an Iterator interface? Is Iterator a Class or Interface? What is its use?


    The Iterator is an interface, used to traverse through the elements of a Collection. It is not advisable to modify the collection itself while traversing an Iterator.


    Difference between Vector and ArrayList? What is the Vector class?


    Vector is synchronized whereas ArrayList is not. The Vector class provides the capability to implement a growable array of objects. ArrayList and Vector class both implement the List interface. Both classes are implemented using dynamically resizable arrays, providing fast random access and fast traversal. In vector the data is retrieved using the elementAt() method while in ArrayList, it is done using the get() method. ArrayList has no default size while vector has a default size of 10. when you want programs to run in multithreading environment then use concept of vector because it is synchronized. But ArrayList is not synchronized so, avoid use of it in a multithreading environment.


    What is the difference between set and list?


    A Set stores elements in an unordered way and does not contain duplicate elements, whereas a list stores elements in an ordered way but may contain duplicate elements.


    Difference between HashMap and HashTable? Can we make hashmap synchronized?


    Java Interview Questions site discussing core java IT technical interview questions in detail. These are some of the java job interview questions me and my friends have faced regularly in campus interviews and off campuses. I have consolidated all of them from different people and communities into a vast resource of core java interview questions all in one place. So I am giving you a chance to prepare well by going through each of the java interview faqs organized by java topics, before attending a technical interview on java.





    Java Collections Interview Questions
    What is HashMap and Map?

    Map is Interface and Hashmap is class that implements this interface.

    What is the significance of ListIterator?

    Or

    What is the difference b/w Iterator and ListIterator?

    Iterator : Enables you to cycle through a collection in the forward direction only, for obtaining or removing elements

    ListIterator : It extends Iterator, allow bidirectional traversal of list and the modification of elements

    Difference between HashMap and HashTable? Can we make hashmap synchronized?

    1. The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesn’t allow nulls).
    2. HashMap does not guarantee that the order of the map will remain constant over time.
    3. HashMap is non synchronized whereas Hashtable is synchronized.
    4. Iterator in the HashMap is fail-safe while the enumerator for the Hashtable isn't.

    Note on Some Important Terms
    1)Synchronized means only one thread can modify a hash table at one point of time. Basically, it means that any thread before performing an update on a hashtable will have to acquire a lock on the object while others will wait for lock to be released.

    2)Fail-safe is relevant from the context of iterators. If an iterator has been created on a collection object and some other thread tries to modify the collection object "structurally”, a concurrent modification exception will be thrown. It is possible for other threads though to invoke "set" method since it doesn’t modify the collection "structurally”. However, if prior to calling "set", the collection has been modified structurally, "IllegalArgumentException" will be thrown.

    HashMap can be synchronized by

    Map m = Collections.synchronizeMap(hashMap);



    What is the significance of ListIterator?


    Or

    What is the difference b/w Iterator and ListIterator?

    Iterator : Enables you to cycle through a collection in the forward direction only, for obtaining or removing elements

    ListIterator : It extends Iterator, allow bidirectional traversal of list and the modification of elements


    LinkWithin

    Related Posts Plugin for WordPress, Blogger...