InterviewSolution
This section includes InterviewSolutions, each offering curated multiple-choice questions to sharpen your knowledge and support exam preparation. Choose a topic below to get started.
| 1. |
What Is Linkedhashset? |
|
Answer» LinkedHashSet is also one of the implementation of the SET INTERFACE. Actually LinkedHashSet class extends the HashSet and has no other methods of its own. LinkedHashSet also STORES unique elements just like other implemetations of the Set interface. How LinkedHashSet differs is that it MAINTAINS the insertion-order; that is elements in the LinkedHashSet are stored in the SEQUENCE in which they are inserted. Note that insertion order is not affected if an element is re-inserted into the set. LinkedHashSet is also one of the implementation of the Set interface. Actually LinkedHashSet class extends the HashSet and has no other methods of its own. LinkedHashSet also stores unique elements just like other implemetations of the Set interface. How LinkedHashSet differs is that it maintains the insertion-order; that is elements in the LinkedHashSet are stored in the sequence in which they are inserted. Note that insertion order is not affected if an element is re-inserted into the set. |
|
| 2. |
Which Set Implementation Should Be Used If You Want The Insertion Order To Be Maintained? |
|
Answer» LINKEDHASHSET should be USED in this CASE. LinkedHashSet should be used in this case. |
|
| 3. |
How Does Hashset Internally Works In Java? |
|
Answer» HASHSET internally uses HashMap to store it's ELEMENTS. But it differs from HashMap on two points.
HashSet internally uses HashMap to store it's elements. But it differs from HashMap on two points. |
|
| 4. |
Hashmap Vs Linkedhashmap Vs Treemap In Java? |
Answer»
|
|
| 5. |
Difference Between Hashmap And Hashtable In Java? |
|
Answer» Though both HashTable and HashMap store elements as a (key, value) pair and use hashing technique to store elements, moreover from Java v1.2, HashTable class was retrofitted to implement the MAP interface, making it a member of the Java COLLECTIONS Framework. But there are certain difference between the TWO -
Though both HashTable and HashMap store elements as a (key, value) pair and use hashing technique to store elements, moreover from Java v1.2, HashTable class was retrofitted to implement the Map interface, making it a member of the Java Collections Framework. But there are certain difference between the two - |
|
| 6. |
What Is A Identityhashmap? |
|
Answer» IdentityHashMap CLASS implements the Map interface with a hash table, using reference-equality in place of object-equality when comparing keys (and values). In other words, in an IdentityHashMap, TWO keys K1 and k2 are considered equal if and only if (k1==k2). Where as In normal Map implementations (like HASHMAP) two keys k1 and k2 are considered equal if and only if (k1==null ? k2==null : k1.equals(k2)). Note that This class is not a general-purpose Map implementation. While this class implements the Map interface, it INTENTIONALLY violates Map's general contract, which mandates the use of the equals method when comparing objects. This class is designed for use only in the rare cases wherein reference-equality semantics are required. IdentityHashMap class implements the Map interface with a hash table, using reference-equality in place of object-equality when comparing keys (and values). In other words, in an IdentityHashMap, two keys k1 and k2 are considered equal if and only if (k1==k2). Where as In normal Map implementations (like HashMap) two keys k1 and k2 are considered equal if and only if (k1==null ? k2==null : k1.equals(k2)). Note that This class is not a general-purpose Map implementation. While this class implements the Map interface, it intentionally violates Map's general contract, which mandates the use of the equals method when comparing objects. This class is designed for use only in the rare cases wherein reference-equality semantics are required. |
|
| 7. |
What Is A Weakhashmap? |
|
Answer» WEAKHASHMAP is a Hash table based implementation of the Map interface, with weak keys. An entry in a WeakHashMap will automatically be REMOVED when its key is no longer in ordinary use. Which MEANS storing only weak references allows GARBAGE collector to remove the entry (key-value PAIR) from the map when its key is not referenced outside of the WeakHashMap. In WeakHashMap both null values and the null key are supported. A WeakHashMap is created as- Map weakHashMap = new WeakHashMap(); WeakHashMap is a Hash table based implementation of the Map interface, with weak keys. An entry in a WeakHashMap will automatically be removed when its key is no longer in ordinary use. Which means storing only weak references allows garbage collector to remove the entry (key-value pair) from the map when its key is not referenced outside of the WeakHashMap. In WeakHashMap both null values and the null key are supported. A WeakHashMap is created as- Map weakHashMap = new WeakHashMap(); |
|
| 8. |
What Is Treemap In Java? |
|
Answer» TreeMap is also one of the implementation of the Map interface LIKE HashMap and LinkedHashMap. TreeMap class implements the NavigableMap interface and extends the AbstractMap class. How it differs from other implementations of the Map interface is that objects in TreeMap are stored in sorted order. The elements are ORDERED using their natural ORDERING or a comparator can be provided at map creation time to PROVIDE custom ordering. One important point about TreeMap is, though HashMap and LinkedHashMap allow one null as key, TreeMap doesn't allow null as key. Any attempt to ADD null in a TreeMap will result in a NullPointerException. TreeMap is also one of the implementation of the Map interface like HashMap and LinkedHashMap. TreeMap class implements the NavigableMap interface and extends the AbstractMap class. How it differs from other implementations of the Map interface is that objects in TreeMap are stored in sorted order. The elements are ordered using their natural ordering or a comparator can be provided at map creation time to provide custom ordering. One important point about TreeMap is, though HashMap and LinkedHashMap allow one null as key, TreeMap doesn't allow null as key. Any attempt to add null in a TreeMap will result in a NullPointerException. |
|
| 9. |
Which Map Implementation Should Be Used If You Want Map Values To Be Sorted By Keys? |
|
Answer» TREEMAP should be USED in this CASE. TreeMap should be used in this case. |
|
| 10. |
What Is Linkedhashmap? |
|
Answer» LinkedHashMap is also one of the implementation of the Map interface, apart from implementing Map interface LinkedHashMap also extends the HashMap class. So just like HashMap, LinkedHashMap also ALLOWS one null key and multiple null values. How it DIFFERS from other implementations of the Map interface like HashMap and TREEMAP is thatLinkedHashMap maintains the insertion order of the elements which means if we iterate a LinkedHashMap we'll get the keys in the order in which they were inserted in the Map. LinkedHashMap maintains a doubly-linked list RUNNING through all of its ENTRIES and that's how it maintains the iteration order. LinkedHashMap is also one of the implementation of the Map interface, apart from implementing Map interface LinkedHashMap also extends the HashMap class. So just like HashMap, LinkedHashMap also allows one null key and multiple null values. How it differs from other implementations of the Map interface like HashMap and TreeMap is thatLinkedHashMap maintains the insertion order of the elements which means if we iterate a LinkedHashMap we'll get the keys in the order in which they were inserted in the Map. LinkedHashMap maintains a doubly-linked list running through all of its entries and that's how it maintains the iteration order. |
|
| 11. |
Which Map Implementation Should Be Used If You Want To Retain The Insertion Order? |
|
Answer» LINKEDHASHMAP should be USED in this CASE. LinkedHashMap should be used in this case. |
|
| 12. |
When Do We Need To Override Hashcode() And Equals() Methods? |
|
Answer» The default implementation of equals() method in the Object class is a simple reference EQUALITY check. public boolean equals(Object obj){ The default implementation of hashCode() in the Object class just returns INTEGER VALUE of the memory address of the object. It becomes very important to override these two methods in case we are using a custom object as KEY in a hash based collection. In that case we can't rely on the default implementation provided by the Object class and need to provide custom implementation of hashCode() and equals() method. If two objects Obj1 and Obj2 are equal according to their equals() method then they must have the same hash code too. Though the vice-versa is not true that is if two objects have the same hash code then they do not have to be equal too. The default implementation of equals() method in the Object class is a simple reference equality check. public boolean equals(Object obj){ The default implementation of hashCode() in the Object class just returns integer value of the memory address of the object. It becomes very important to override these two methods in case we are using a custom object as key in a hash based collection. In that case we can't rely on the default implementation provided by the Object class and need to provide custom implementation of hashCode() and equals() method. If two objects Obj1 and Obj2 are equal according to their equals() method then they must have the same hash code too. Though the vice-versa is not true that is if two objects have the same hash code then they do not have to be equal too. |
|
| 13. |
What Is Equals() Method? |
|
Answer» EQUALS() METHOD is present in the java.lang.Object class. It is used to determine the EQUALITY of TWO objects. equals() method is present in the java.lang.Object class. It is used to determine the equality of two objects. |
|
| 14. |
What Is The Hashcode() Method? |
|
Answer» hashCode() METHOD is present in the java.lang.Object class. This method is used to GET a unique integer value for a given object. We can see it's USE with hash based collections like HASHTABLE or HashMap where hashCode() is used to find the correct bucket LOCATION where the particular (key, value) pair is stored. hashCode() method is present in the java.lang.Object class. This method is used to get a unique integer value for a given object. We can see it's use with hash based collections like HashTable or HashMap where hashCode() is used to find the correct bucket location where the particular (key, value) pair is stored. |
|
| 15. |
What Is Hash-collision In Hash Based Collections? |
|
Answer» In HashMap, using the KEY, a Hash is calculated and that hash VALUE decides in which bucket the particular Map.Entry object will RESIDE. Hash collision means more than ONE key having the same calculated hash value THUS stored in the same bucket. In HashMap, in that case Entry objects are stored as a linked-list with in the same bucket. In HashMap, using the key, a Hash is calculated and that hash value decides in which bucket the particular Map.Entry object will reside. Hash collision means more than one key having the same calculated hash value thus stored in the same bucket. In HashMap, in that case Entry objects are stored as a linked-list with in the same bucket. |
|
| 16. |
What Happens If Hashmap Has Duplicate Keys? |
|
Answer» If an attempt is made to add the same key twice, it won't CAUSE any error but the VALUE which is added later will override the PREVIOUS value. As Exp. If you have a Map, cityMap and you add TWO values with same key in the cityMap, Kolkata will override the New Delhi. cityMap.put("5", "New Delhi"); If an attempt is made to add the same key twice, it won't cause any error but the value which is added later will override the previous value. As Exp. If you have a Map, cityMap and you add two values with same key in the cityMap, Kolkata will override the New Delhi. cityMap.put("5", "New Delhi"); |
|
| 17. |
Does Hashmap Allow Null Keys And Null Values? |
|
Answer» HashMap allows one null key and any number of null values. If another null key is added it won't cause any ERROR. But the value with the new null key will override the value with OLD null key. As exp. If you have a Map, cityMap and you ADD TWO values with null keys in the cityMap, Kolkata will override the New Delhi as only one null key is allowed. cityMap.put(null, "New Delhi"); HashMap allows one null key and any number of null values. If another null key is added it won't cause any error. But the value with the new null key will override the value with old null key. As exp. If you have a Map, cityMap and you add two values with null keys in the cityMap, Kolkata will override the New Delhi as only one null key is allowed. cityMap.put(null, "New Delhi"); |
|
| 18. |
What Is Map.entry In Map? |
|
Answer» Map.Entry is an interface in java.util, in fact Entry is a nested interface in Map interface. Nested interface must be QUALIFIED by the NAME of the class or interface of which it is a member, that's why it is qualified as Map.Entry. Map.Entry REPRESENTS a key/value pair that forms one element of a Map. The Map.entrySet method RETURNS a collection-view of the map, whose elements are of this class. As exp. If you have a Map called cityMap then using entrySet method you can get the set view of the map whose elements are of type Map.Entry, and then using getKey and getValue methods of the Map.Entry you can get the key and value pair of the Map. for(Map.Entry<String, String> entry: cityMap.entrySet()){ System.out.println("Key is " + entry.getKey() + " Value is " + entry.getValue()); } Map.Entry is an interface in java.util, in fact Entry is a nested interface in Map interface. Nested interface must be qualified by the name of the class or interface of which it is a member, that's why it is qualified as Map.Entry. Map.Entry represents a key/value pair that forms one element of a Map. The Map.entrySet method returns a collection-view of the map, whose elements are of this class. As exp. If you have a Map called cityMap then using entrySet method you can get the set view of the map whose elements are of type Map.Entry, and then using getKey and getValue methods of the Map.Entry you can get the key and value pair of the Map. for(Map.Entry<String, String> entry: cityMap.entrySet()){ System.out.println("Key is " + entry.getKey() + " Value is " + entry.getValue()); } |
|
| 19. |
Are Maps Actually Collections Or Why Doesn't Map Extend Collection? |
|
Answer» MAPS themselves are not COLLECTIONS because they don't IMPLEMENT COLLECTION INTERFACE. Maps themselves are not collections because they don't implement Collection interface. |
|
| 20. |
Can We Iterate Through A Map? |
|
Answer» Though we can't ITERATE a MAP as such but Map interface has methods which provide a set view of the Map. That set can be iterated. Those two methods are -
There is also a values() method in the Map that returns a Collection view of the values CONTAINED in this map. Though we can't iterate a Map as such but Map interface has methods which provide a set view of the Map. That set can be iterated. Those two methods are - There is also a values() method in the Map that returns a Collection view of the values contained in this map. |
|
| 21. |
Difference Between Fail-fast Iterator And Fail-safe Iterator? |
Answer»
|
|
| 22. |
What Is A Fail-safe Iterator? |
|
Answer» An iterator is considered fail-safe if it does not throw ConcurrentModificationException. ConcurrentModificationException is not THROWN as the fail-safe iterator makes a copy of the underlying STRUCTURE and iteration is done over that snapshot. SINCE iteration is done over a copy of the collection so interference is IMPOSSIBLE and the iterator is guaranteed not to throw ConcurrentModificationException. An iterator is considered fail-safe if it does not throw ConcurrentModificationException. ConcurrentModificationException is not thrown as the fail-safe iterator makes a copy of the underlying structure and iteration is done over that snapshot. Since iteration is done over a copy of the collection so interference is impossible and the iterator is guaranteed not to throw ConcurrentModificationException. |
|
| 23. |
What Is Fail Fast Iterator? |
|
Answer» An iterator is considered fail-fast if it throws a CONCURRENTMODIFICATIONEXCEPTION under either of the following two conditions:
fail-fast iterator will throw a ConcurrentModificationException if the underlying collection is structurally modified in any way except through the iterator's own remove or add (if applicable as in list-iterator) methods. Note that structural modification is any operation that adds or deletes one or more elements; merely SETTING the value of an element (in case of list) or changing the value associated with an existing key (in case of map) is not a structural modification. An iterator is considered fail-fast if it throws a ConcurrentModificationException under either of the following two conditions: fail-fast iterator will throw a ConcurrentModificationException if the underlying collection is structurally modified in any way except through the iterator's own remove or add (if applicable as in list-iterator) methods. Note that structural modification is any operation that adds or deletes one or more elements; merely setting the value of an element (in case of list) or changing the value associated with an existing key (in case of map) is not a structural modification. |
|
| 24. |
Why Iterator Doesn't Have Add Method Whereas Listiterator Has Add Method? |
|
Answer» Iterator can be OBTAINED on any Collection CLASS like List or SET so contract for Iterator makes no guarantees about the order of ITERATION. But ListIterator can only be used to traverse a List so it does guarantee the order of the iteration. That is why ListIterator provides an ADD operation. Iterator can be obtained on any Collection class like List or Set so contract for Iterator makes no guarantees about the order of iteration. But ListIterator can only be used to traverse a List so it does guarantee the order of the iteration. That is why ListIterator provides an add operation. |
|
| 25. |
What Is An Iterator? |
|
Answer» Iterator is an INTERFACE which is part of the Java Collections FRAMEWORK. An Iterator enables you to iterate a collection. Iterators also allow the caller to remove elements from the underlying collection during the iteration. Collection CLASSES provide iterator method which RETURNS an iterator. This iterator can be used to traverse a collection. As exp. if there is a set called citySet, an iterator on this set can be obtained as - Iterator<String> itr = citySet.iterator(); Iterator is an interface which is part of the Java Collections framework. An Iterator enables you to iterate a collection. Iterators also allow the caller to remove elements from the underlying collection during the iteration. Collection classes provide iterator method which returns an iterator. This iterator can be used to traverse a collection. As exp. if there is a set called citySet, an iterator on this set can be obtained as - Iterator<String> itr = citySet.iterator(); |
|
| 26. |
Difference Between Array And Arraylist In Java? |
Answer»
|
|
| 27. |
Difference Between Arraylist And Vector In Java? |
Answer»
|
|
| 28. |
Difference Between Arraylist And Linkedlist In Java? |
|
Answer» In Java collections FRAMEWORK ArrayList and LinkedList are TWO different implementations of List INTERFACE
In Java collections framework ArrayList and LinkedList are two different implementations of List interface |
|
| 29. |
What Is Deque Interface In Java? |
|
Answer» Java.util.Deque is an interface in Java which EXTENDS QUEUE interface and provides support for element insertion and removal at both ends. The name deque is SHORT for "DOUBLE ENDED queue" and is usually pronounced "deck". Some of the implementing classes of the Deque interface are LinkedList, ConcurrentLinkedDeque, LinkedBlockingDeque. Note that addFirst() and addLast() methods provided in the LinkedList implementation are specified by the Deque interface. Java.util.Deque is an interface in Java which extends Queue interface and provides support for element insertion and removal at both ends. The name deque is short for "double ended queue" and is usually pronounced "deck". Some of the implementing classes of the Deque interface are LinkedList, ConcurrentLinkedDeque, LinkedBlockingDeque. Note that addFirst() and addLast() methods provided in the LinkedList implementation are specified by the Deque interface. |
|
| 30. |
What Is Linkedlist Class In Java? How Is It Implemented? |
|
Answer» LinkedList class in JAVA implements List and Deque interfaces and LinkedList implements it using doubly linkedlist. WITHIN the LinkedList implementation there is a private class NODE which provides the structure for a node in a doubly linked list. It has ITEM variable for holding the value and two reference to Node class itself for connecting to next and previous nodes. LinkedList class in Java implements List and Deque interfaces and LinkedList implements it using doubly linkedlist. Within the LinkedList implementation there is a private class Node which provides the structure for a node in a doubly linked list. It has item variable for holding the value and two reference to Node class itself for connecting to next and previous nodes. |
|
| 31. |
How Is The Performance Of An Arraylist? |
Answer»
|
|
| 32. |
How To Convert Array To Arraylist In Java? |
|
Answer» Arrays class contains a STATIC factory method asList() that allows arrays to be VIEWED as LISTS. public static <T> List<T> asList(T... a) As Exp. String cityArray[] = {"Delhi", "Mumbai", "Bangalore", "Hyderabad", "CHENNAI"}; //Converting array to List List<String> cityList = Arrays.asList(cityArray); Arrays class contains a static factory method asList() that allows arrays to be viewed as lists. public static <T> List<T> asList(T... a) As Exp. String cityArray[] = {"Delhi", "Mumbai", "Bangalore", "Hyderabad", "Chennai"}; //Converting array to List List<String> cityList = Arrays.asList(cityArray); |
|
| 33. |
How To Convert Arraylist To Array In Java? |
|
Answer» Within Collection interface there are two versions of toArray() which can be used to convert ARRAYLIST to ARRAY.
The first version RETURNS an array of Object. The second version returns an array containing the elements of the LIST. Normally we go with the second version because it returns the array of the same type as List. If you have a List called cityList, it can be converted to an array like this - String cityArray[] = new String[cityList.size()]; Within Collection interface there are two versions of toArray() which can be used to convert ArrayList to array. The first version returns an array of Object. The second version returns an array containing the elements of the list. Normally we go with the second version because it returns the array of the same type as List. If you have a List called cityList, it can be converted to an array like this - String cityArray[] = new String[cityList.size()]; |
|
| 34. |
How And Why To Synchronize Arraylist In Java? |
|
Answer» In order to have better performance most of the COLLECTIONS are not synchronized. Which means sharing an instance of arrayList among many threads where those threads are MODIFYING (by adding or removing the values) the COLLECTION may RESULT in unpredictable behaviour. To synchronize a List Collections.synchronizedList() method can be used. In order to have better performance most of the Collections are not synchronized. Which means sharing an instance of arrayList among many threads where those threads are modifying (by adding or removing the values) the collection may result in unpredictable behaviour. To synchronize a List Collections.synchronizedList() method can be used. |
|
| 35. |
How To Sort Arraylist Of Strings In Descending Order? |
|
Answer» Collections.sort() METHOD will sort the ARRAYLIST of STRING in ascending order. To have a descending order EITHER comparator has to be provided or reverseOrder method of the Collections class can be used. Collections.sort(cityList, Collections.reverseOrder()); Collections.sort() method will sort the ArrayList of String in ascending order. To have a descending order either comparator has to be provided or reverseOrder method of the Collections class can be used. Collections.sort(cityList, Collections.reverseOrder()); |
|
| 36. |
How To Sort Arraylist In Java? |
|
Answer» Collections class has a STATIC method sort which can be used for SORTING an arraylist. There are TWO overloaded versions of sort method -
If you have a List called cityList it can be sorted LIKE this - Collections.sort(cityList); Collections class has a static method sort which can be used for sorting an arraylist. There are two overloaded versions of sort method - If you have a List called cityList it can be sorted like this - Collections.sort(cityList); |
|
| 37. |
What Is Listiterator In Java? |
|
Answer» ListIterator provides the FUNCTIONALITY to iterate a LIST in both directions. The interesting POINT about list iterator is that it has no current element. Its current cursor position always lies between the element that would be returned by a CALL to previous() and the element that would be returned by a call to NEXT(). ListIterator provides the functionality to iterate a list in both directions. The interesting point about list iterator is that it has no current element. Its current cursor position always lies between the element that would be returned by a call to previous() and the element that would be returned by a call to next(). |
|
| 38. |
How To Loop/iterate An Arraylist In Java? |
|
Answer» There are many WAYS to loop/iterate an ARRAYLIST in Java. Options are -
for-each loop is the best WAY to iterate a list if you just need to traverse SEQUENTIALLY through a list. There are many ways to loop/iterate an arrayList in Java. Options are - for-each loop is the best way to iterate a list if you just need to traverse sequentially through a list. |
|
| 39. |
How To Remove Duplicate Elements From An Arraylist? |
|
Answer» We can USE a HashSet to do the job of removing the DUPLICATE elements. HashSet only stores UNIQUE elements and we'll use that FEATURE of HashSet to remove duplicates. If you have a LIST called cityList you can create a HashSet using this list - Set<String> citySet = new HashSet<String>(cityList); That will remove all the duplicate elements from the given list. Note that insertion order won't be retained if a HashSet is used. In case insertion order is to be retained use LinkedHashSet. We can use a HashSet to do the job of removing the duplicate elements. HashSet only stores unique elements and we'll use that feature of HashSet to remove duplicates. If you have a List called cityList you can create a HashSet using this list - Set<String> citySet = new HashSet<String>(cityList); That will remove all the duplicate elements from the given list. Note that insertion order won't be retained if a HashSet is used. In case insertion order is to be retained use LinkedHashSet. |
|
| 40. |
How To Remove Elements From An Arraylist? |
|
Answer» ArrayList provides several methods to remove elements from the LIST. Since ArrayList internally uses array to store elements, one point to note is that when an element is removed from the List the remaining elements have to be shifted to fill the GAP created in the underlying array.
ArrayList provides several methods to remove elements from the List. Since ArrayList internally uses array to store elements, one point to note is that when an element is removed from the List the remaining elements have to be shifted to fill the gap created in the underlying array. |
|
| 41. |
How To Join Two Or More Arraylists? |
|
Answer» List provides a method addAll to join TWO or more lists in JAVA. If you have one list cityList and ANOTHER List secondCityList then you can join them using addAll LIKE this - cityList.addAll(secondCityList); List provides a method addAll to join two or more lists in Java. If you have one list cityList and another List secondCityList then you can join them using addAll like this - cityList.addAll(secondCityList); |
|
| 42. |
Does Arraylist Allow Null? |
|
Answer» In ARRAYLIST any NUMBER of NULLS can be ADDED. In ArrayList any number of nulls can be added. |
|
| 43. |
Does Arraylist Allow Duplicate Elements? |
|
Answer» Yes. List ALLOWS DUPLICATE ELEMENTS to be ADDED. Yes. List allows duplicate elements to be added. |
|
| 44. |
How To Add Elements To An Arraylist? |
Answer»
|
|
| 45. |
How Arraylist Works Internally In Java? |
|
Answer» Basic data structure USED by ARRAYLIST to store objects is an array of Object class, which is defined like - transient Object[] elementData; When we ADD an element to an ArrayList it first verifies whether it has that much capacity in the array to store new element or not, in case there is not then the new capacity is CALCULATED which is 50% more than the old capacity and the array is increased by that much capacity (Actually uses Arrays.copyOf which returns the original array increased to the new length) Basic data structure used by ArrayList to store objects is an array of Object class, which is defined like - transient Object[] elementData; When we add an element to an ArrayList it first verifies whether it has that much capacity in the array to store new element or not, in case there is not then the new capacity is calculated which is 50% more than the old capacity and the array is increased by that much capacity (Actually uses Arrays.copyOf which returns the original array increased to the new length) |
|
| 46. |
Why Arraylist Is Called Dynamically Growing Array? How That Dynamic Behaviour Is Achieved? |
|
Answer» In the case of ArrayList you don't have to anticipate in advance, like in the case of array, how many ELEMENTS you are going to STORE in the arraylist. As and when elements are added list keeps GROWING. That is why ArrayList is called dynamically growing array. For ArrayList, data structure used for storing elements is array itself. When ArrayList is created it initializes an array with an INITIAL capacity (default is array of length 10). When that limit is crossed another array is created which is 1.5 TIMES the original array and the elements from the old array are copied to the new array. In the case of ArrayList you don't have to anticipate in advance, like in the case of array, how many elements you are going to store in the arraylist. As and when elements are added list keeps growing. That is why ArrayList is called dynamically growing array. For ArrayList, data structure used for storing elements is array itself. When ArrayList is created it initializes an array with an initial capacity (default is array of length 10). When that limit is crossed another array is created which is 1.5 times the original array and the elements from the old array are copied to the new array. |
|
| 47. |
Which Collection Classes Implement List Interface? |
|
Answer» Some of the COLLECTION classes that implement List interface are ARRAYLIST, CopyOnWriteArrayList, LinkedList, Stack, VECTOR. Some of the Collection classes that implement List interface are ArrayList, CopyOnWriteArrayList, LinkedList, Stack, Vector. |
|
| 48. |
What Is List Interface? |
|
Answer» List INTERFACE EXTENDS the ROOT interface Collection and adds behaviour for the collection that stores a sequence of elements. These elements can be INSERTED or ACCESSED by their position in the list using a zero-based index. List interface extends the root interface Collection and adds behaviour for the collection that stores a sequence of elements. These elements can be inserted or accessed by their position in the list using a zero-based index. |
|
| 49. |
How To Make A Collection Class Immutable? |
|
Answer» COLLECTIONS class provides static method to MAKE a Collection unmodifiable. Each of the SIX core collection interfaces -Collection, Set, List, Map, SortedSet, and SortedMap - has one static factory method. public static <T> Collection<T> unmodifiableCollection(Collection<? extends T> C); public static <T> Set<T> unmodifiableSet(Set<? extends T> s); public static <T> List<T> unmodifiableList(List<? extends T> list); public static <K,V> Map<K, V> unmodifiableMap(Map<? extends K, ? extends V> m); public static <T> SortedSet<T> unmodifiableSortedSet(SortedSet<? extends T> s); public static <K,V> SortedMap<K, V> unmodifiableSortedMap(SortedMap<K, ? extends V> m); Collections class provides static method to make a Collection unmodifiable. Each of the six core collection interfaces -Collection, Set, List, Map, SortedSet, and SortedMap - has one static factory method. public static <T> Collection<T> unmodifiableCollection(Collection<? extends T> c); public static <T> Set<T> unmodifiableSet(Set<? extends T> s); public static <T> List<T> unmodifiableList(List<? extends T> list); public static <K,V> Map<K, V> unmodifiableMap(Map<? extends K, ? extends V> m); public static <T> SortedSet<T> unmodifiableSortedSet(SortedSet<? extends T> s); public static <K,V> SortedMap<K, V> unmodifiableSortedMap(SortedMap<K, ? extends V> m); |
|
| 50. |
How Can We Synchronize A Collection Or How To Make A Collection Thread-safe? |
|
Answer» Collections class has several STATIC methods that RETURN synchronized collections. Each of the six core collection interfaces -Collection, SET, List, Map, SortedSet, and SortedMap - has one static factory method. public static <T> Collection<T> synchronizedCollection(Collection<T> c); Each of these methods returns a synchronized (thread-safe) Collection backed up by the specified collection. Collections class has several static methods that return synchronized collections. Each of the six core collection interfaces -Collection, Set, List, Map, SortedSet, and SortedMap - has one static factory method. public static <T> Collection<T> synchronizedCollection(Collection<T> c); Each of these methods returns a synchronized (thread-safe) Collection backed up by the specified collection. |
|