Description

Java Reference books: 1) Java Programming Interviews Exposed - Feb 2014 2) Core Java Career Essentials EditionFirst EditionPublished October 12, 2013 LanguageEnglishPages542File FormatPDFFile Size7.42 MB 3) Java/JEE Resume Companion - Published March 11, 2013 EditionSecond EditionPublisherSivayini & ArulkumaranPublished October 27, 2013 http://www.geeksforgeeks.org/java/ https://www.hackerrank.com/ careercup.com http://javahungry.blogspot.com/ What is ClassLoader in Java ClassLoader in Java is a class which is used to load class files in Java. Java code is compiled into class file by javac compiler and JVM executes Java program, by executing byte codes written in class file. ClassLoader is responsible for loading class files from file system, network or any other source. There are three default class loader used in Java, Bootstrap, Extension and System or Application class loader. Every class loader has a predefined location, from where they loads class files. Bootstrap ClassLoader is responsible for loading standard JDK class files from rt.jar and it is parent of all class loaders in Java. Bootstrap class loader don't have any parents, if you call String.class.getClassLoader() it will return null and any code based on that may throw NullPointerException in Java. Bootstrap class loader is also known as Primordial ClassLoader in Java. Extension ClassLoader delegates class loading request to its parent, Bootstrap and if unsuccessful, loads class form jre/lib/ext directory or any other directory pointed by java.ext.dirs system property. Extension ClassLoader in JVM is implemented by sun.misc.Launcher$ExtClassLoader. Third default class loader used by JVM to load Java classes is called System or Application class loader and it is responsible for loading application specific classes from CLASSPATH environment variable, -classpath or cp command line option, Class-Path attribute of Manifest file inside JAR. Application class loader is a child of Extension ClassLoader and its implemented by sun.misc.Launcher$AppClassLoader class. Also, except Bootstrap class loader, which is implemented in native language mostly in C, all Java class loaders are implemented using java.lang.ClassLoader. How ClassLoader works in Java As I explained earlier Java ClassLoader works in three principles : delegation, visibility and uniqueness. In this section we will see those rules in detail and understand working of Java ClassLoader with example. By the way here is a diagram which explains How ClassLoader load class in Java using delegation. Delegation principles As discussed on when a class is loaded and initialized in Java, a class is loaded in Java, when its needed. Suppose you have an application specific class called Abc.class, first request of loading this class will come to Application ClassLoader which will delegate to its parent Extension ClassLoader which further delegates to Primordial or Bootstrap class loader. Primordial will look for that class in rt.jar and since that class is not there, request comes to Extension class loader which looks on jre/lib/ext directory and tries to locate this class there, if class is found there than Extension class loader will load that class and Application class loader will never load that class but if it’s not loaded by extension class-loader than Application class loader loads it from Classpath in Java. Remember Classpath is used to load class files while PATH is used to locate executable like javac or java command. Visibility Principle According to visibility principle, Child ClassLoader can see class loaded by Parent ClassLoader but vice-versa is not true. Which mean if class Abc is loaded by Application class loader than trying to load class ABC explicitly using extension ClassLoader will throw either java.lang.ClassNotFoundException. as shown in below Example package test; import java.util.logging.Level; import java.util.logging.Logger; /** * Java program to demonstrate How ClassLoader works in Java, * in particular about visibility principle of ClassLoader. * * @author Javin Paul */ public class ClassLoaderTest { public static void main(String args[]) { try { //printing ClassLoader of this class System.out.println("ClassLoaderTest.getClass().getClassLoader() : " + ClassLoaderTest.class.getClassLoader()); //trying to explicitly load this class again using Extension class loader Class.forName("test.ClassLoaderTest", true , ClassLoaderTest.class.getClassLoader().getParent()); } catch (ClassNotFoundException ex) { Logger.getLogger(ClassLoaderTest.class.getName()).log(Level.SEVERE, null, ex); } } } Output: ClassLoaderTest.getClass().getClassLoader() : sun.misc.Launcher$AppClassLoader@601bb1 16/08/2012 2:43:48 AM test.ClassLoaderTest main SEVERE: null java.lang.ClassNotFoundException: test.ClassLoaderTest at java.net.URLClassLoader$1.run(URLClassLoader.java:202) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:190) at sun.misc.Launcher$ExtClassLoader.findClass(Launcher.java:229) at java.lang.ClassLoader.loadClass(ClassLoader.java:306) at java.lang.ClassLoader.loadClass(ClassLoader.java:247) at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Class.java:247) at test.ClassLoaderTest.main(ClassLoaderTest.java:29) Uniqueness Principle According to this principle a class loaded by Parent should not be loaded by Child ClassLoader again. Though its completely possible to write class loader lang. since Applets are mostly loaded from internet rather than local file system.class instance which is returned to the caller. You should follow all class loader principle while writing your own ClassLoader.ClassLoader class which calls findClass() method to locate bytecodes for corresponding class.forName(classname. How to load class explicitly in Java Java provides API to explicitly load a class by Class. In this example Extension ClassLoader uses java. HashMap & HashSet and how do they internally work? What is a hashing function? Q1. any search path which is ended using "/" is considered directory. You can also use ClassLoader to load classes from database or any other persistent store.URLClassLoader which search for class files and resources in JAR and directories. Class is loaded by calling loadClass() method of java.ClassNotFoundException and if it finds it calls defineClass() to convert bytecodes into a . As shown in above example you can pass name of ClassLoader which should be used to load that particular class along with binary name of class. Q3 How does a HashMap internally store data? .which violates Delegation and Uniqueness principles and loads class by itself. You can store and retrieve values with the keys.net. On average it is O(1) if the hashCode() method spreads out the buckets as discussed below. initialized. How does a HashMap store data? A1. What is the HashMap lookup time in Big O notation? A2.lang. J2EE uses multiple class loaders to load class from different location like classes from WAR file will be loaded by Web-app ClassLoader while classes bundled in EJB-JAR is loaded by another class loader. By using separate ClassLoader you can also loads same class from multiple sources and they will be treated as different class in JVM.forName(classname) and Class. It is O(n) = O(k * n). classloader) remember JDBC code which is used to load JDBC drives we have seen in Java program to Connect Oracle database. Where to use ClassLoader in Java ClassLoader in Java is a powerful concept and used at many places. Q2. its not something which is beneficial. One of the popular example of ClassLoader is AppletClassLoader which is used to load class by Applet. Some web server also supports hot deploy functionality which is implemented using ClassLoader. As key/value pairs. If findClass() does not found the class than it throwsjava. Two different keys can return the same hash value. In the above example. A backing array for the buckets and a linked list to store key/value pairs. let’s assume that (“John”. 1) When you put an object into a map with a key and a value.A3. 01/01/1995) key return the same hash value of 123. hashCode() method is implicitly invoked. Backing Array with buckets: as shown below.01/01/1956) key and (“Peter”. A good hashing algorithm spreads out the numbers. and hash code value say 123 is returned. . This function in a very simple explanation is like hashCode() % capacity 123 % 10 = 3 456 % 10 = 6 This means the “hashcode = 123” gets stored in index 3 in the backing array. int length) methods. Once the HashMap reaches its 75% of the capacity indicated by the default hash factor of 0. So you get numbers between 0 and 9 for the capacity of 10.75. This is known as the hashing function.2) Now when a hashCode value of say 123 is returned and the initial HashMap capacity is say 10. the backing array’s capacity is doubled and the rehashing takes place to reallocate the buckets for the new capacity of 20. how does it know which index of the backing array to store it in? This is where the HashMap internally invokes the hash(int ) & indexFor(int h. . its implementation uses a). the key/value pairs are stored as linked list. h ^= (h >>> 20) ^ (h >>> 12). 01/01/1995” in the above example. 01/01/1956”? This is where you key class’s equals() method gets invoked. static int indexFor(int h. (123 & 0x7FFFFFFF) % 20 = 3 (456 & 0x7FFFFFFF) % 20 = 16 This ensures that you get a positive index value.e. 01/01/1956” & “Peter. For example. 01/01/1956” by using the equals() method to . int length) { return h & (length-1).hashCode() % capacity 123 % 20 = 3 456 % 20 = 16 Now the above modulus operator approach of rehashing has a flaw. What if the hashCode is a negative number? You don’t want a negative index. Hence. “John. %) operator. So. It is important to understand that two different keys can result in the same hashcode say 123. } Actual name value pairs are stored as a key/value pair LinkedList As shown in the diagram. return h ^ (h >>> 7) ^ (h >>> 4). an improved hashing formula would be to shift out the sign bit and then calculate the remainder with the modulus (i. Determine the index based on the hashCode and capacity. If you look at the Java 8 HashMap source code. } b). Protect against poorer hashes by only extracting the important lower bits. how do you retrieve just “John. and get stored in the same bucket. It loops through the items in the LinkedList bucket “123” to retrieve the key “John. static int hash(int h) { // This function ensures that hashCodes that differ only by // constant multiples at each bit position have a bounded // number of collisions (approximately 8 at default load factor). it is already implemented. you are responsible for properly implementing these methods.println("Set is "+hashset). hashset. If you write your own key class like “MyKey” with name and DOB as the attributes as in “John. } } . Set Implementation Internally in Java Each and every element in the set is unique. So that there is no duplicate element in set. Why is it a good practice to appropriately set the initial capacity of a HashMap? A5. hashset. System. How does a HashSet internally store data? A6. Q5. It stores the element as both key and value.add(3). What is the effect of implementing a poor hashcode() for an object? A7. So in java if we want to add elements in the set then we write code like this public class JavaHungry { public static void main(String[] args) { // TODO Auto-generated method stub HashSet<Object> hashset = new HashSet<Object>().add("Blogspot"). Q6. The invocation of hashCode() method should return different values for different objects. If it returns same values for different objects then this results in more key/value pairs getting stored against the same bucket. If you are using an existing wrapper class like Integer or the String as a key. Q7.find a match. 01/01/1956”.out. To minimize the occurrences of rehashing.add("Java Hungry"). A HashSet internally uses a HashMap. hashset. This is why it is important to implement the hashCode() & equals() method in your key class. This adversely impacts performance of HashMaps & HashSets. add("Java Hungry"). Java Hungry. you will find the following code in it public class HashSet<E> extends AbstractSet<E> implements Set<E>.add("Blogspot").io. hashset. } } It will print the result : Set is [3. But the main problem arises that how it returns false .add("Java Hungry"). hashset. It will return false and do not add to the HashSet .jar .add(3). Blogspot] Now . hashset. Blogspot] Now let add duplicate element in the above code public class JavaHungry { public static void main(String[] args) { HashSet<Object> hashset = new HashSet<Object>(). So here is the answer When you open the HashSet implementation of the add() method in Java Apis that is rt.Serializable . Cloneable. hashset.out.println("Set is "+hashset). as the element is already present . // duplicate elements System.So far so good . // duplicate elements hashset. what happens internally when you pass duplicate elements in the add() method of the Set object .It will print the result : Set is [3.add(3). java. Java Hungry. e Other methods in Hash Set public boolean add(E e) { return map.put(e. As we know in HashMap each key is unique . public HashSet() { map = new HashMap<>(). actually when you are adding a line in HashSet like hashset.i. Now we need to associate some value to the key . // Dummy value to associate with an Object in the backing Map private static final Object PRESENT = new Object(). } // SOME CODE . So . we are achieving uniqueness in Set. Whenever you create an object of HashSet it will create an object of HashMap as you can see in the italic lines in the above code . so what Java apis developer did is to pass the Dummy value that is ( new Object () ) which is referred by Object reference PRESENT .internally in java through HashMap .Object> map.i. We already discussed How HashMap works internally in java . } // SOME CODE .add(3) .{ private transient HashMap<E.e Other methods in Hash Set } So . PRESENT)==null. So what we do in the set is that we pass the argument in the add(Elemene E) that is E as a key in the HashMap . Value V) method . Old Value of the key . if map. if map.then map. in HashSet add() method . PRESENT)==null.put(e. PRESENT)==null will return true and element is added to the HashSet. null .put(key.value) will return 1. Now if you see the code of the HashMap put(Key k.what java does internally is that it will put that element E here 3 as a key in the HashMap(created during HashSet object creation) and some dummy value that is Object's object is passed as a value to the key . you will find something like this public V put(K key. . public boolean add(E e) { return map. we check the return value of map. } So .value) method with null value i. if key is unique and added to the map 2.put(e.then map. PRESENT)==null will return false and element is not added to the HashSet . if key is duplicate So .put(e.value) returns old value of the key . V value) { //Some code } The main point to notice in above code is that put (key. So .e.value) returns null .put(key.put(key. import java. 7. } public static void main(String args[]){ Parent p=new TestExceptionChild().out. 6. 3. 10.out. 14. 8. 1. subclass overridden method cannot declare the checked exception but it can declare unchecked exception.println("parent"). } } Test it Now Output:Compile Time Error .} } class TestExceptionChild extends Parent{ void msg()throws IOException{ System. 9.*.io. class Parent{ void msg(){System. If the superclass method does not declare an exception 1) Rule: If the superclass method does not declare an exception.ExceptionHandling with MethodOverriding in Java ExceptionHandling with MethodOverriding in Java There are many rules if we talk about methodoverriding with exception handling.println("TestExceptionChild"). 5. subclass overridden method cannot declare the checked exception. subclass exception or no exception but cannot declare parent exception. If the superclass method declares an exception o  o If the superclass method declares an exception. 12.msg(). 11. The Rules are as follows:  If the superclass method does not declare an exception If the superclass method does not declare an exception. 13. 2. p. subclass overridden method can declare same. 4. 2.out. class Parent{ void msg()throws ArithmeticException{System. 8. 13.io. 9. 6.msg(). 12. } } Test it Now Output:child If the superclass method declares an exception 1) Rule: If the superclass method declares an exception. 7.println("parent").*.println("parent"). 5. 8. import java. 3.} } class TestExceptionChild2 extends Parent{ void msg()throws Exception{System.} } class TestExceptionChild1 extends Parent{ void msg()throws ArithmeticException{ System. 13. 12. 3. 7.io. 1.out.} public static void main(String args[]){ Parent p=new TestExceptionChild2(). p.println("child").out. 10. 4. 5. } public static void main(String args[]){ Parent p=new TestExceptionChild1(). subclass overridden method can declare same. 4. Example in case subclass overridden method declares parent exception 1. try{ p. }catch(Exception e){} } } Test it Now Output:Compile Time Error . 14. class Parent{ void msg(){System.msg().*. 11.out. 10. 15.2) Rule: If the superclass method does not declare an exception. subclass overridden method cannot declare the checked exception but can declare unchecked exception. 14. import java. 9. 11. 2.println("child"). 6. subclass exception or no exception but cannot declare parent exception. 6.println("parent").*. 6.} } class TestExceptionChild3 extends Parent{ void msg()throws Exception{System. 11. 14. 3. try{ p.io. 4. import java. 4. }catch(Exception e){} } } Test it Now Output:child Example in case subclass overridden method declares no exception 1.println("child"). 9. 8.*.println("parent").} } class TestExceptionChild4 extends Parent{ void msg()throws ArithmeticException{System. class Parent{ void msg()throws Exception{System. 10. import java. class Parent{ void msg()throws Exception{System.msg().msg(). 12. 15.out.Example in case subclass overridden method declares same exception 1.} public static void main(String args[]){ Parent p=new TestExceptionChild4(). 13.println("child"). 14.io.*.out. }catch(Exception e){} } Test it Now Output:child Example in case subclass overridden method declares subclass exception 1. 10. 2. 5.out.} } public static void main(String args[]){ Parent p=new TestExceptionChild3(). 12. 3.io. 9. try{ p. 7. 2. 7.out. 11. 8. 15. 13. import java. . 5. 2.out.e worst case. 10. 7. 2. if array is full i.} } class TestExceptionChild5 extends Parent{ void msg(){System. In LinkedList adding or insertion is O(1) operation.e O(1) while LinkedList get(int index) operation run time is O(n). . 14.println("parent"). }catch(Exception e){} } Test it Now Output:child Next TopicCustom Exception Difference between ArrayList and LinkedList in Java 1. on the other hand.out. try{ p. LinkedList does not provide index based access for its elements as it iterates either from the beginning or end (whichever is closer) to retrieve the node at the specified element index. The reason behind ArrayList being faster than LinkedList is that ArrayList uses index based system for its elements as it internally uses array data structure. 12. 8.println("child"). insert() or add(Object) operation : Insertions in LinkedList are generally fast as compare to ArrayList. 3. b. 5. which makes runtime of add operation in ArrayList O(n). 11. 6. while LinkedList is the Doubly-linked list implementation of the list interface.} } public static void main(String args[]){ Parent p=new TestExceptionChild5(). get (int index) or search operation : ArrayList get(int index) operation runs in constant time i. While in ArrayList. 13. Performance: Performance of ArrayList and LinkedList depends on the type of operation a. 4.msg(). 9. class Parent{ void msg()throws Exception{System. there is extra cost of resizing array and copying elements to the new array. Implementation: ArrayList is the resizable array implementation of list interface. 15. otherwise it is O(1). System. so we need to write our own code to iterate over the ArrayList in reverse direction. public class ArrayListLinkedListExample { public static void main(String[] args) { ArrayList<String> arrlistobj = new ArrayList<String>(). 4. Hence this method run time is O(n).add("2.LinkedList. While in ArrayList each index only holds the actual object(data). LinkedList llobj = new LinkedList(). Memory Overhead: Memory overhead in LinkedList is more as compared to ArrayList as node in LinkedList needs to maintain the addresses of next and previous node. In LinkedList. while LinkedList only constructs the empty list without any initial capacity.e.out. O(n). The other overloaded remove method in LinkedList is remove(int) or remove(Object) which removes the Object or int passed as parameter. Love yourself"). While in ArrayList remove(int) method involves copying elements from old array to new updated array. there are two overloaded remove methods.util.out. Initial Capacity: If the constructor is not overloaded.ArrayList. llobj. arrlistobj. one is remove() without any parameter which removes the head of the list and runs in constant time O(1).println("LinkedList object output :"+llobj). 3. llobj. remove(int) operation : Remove operation in LinkedList is generally same as ArrayList i. Example of ArrayList and LinkedList: import java. } } . Alive is awesome"). Love yourself"). 5. hence its run time is O(n).util. Alive is awesome").println("ArrayList object output :"+ arrlistobj). then ArrayList creates an empty list of initial capacity 10. Reverse Iterator: LinkedList can be iterated in reverse direction using descendingIterator() while there is no descendingIterator() in ArrayList .add("1.c. System.add("2. import java. This method traverses the LinkedList until it found the Object and unlink it from the original list. arrlistobj.add("1. 2. Love yourself] Similarities between ArrayList and LinkedList: 1. 2. 3. they both inherit properties of List.Output: ArrayList object output: [1. Alive is awesome. Not synchronized: Both ArrayList and LinkedList are not synchronized and can be made synchronized explicitly using Collections.e. 2. ArrayList LinkedList Implementatio n Resizable Array Doubly-LinkedList ReverseIterato No Yes . delete(int) operations then the get(int) operations then LinkedList is preferred as they do not need to maintain back and forth like arraylist to preserve continues indices. 1. so. Alive is awesome. clone() operation: Both ArrayList and LinkedList returns a shallow copy of the original object . 4. Insertion Order: As ArrayList and LinkedList are the implementation of List interface. Fail fast iterators throw ConcurrentModificationException.i. . 2. Love yourself] LinkedList object output: [1. If application requires more insert(int) . Iterators: The iterators returned by ArrayList and LinkedList class's iterator and listIterator methods are fail-fast. the elements themselves are not cloned. ArrayList is preferred when there are more get(int) or search operations need to be performed as every search operation runtime is O(1). But in a very specific situations LinkedList can be preferred. They both preserves the order of the elements in the way they are added to the ArrayList or LinkedList object. you will more frequently use ArrayList than LinkedList.synchronizedList() method. When to Use ArrayList and LinkedList: In real world applications. Each ArrayList object has instance variable capacity which indicates the size of the ArrayList. // try to add 23 (primitive) . resize() operation : Automatic resize of ArrayList will slow down the performance as it will use temporary array to copy elements from the old array to new array.add(23). as for ArrayList object these operations run in constant time. ArrayList is dynamic in size.srcPos.r descendingIterator() Initial Capacity 10 Constructs empty list get(int) operation Fast Slow in comparison add(int) operation Slow in comparison Fast Memory Overhead No Yes Difference between Array and ArrayList in Java with Example 1. arraylistobject. ArrayList is internally backed by Array during resizing as it calls the native implemented method System. add() or get() operation : adding an element or retrieving an element from the array or arraylist object has almost same performance. 2. float and double) it can only contains Object while Array can contain both primitive data types as well as objects.float and double) in ArrayList.destPos.arrayCopy(src. Resizable: Array is static in size that is fixed length data structure. As elements are added to an ArrayList its capacity grows automatically. One get a misconception that we can store primitives (int. but it is not true Suppose we have ArrayList object ArrayList arraylistobject = new ArrayList(). b. 3.length). Performance: Performance of Array and ArrayList depends on the operation you are performing: a. one cannot change the length after creating the Array object. Primitives: ArrayList cannot contains primitive data types (like int.dest. . above step internally works like this: arraylistobject. // Converted int primitive to Integer object and added to arraylistobject 4. //uses arrayobject length variable ArrayList arraylistobject = new ArrayList(). Multi-dimensional: Array can be multi-dimensional. one can ensure Type Safety through Generics. The iterators returned by the ArrayList class's iterator and listiterator method are fail-fast. While Array is a homogeneous data structure. Thus. thus it will contain objects of specific class or primitives of specific data type. Iterating the values: We can use iterator to iterate through ArrayList . For example: Integer arrayobject[] = new Integer[3]. arraylistobject. ArrayStoreException is thrown.size(). arraylistobject.JVM through Autoboxing(converting primitives to equivalent objects internally) ensures that only objects are added to the arraylist object. For example: String temp[] = new String[2]. //uses arraylistobject size method 7. Length: Length of the ArrayList is provided by the size() method while Each array object has the length variable which returns the length of the array.add( new Integer(23)). arraylength= arrayobject. In array if one try to store the different data type other than the specified while creating the array object.length . Adding elements: We can insert elements into the ArrayList object using the add() method while in Array we insert elements using the assignment operator. while ArrayList is always single dimensional. addarrayobject[0]= new Integer(8) .add(12). 5. For example: Integer addarrayobject[] = new Integer[3]. Type-Safety: In Java. We can use for loop or for each loop to iterate through array. // throws ArrayStoreException. trying to add Integer object in String[] 6. //new object is added to the array object 8. // creates a string array of size 2 temp[0] = new Integer(12). arrayobj[2]= "Be in Present". Alive is awesome.util. for(int i=0.print(arrayobj[i] + " ").print(it. public class ArrayArrayListExample { public static void main(String[] args) { // ArrayList Example ArrayList<String> arrlistobj = new ArrayList<String>().util. Iterator it = arrlistobj. Love yourself} Array object output :{ Love yourself. System.add("Love yourself").print("Array object output :"). arrlistobj.i++) System. be in present} Similarities between Array and ArrayList .hasNext()) System.out. i < arrayobj.iterator(). while(it.add("Alive is awesome"). } } Output: ArrayList object output :{ Alive is awesome. arrlistobj. addarrayobject[0][0]= new Integer(8) Example of Array and ArrayList import java.out.next() + " "). arrayobj[0]= "Love yourself".Iterator.print("ArrayList object output :").Example of multidimensional array: Integer addarrayobject[][] = new Integer[3][2].out. arrayobj[1]= "Alive is awesome".length . import java.ArrayList.out. System. // Array Example String[] arrayobj = new String[3]. for each Length length variable size method Performance Fast Slow in comparison Multidimensional Yes No Add Elements Assignment operator add method Difference between HashMap and HashTable: 1. in other words hashmap is better for non-threading applications. . When to use HashMap? Answer is if your application do not require any multi-threading task. Duplicate elements: Both array and arraylist can contain duplicate elements. On the other hand. while Hashtable do not allow null keys and null values in the HashTable object. 3.1. HashTable is the only class other than vector which uses enumerator to iterate the values of HashTable object. HashTable is thread safe and synchronized. Iterating the values: Hashmap object values are iterated by using iterator. Null keys and null values: Hashmap allows one null key and any number of null values. Synchronization or Thread Safe: This is the most important difference between two. Null Values: Both can store null values and uses index to refer to their elements. 3. Unordered: Both does not guarantee ordered elements. 4. for each Iterator . 2. HashMap is non-synchronized and not thread safe. Array ArrayList Resizable No Yes Primitives Yes No Iterating values for. 2. 4. Fail-fast iterator: The iterator in Hashmap is fail-fast iterator while the enumerator for Hashtable is not. add and get method : Performance of Array and ArrayList are similar for the add and get operations. HashTable should be used in multithreading applications. Both operations runs in constant time. According to Oracle Docs.7. System. Structural modification means adding or removing elements from the Collection object (here hashmap or hashtable). hashtableobj.put("Love". String>(). It is better off externally synchronizing a HashMap or using a ConcurrentHashMap.println("Hashtable object output :"+ hashtableobj). Thus the enumerations returned by the Hashtable keys and elements methods are not fail fast. so. HashMap hashmapobj = new HashMap(). HashMap is the subclass of the AbstractMap class. System. } } Output: Hashtable object output :{Love=yourself. it is not used anymore. as the order . then the iterator will throw ConcurrentModificationException. Instead use LinkedHashMap. Love=yourself} Similarities between HashMap and Hashtable 1.String> hashtableobj = new Hashtable<String. Superclass and Legacy: Hashtable is a subclass of Dictionary class which is now obsolete in Jdk 1. Insertion Order: Both HashMap and Hashtable does not guarantee that the order of the map will remain constant over time. Alive is =awesome} HashMap object output :{Alive is =awesome. Although Hashtable and HashMap has different superclasses but they both are implementations of the "Map" abstract data type.println("HashMap object output :"+hashmapobj). hashmapobj.put("Alive is ". Performance: Hashmap is much faster and uses less memory than Hashtable as former is unsynchronized. 6. Unsynchronized objects are often much better in performance in compare to synchronized object like Hashtable in single threaded environment. public class HashMapHashtableExample { public static void main(String[] args) { Hashtable<String. "awesome"). 5. "yourself"). hashtableobj.util.Hashtable. Example of HashMap and HashTable: import java.put("Love".out. "awesome"). "yourself"). hashmapobj. if the Hashtable is structurally modified at any time after the iterator is created in any way except the iterator's own remove method.out.put("Alive is ". 8.util. Single Threaded Application: HashMap should be preferred over Hashtable for the non-threaded applications. 3. Internal working: Both HashMap and Hashtable works on the Principle of Hashing. .Any null values Not permit null keys and values Iterator type Fail fast iterator Fail safe iterator Performance Fast Slow in comparison Superclass and Legacy AbstractMap . Map interface: Both HashMap and Hashtable implements Map interface. as the class is now obsolete in latest Jdk 1. use HashMap in unsynchronized or single threaded applications. 2.remains constant over time. Oracle has provided a better replacement of Hashtable named ConcurrentHashMap. Multi-Threaded Application we should avoid using Hashtable. Yes Difference between HashSet and TreeSet 1.HashSet. 2. For multithreaded application prefer ConcurrentHashMap instead of Hashtable. Ordering: HashSet stores the object in random order. In simple words. 4. No Dictionary . There is no guarantee that the element we inserted first in the HashSet will be printed first in the output. When to use HashMap and Hashtable? 1. HashMap Hashtable Synchronized No Yes Thread-Safe No Yes Null Keys and Null values One null key . Put and get method: Both HashMap and Hashtable provides constant time performance for put and get methods assuming that the objects are distributed uniformly across the bucket. For example import java. import java. public class TreeSetExample { public static void main(String[] args) { TreeSet<String> obj1= new TreeSet<String>(). If the objects cannot be sorted in natural order than use compareTo() method to sort the elements of TreeSet object . Awesome.add("Awesome"). obj1.out. obj1. obj1. remove. Speed: HashSet is much faster than TreeSet.TreeSet.println(obj1). . 3. While TreeSet is backed by a Navigable TreeMap. System.add("Alive"). obj1. contains and size). remove and contains). obj1. } } OUTPUT : [is. System. If one try to store null object in TreeSet object. obj1.println(obj1). Performance: HashSet take constant time performance for the basic operations like add. Alive] Elements are sorted according to the natural ordering of its elements in TreeSet. is] 2.add("is"). Awesome. 5. 4.add("Awesome").public class HashSetExample { public static void main(String[] args) { HashSet<String> obj1= new HashSet<String>().add("Alive"). While TreeSet guarantees log(n) time cost for the basic operations (add.util. Null value: HashSet can store null object while TreeSet does not allow null object.add("is").out. } } OUTPUT : [Alive. Internal implementation: HashSet are internally backed by hashmap. it will throw Null Pointer Exception. as performance time of HashSet is constant against the log time of TreeSet for most operations (add. remove contains and size. Iteration performance of HashSet mainly depends on the load factor and initial capacity parameters. last(). first(). but we also added our own sorting method by implementing Comparable interface compareTo() method then to whom priority is given. Both are allowed to store only unique elements in their objects. Suppose there are elements in TreeSet which can be naturally sorted by the TreeSet. Parameters: comparator . 7. HashSet and TreeSet. and at least one of the threads modifies the set. Functionality: TreeSet is rich in functionality as compare to HashSet. it must be synchronized externally. 3.compareTo() . 4. empty tree set. Thus there can never be any duplicate elements inside the HashSet and TreeSet objects. Fail-fast Iterators: The iterators returned by this class's method are fail-fast: if the set is modified at any time after the iterator is created.the comparator that will be used to order this set. in any way except through the . makes TreeSet easier to use than HashSet. To whom priority is given TreeSet comparator or Comparable. both implementations are not synchronized. ceiling(). lower() etc. pollLast(). 2. the natural ordering of the elements will be used. According to Oracle Java docs public TreeSet(Comparator comparator) Constructs a new. Similarities between HashSet and TreeSet 1. If null.6. Clone() method copy technique: Both HashSet and TreeSet uses shallow copy technique to create a clone of their objects . Answer to the above question is that the Comparator passed into the TreeSet constructor has been given priority. If multiple threads access a hash set/ tree set concurrently. Comparision: HashSet uses equals() method for comparison in java while TreeSet uses compareTo() method for maintaining ordering. sorted according to the specified comparator. Functions like pollFirst(). Unique Elements: Since HashSet and TreeSet both implements Set interface. Not Thread Safe: HashSet and TreeSet both are not synchronized or not thread safe. If two entries are nearby in the order. Sorted unique elements are required instead of unique elements. non-deterministic behavior at an undetermined time in the future. TreeSet uses Red. then TreeSet places them near each other in data structure and hence in memory. When one need to perform read/write operations frequently. TreeSet has greater locality than HashSet. When to prefer TreeSet over HashSet 1. As we know Data reads from the hard drive takes much more latency time than data read from the cache or memory.Black tree algorithm underneath to sort out the elements. rather than risking arbitrary. the iterator fails quickly and cleanly. . 2. the iterator will throw a ConcurrentModificationException. 3. then TreeSet is a good choice.iterator's own remove method. in the face of concurrent modification. The sorted list given by TreeSet is always in ascending order. while HashSet spreads the entries all over memory regardless of the keys they are associated to. In case data needs to be read from hard drive than prefer TreeSet as it has greater locality than HashSet. Thus. com/java-program-implement-stack/ .ds-java.htm http://www.com/tutorials/JavaDatastructures/article.thiyagaraaj.vogella.stackexchange.com/javaexamples/data_stack.com/questions/52558/implementing-astack-in-java-for-a-technical-interview http://www.sanfoundry.com/programs/stack-example-programs-injava/simple-example-program-for-stack-in-java-using-array-and-class http://www.1) Stack implementation in java? http://www.html#stack http://codereview.tutorialspoint. Comparator c)? how it is using merge sort 8) why there is equal methd in comparator interface 9) How binarySearch() is implemented for Searching elements in collections and arrays 10) Difference between Comparable and Comparator Interface? 11) Implementation of HashMap .Y coordinates list is provide can u give logic for bounding box for a given polygon 5) Diff between ArrayList and LinkedList LINKED LIST REVERSAL PROGRAM SYMMENTRIC BINARY TREE stack implementation through generic When to use intern() method of String in Java? Why is String made final or Immutable in Java? (answer) How substring() method works in Java? (answer) Why char[] is more secure than String for storing a password in Java? (answer) How String in switch case internally implemented in Java 7? (answer) The right way to check if String is empty in Java? (answer) How to compare two String objects in Java? (answer) How does String concatenation work in Java? (answer) How to escape String literal in Java and Eclipse IDE? (tip) The real difference between String. and StringBuilder in Java? (answer) What is String[] args argument in main() method of Java program? (answer) Read more: http://javarevisited. LinekdHashMap and LinkedHashSet 5) Realtime example & Diff between TreeSet and TreeMap 6) How to implement sorting in our own Class/collection 7) Comparator Inteface calling sort(T c.2) Draw sample Class diagram for your project 3) What is aggregation & composition 4) X. ArrayList and Vector 3) Diff between HashMap and Hashtable 4) Diff between LinkedList.com/2015/12/when-to-use-internmethod-of-string-in-java. StringBuffer.blogspot.html#ixzz431wOW2T8 IQ collections 1) Realtime example & Diff between HashSet and HashMap 2) Realtime example of LinkedList. 12) Why Generics use is like List<Type> list = new ArrayList<Type> and can't be <SubType> class 13) System.out.println -> innerclasses 14) What is thread? Use of threads? How to creates Thread? how to identify duplicate request in servlet DESIGN PATTERNS IN JAVA Abstract Factory Creational design patterns Builder Factory Method Object Pool Prototype Singleton Structural design patterns Adapter Bridge Composite Decorator Add responsibilities to objects dynamically Facade A single class that represents an entire subsystem Flyweight A fine-grained instance used for efficient sharing Private Class Data Restricts accessor/mutator access Proxy Behavioral design patterns Chain of responsibility A way of passing a request between a chain of objects . Command Encapsulate a command request as an object Interpreter A way to include language elements in a program Iterator Sequentially access the elements of a collection Mediator Defines simplified communication between classes Memento Capture and restore an object's internal state Null Object Designed to act as a default value of an object Observer A way of notifying change to a number of classes State Alter an object's behavior when its state changes Strategy Encapsulates an algorithm inside a class Template method Defer the exact steps of an algorithm to a subclass Visitor Defines a new operation to a class without change . trying to create objects in a manner suitable to the situation. well understood names for software interactions. object-creation patterns use delegation effectively to get the job done. While class-creation patterns use inheritance effectively in the instantiation process. Creational patterns These design patterns are all about class instantiation. documented in a format that doesn't require specifics tied to a particular problem. Uses of Design Patterns Design patterns can speed up the development process by providing tested. Common design patterns can be improved over time. This pattern can be further divided into class-creation patterns and object-creational patterns. These techniques are difficult to apply to a broader range of problems. a design pattern is a general repeatable solution to a commonly occurring problem in software design. Often. Effective software design requires considering issues that may not become visible until later in the implementation. It is a description or template for how to solve a problem that can be used in many different situations. Design patterns provide general solutions. patterns allow developers to communicate using well-known.Design Patterns In software engineering. The basic form of object creation could result in design problems or added . In software engineering. making them more robust than ad-hoc designs. creational design patterns are design patterns that deal with object creation mechanisms. In addition. A design pattern isn't a finished design that can be transformed directly into code. people only understand how to apply certain software design techniques to certain problems. Reusing design patterns helps to prevent subtle issues that can cause major problems and improves code readability for coders and architects familiar with the patterns. proven development paradigms. Creational design patterns solve this problem by somehow controlling this object creation.  Abstract Factory  Creates an instance of several families of classes Builder  Separates object construction from its representation Factory Method  Creates an instance of several derived classes Object Pool Avoid expensive acquisition and release of resources by recycling objects that are no longer in use  Prototype A fully initialized instance to be copied or cloned .complexity to the design. more customizable. Abstract Factory emphasizes a family of product objects (either simple or complex). Builder is to creation as Strategy is to algorithm. 6. Builder. Singleton A class of which only a single instance can exist Rules of thumb 1. Abstract Factory can be used as an alternative to Facade to hide platform-specific classes. Builder. and Prototype can useSingleton in their implementation. Prototype. but doesn't require Initialize. . 12. Factory Methodrequires subclassing. 5. designs start out using Factory Method (less complicated. 11. Builder has the factory object building a complex product incrementally using a correspondingly complex protocol. but it does require an Initialize operation. 10. 4. more complex) as the designer discovers where more flexibility is needed. At other times they are complementory: Abstract Factory might store a set of Prototypes from which to clone and return product objects. Abstract Factory has the factory object producing objects of several classes. Sometimes creational patterns are competitors: there are cases when either Prototype or Abstract Factory could be used profitably. Prototype has the factory object (aka prototype) building a product by copying a prototype object. Prototype doesn't require subclassing. 8. Builder focuses on constructing a complex object step by step. 3. or Builder (more flexible. Designs that make heavy use of the Composite and Decorator patterns often can benefit fromPrototype as well. Builder returns the product as a final step. 9. Abstract Factory. Factory Methods are usually called within Template methods. but they can also be implemented using Prototype. and Prototype define a factory object that's responsible for knowing and creating the class of product objects. Prototype: creation through delegation. the product gets returned immediately. 7. Abstract Factory classes are often implemented with Factory Methods. Builder often builds a Composite. Factory Method: creation through inheritance. 2. Abstract Factory. subclasses proliferate) and evolve toward Abstract Factory. and make it a parameter of the system. but as far as the Abstract Factory is concerned. Often. Builder can use one of the other patterns to implement which components get built. Structural object-patterns define ways to compose objects to obtain new functionality. .Structural design patterns These design patterns are all about Class and Object composition. Structural classcreation patterns use inheritance to compose interfaces.
Copyright © 2024 DOKUMEN.SITE Inc.