Question
stringlengths
1
113
Answer
stringlengths
22
6.98k
What are the important points about the Java TreeSet class?
Java TreeSet class implements the Set interface that uses a tree for storage. It inherits AbstractSet class and implements the NavigableSet interface. The objects of the TreeSet class are stored in ascending order. The important points about the Java TreeSet class are: -Java TreeSet class contains unique elements only like HashSet. -Java TreeSet class access and retrieval times are quiet fast. -Java TreeSet class doesn't allow null element. -Java TreeSet class is non synchronized. -Java TreeSet class maintains ascending order. -Java TreeSet class contains unique elements only like HashSet. -Java TreeSet class access and retrieval times are quite fast. -Java TreeSet class doesn't allow null elements. -Java TreeSet class is non-synchronized. -Java TreeSet class maintains ascending order. -The TreeSet can only allow those generic types that are comparable. For example The Comparable interface is being implemented by the StringBuffer class.
What is Internal Working of The TreeSet Class?
TreeSet is being implemented using a binary search tree, which is self-balancing just like a Red-Black Tree. Therefore, operations such as a search, remove, and add consume O(log(N)) time. The reason behind this is there in the self-balancing tree. It is there to ensure that the tree height never exceeds O(log(N)) for all of the mentioned operations. Therefore, it is one of the efficient data structures in order to keep the large data that is sorted and also to do operations on it.
What is Synchronization of The TreeSet Class?
As already mentioned above, the TreeSet class is not synchronized. It means if more than one thread concurrently accesses a tree set, and one of the accessing threads modify it, then the synchronization must be done manually. It is usually done by doing some object synchronization that encapsulates the set. However, in the case where no such object is found, then the set must be wrapped with the help of the Collections.synchronizedSet() method. It is advised to use the method during creation time in order to avoid the unsynchronized access of the set. The following code snippet shows the same. TreeSet treeSet = new TreeSet(); Set syncrSet = Collections.synchronziedSet(treeSet);
What is the class declaration for TreeSet Class?
Let's see the declaration for java.util.TreeSet class. public class TreeSet<E> extends AbstractSet<E> implements NavigableSet<E>, Cloneable, Serializable
What are the Constructors of the Java TreeSet Class?
Constructor: TreeSet() Description: It is used to construct an empty tree set that will be sorted in ascending order according to the natural order of the tree set. Constructor: TreeSet(Collection<? extends E> c) Description: It is used to build a new tree set that contains the elements of the collection c. Constructor: TreeSet(Comparator<? super E> comparator) Description: It is used to construct an empty tree set that will be sorted according to given comparator. Constructor: TreeSet(SortedSet<E> s) Description: It is used to build a TreeSet that contains the elements of the given SortedSe
What are the Methods of Java TreeSet Class?
Method: boolean add(E e) Description: It is used to add the specified element to this set if it is not already present. Method: boolean addAll(Collection<? extends E> c) Description: It is used to add all of the elements in the specified collection to this set. Method: E ceiling(E e) Description: It returns the equal or closest greatest element of the specified element from the set, or null there is no such element. Method: Comparator<? super E> comparator() Description: It returns a comparator that arranges elements in order. Method: Iterator descendingIterator() Description: It is used to iterate the elements in descending order. Method: NavigableSet descendingSet() Description: It returns the elements in reverse order. Method: E floor(E e) Description: It returns the equal or closest least element of the specified element from the set, or null there is no such element. Method: SortedSet headSet(E toElement) Description: It returns the group of elements that are less than the specified element. Method: NavigableSet headSet(E toElement, boolean inclusive) Description: It returns the group of elements that are less than or equal to(if, inclusive is true) the specified element. Method: E higher(E e) Description: It returns the closest greatest element of the specified element from the set, or null there is no such element. Method: Iterator iterator() Description: It is used to iterate the elements in ascending order. Method: E lower(E e) Description: It returns the closest least element of the specified element from the set, or null there is no such element. Method: E pollFirst() Description: It is used to retrieve and remove the lowest(first) element. Method: E pollLast() Description: It is used to retrieve and remove the highest(last) element. Method: Spliterator spliterator() Description: It is used to create a late-binding and fail-fast spliterator over the elements. Method: NavigableSet subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) Description: It returns a set of elements that lie between the given range. Method: SortedSet subSet(E fromElement, E toElement)) Description: It returns a set of elements that lie between the given range which includes fromElement and excludes toElement. Method: SortedSet tailSet(E fromElement) Description: It returns a set of elements that are greater than or equal to the specified element. Method: NavigableSet tailSet(E fromElement, boolean inclusive) Description: It returns a set of elements that are greater than or equal to (if, inclusive is true) the specified element. Method: boolean contains(Object o) Description: It returns true if this set contains the specified element. Method: boolean isEmpty() Description: It returns true if this set contains no elements. Method: boolean remove(Object o) Description: It is used to remove the specified element from this set if it is present. Method: void clear() Description: It is used to remove all of the elements from this set. Method: Object clone() Description: It returns a shallow copy of this TreeSet instance. Method: E first() Description: It returns the first (lowest) element currently in this sorted set. Method: E last() Description: It returns the last (highest) element currently in this sorted set. Method: int size() Description: It returns the number of elements in this set.
Can you provide an example of Java TreeSet?
Let's see a simple example of Java TreeSet. FileName: TreeSet1.java import java.util.*; class TreeSet1{ public static void main(String args[]){ //Creating and adding elements TreeSet<String> al=new TreeSet<String>(); al.add("Ravi"); al.add("Vijay"); al.add("Ravi"); al.add("Ajay"); //Traversing elements Iterator<String> itr=al.iterator(); while(itr.hasNext()){ System.out.println(itr.next()); } } } Output: Ajay Ravi Vijay
What is Java Queue Interface?
The interface Queue is available in the java.util package and does extend the Collection interface. It is used to keep the elements that are processed in the First In First Out (FIFO) manner. It is an ordered list of objects, where insertion of elements occurs at the end of the list, and removal of elements occur at the beginning of the list. Being an interface, the queue requires, for the declaration, a concrete class, and the most common classes are the LinkedList and PriorityQueue in Java. Implementations done by these classes are not thread safe. If it is required to have a thread safe implementation, PriorityBlockingQueue is an available option.
What is the class declaration for Queue Interface?
public interface Queue<E> extends Collection<E>
What are the Methods of Java Queue Interface?
Method: boolean add(object) Description: It is used to insert the specified element into this queue and return true upon success. Method: boolean offer(object) Description: It is used to insert the specified element into this queue. Method: Object remove() Description: It is used to retrieves and removes the head of this queue. Method: Object poll() Description: It is used to retrieves and removes the head of this queue, or returns null if this queue is empty. Method: Object element() Description: It is used to retrieves, but does not remove, the head of this queue. Method: Object peek() Description: It is used to retrieves, but does not remove, the head of this queue, or returns null if this queue is empty.
What are the following important features of a Queue?
The following are some important features of a queue. -As discussed earlier, FIFO concept is used for insertion and deletion of elements from a queue. -The Java Queue provides support for all of the methods of the Collection interface including deletion, insertion, etc. -PriorityQueue, ArrayBlockingQueue and LinkedList are the implementations that are used most frequently. -The NullPointerException is raised, if any null operation is done on the BlockingQueues. -Those Queues that are present in the util package are known as Unbounded Queues. -Those Queues that are present in the util.concurrent package are known as bounded Queues. -All Queues barring the Deques facilitates removal and insertion at the head and tail of the queue; respectively. In fact, deques support element insertion and removal at both ends.
What is the class declaration for PriorityQueue?
Let's see the declaration for java.util.PriorityQueue class. public class PriorityQueue<E> extends AbstractQueue<E> implements Serializable
Can you provide an example of Java PriorityQueue?
FileName: TestCollection12.java import java.util.*; class TestCollection12{ public static void main(String args[]){ PriorityQueue<String> queue=new PriorityQueue<String>(); queue.add("Amit"); queue.add("Vijay"); queue.add("Karan"); queue.add("Jai"); queue.add("Rahul"); System.out.println("head:"+queue.element()); System.out.println("head:"+queue.peek()); System.out.println("iterating the queue elements:"); Iterator itr=queue.iterator(); while(itr.hasNext()){ System.out.println(itr.next()); } queue.remove(); queue.poll(); System.out.println("after removing two elements:"); Iterator<String> itr2=queue.iterator(); while(itr2.hasNext()){ System.out.println(itr2.next()); } } } Output: head:Amit head:Amit iterating the queue elements: Amit Jai Karan Vijay Rahul after removing two elements: Karan Rahul Vijay
What is Java Deque Interface?
The interface called Deque is present in java.util package. It is the subtype of the interface queue. The Deque supports the addition as well as the removal of elements from both ends of the data structure. Therefore, a deque can be used as a stack or a queue. We know that the stack supports the Last In First Out (LIFO) operation, and the operation First In First Out is supported by a queue. As a deque supports both, either of the mentioned operations can be performed on it. Deque is an acronym for "double ended queue".
What is the class declaration for Deque Interface?
public interface Deque<E> extends Queue<E>
What are the Methods of Java Deque Interface?
Method: boolean add(object) Description: It is used to insert the specified element into this deque and return true upon success. Method: boolean offer(object) Description: It is used to insert the specified element into this deque. Method: Object remove() Description: It is used to retrieve and removes the head of this deque. Method: Object poll() Description: It is used to retrieve and removes the head of this deque, or returns null if this deque is empty. Method: Object element() Description: It is used to retrieve, but does not remove, the head of this deque. Method: Object peek() Description: It is used to retrieve, but does not remove, the head of this deque, or returns null if this deque is empty. Method: Object peekFirst() Description: The method returns the head element of the deque. The method does not remove any element from the deque. Null is returned by this method, when the deque is empty. Method: Object peekLast() Description: The method returns the last element of the deque. The method does not remove any element from the deque. Null is returned by this method, when the deque is empty. Method: Boolean offerFirst(e) Description: Inserts the element e at the front of the queue. If the insertion is successful, true is returned; otherwise, false. Method: Object offerLast(e) Description: Inserts the element e at the tail of the queue. If the insertion is successful, true is returned; otherwise, false.
What are the important points about ArrayDeque class?
We know that it is not possible to create an object of an interface in Java. Therefore, for instantiation, we need a class that implements the Deque interface, and that class is ArrayDeque. It grows and shrinks as per usage. It also inherits the AbstractCollection class. The important points about ArrayDeque class are: -Unlike Queue, we can add or remove elements from both sides. -Null elements are not allowed in the ArrayDeque. -ArrayDeque is not thread safe, in the absence of external synchronization. -ArrayDeque has no capacity restrictions. -ArrayDeque is faster than LinkedList and Stack.
What is ArrayDeque Hierarchy?
The hierarchy of ArrayDeque class is given in the figure displayed at the right side of the page.
What is the class declaration for ArrayDeque class?
Let's see the declaration for java.util.ArrayDeque class. public class ArrayDeque<E> extends AbstractCollection<E> implements Deque<E>, Cloneable, Serializable
Can you provide an example Java ArrayDeque?
FileName: ArrayDequeExample.java import java.util.*; public class ArrayDequeExample { public static void main(String[] args) { //Creating Deque and adding elements Deque<String> deque = new ArrayDeque<String>(); deque.add("Ravi"); deque.add("Vijay"); deque.add("Ajay"); //Traversing elements for (String str : deque) { System.out.println(str); } } } Output: Ravi Vijay Ajay
What is Java Map Interface?
A map contains values on the basis of key, i.e. key and value pair. Each key and value pair is known as an entry. A Map contains unique keys. A Map is useful if you have to search, update or delete elements on the basis of a key.
What are the Useful methods of Map interface?
Method: V put(Object key, Object value) Description: It is used to insert an entry in the map. Method: void putAll(Map map) Description: It is used to insert the specified map in the map. Method: V putIfAbsent(K key, V value) Description: It inserts the specified value with the specified key in the map only if it is not already specified. Method: V remove(Object key) Description: It is used to delete an entry for the specified key. Method: boolean remove(Object key, Object value) Description: It removes the specified values with the associated specified keys from the map. Method: Set keySet() Description: It returns the Set view containing all the keys Method: Set<Map.Entry<K,V>> entrySet() Description: It returns the Set view containing all the keys and values. Method: void clear() Description: It is used to reset the map. Method: V compute(K key, BiFunction<? super K,? super V,? extends V> remappingFunction) Description: It is used to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping). Method: V computeIfAbsent(K key, Function<? super K,? extends V> mappingFunction) Description: It is used to compute its value using the given mapping function, if the specified key is not already associated with a value (or is mapped to null), and enters it into this map unless null. Method: V computeIfPresent(K key, BiFunction<? super K,? super V,? extends V> remappingFunction) Description: It is used to compute a new mapping given the key and its current mapped value if the value for the specified key is present and non-null. Method: boolean containsValue(Object value) Description: This method returns true if some value equal to the value exists within the map, else return false. Method: boolean containsKey(Object key) Description: This method returns true if some key equal to the key exists within the map, else return false. Method: boolean equals(Object o) Description: It is used to compare the specified Object with the Map. Method: void forEach(BiConsumer<? super K,? super V> action) Description: It performs the given action for each entry in the map until all entries have been processed or the action throws an exception. Method: V get(Object key) Description: This method returns the object that contains the value associated with the key. Method: V getOrDefault(Object key, V defaultValue) Description: It returns the value to which the specified key is mapped, or defaultValue if the map contains no mapping for the key. Method: int hashCode() Description: It returns the hash code value for the Map Method: boolean isEmpty() Description: This method returns true if the map is empty; returns false if it contains at least one key. Method: V merge(K key, V value, BiFunction<? super V,? super V,? extends V> remappingFunction) Description: If the specified key is not already associated with a value or is associated with null, associates it with the given non-null value. Method: V replace(K key, V value) Description: It replaces the specified value for a specified key. Method: boolean replace(K key, V oldValue, V newValue) Description: It replaces the old value with the new value for a specified key. Method: void replaceAll(BiFunction<? super K,? super V,? extends V> function) Description: It replaces each entry's value with the result of invoking the given function on that entry until all entries have been processed or the function throws an exception. Method: Collection values() Description: It returns a collection view of the values contained in the map. Method: int size() Description: This method returns the number of entries in the map.
What is Map.Entry Interface?
Entry is the subinterface of Map. So we will be accessed it by Map.Entry name. It returns a collection-view of the map, whose elements are of this class. It provides methods to get key and value.
What are the Methods of Map.Entry interface?
Method: K getKey() Description: It is used to obtain a key. Method: V getValue() Description: It is used to obtain value. Method: int hashCode() Description: It is used to obtain hashCode. Method: V setValue(V value) Description: It is used to replace the value corresponding to this entry with the specified value. Method: boolean equals(Object o) Description: It is used to compare the specified object with the other existing objects. Method: static <K extends Comparable<? super K>,V> Comparator<Map.Entry<K,V>> comparingByKey() Description: It returns a comparator that compare the objects in natural order on key. Method: static <K,V> Comparator<Map.Entry<K,V>> comparingByKey(Comparator<? super K> cmp) Description: It returns a comparator that compare the objects by key using the given Comparator. Method: static <K,V extends Comparable<? super V>> Comparator<Map.Entry<K,V>> comparingByValue() Description: It returns a comparator that compare the objects in natural order on value. Method: static <K,V> Comparator<Map.Entry<K,V>> comparingByValue(Comparator<? super V> cmp) Description: It returns a comparator that compare the objects by value using the given Comparator.
Can you provide an example of Java Map: Non-Generic (Old Style)?
//Non-generic import java.util.*; public class MapExample1 { public static void main(String[] args) { Map map=new HashMap(); //Adding elements to map map.put(1,"Amit"); map.put(5,"Rahul"); map.put(2,"Jai"); map.put(6,"Amit"); //Traversing Map Set set=map.entrySet();//Converting to Set so that we can traverse Iterator itr=set.iterator(); while(itr.hasNext()){ //Converting to Map.Entry so that we can get key and value separately Map.Entry entry=(Map.Entry)itr.next(); System.out.println(entry.getKey()+" "+entry.getValue()); } } } Output: 1 Amit 2 Jai 5 Rahul 6 Amit
Can you provide an example of Java Map: Generic (New Style)?
import java.util.*; class MapExample2{ public static void main(String args[]){ Map<Integer,String> map=new HashMap<Integer,String>(); map.put(100,"Amit"); map.put(101,"Vijay"); map.put(102,"Rahul"); //Elements can traverse in any order for(Map.Entry m:map.entrySet()){ System.out.println(m.getKey()+" "+m.getValue()); } } } Output: 102 Rahul 100 Amit 101 Vijay
What is Java HashMap?
Java HashMap class implements the Map interface which allows us to store key and value pair, where keys should be unique. If you try to insert the duplicate key, it will replace the element of the corresponding key. It is easy to perform operations using the key index like updation, deletion, etc. HashMap class is found in the java.util package. HashMap in Java is like the legacy Hashtable class, but it is not synchronized. It allows us to store the null elements as well, but there should be only one null key. Since Java 5, it is denoted as HashMap<K,V>, where K stands for key and V for value. It inherits the AbstractMap class and implements the Map interface. Points to remember -Java HashMap contains values based on the key. -Java HashMap contains only unique keys. -Java HashMap may have one null key and multiple null values. -Java HashMap is non synchronized. -Java HashMap maintains no order. -The initial default capacity of Java HashMap class is 16 with a load factor of 0.75.
What is the class declaration for HashMap class?
Let's see the declaration for java.util.HashMap class. public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable
What is HashMap class Parameters?
Let's see the Parameters for java.util.HashMap class. -K: It is the type of keys maintained by this map. -V: It is the type of mapped values.
What are the Constructors of the Java HashMap?
Constructor: HashMap() Description: It is used to construct a default HashMap. Constructor: HashMap(Map<? extends K,? extends V> m) Description: It is used to initialize the hash map by using the elements of the given Map object m. Constructor: HashMap(int capacity) Description: It is used to initializes the capacity of the hash map to the given integer value, capacity. Constructor: HashMap(int capacity, float loadFactor) Description: It is used to initialize both the capacity and load factor of the hash map by using its arguments.
What are the Methods of Java HashMap class?
Method: void clear() Description: It is used to remove all of the mappings from this map. Method: boolean isEmpty() Description: It is used to return true if this map contains no key-value mappings. Method: Object clone() Description: It is used to return a shallow copy of this HashMap instance: the keys and values themselves are not cloned. Method: Set entrySet() Description: It is used to return a collection view of the mappings contained in this map. Method: Set keySet() Description: It is used to return a set view of the keys contained in this map. Method:V put(Object key, Object value) Description: It is used to insert an entry in the map. Method: void putAll(Map map) Description: It is used to insert the specified map in the map. Method: V putIfAbsent(K key, V value) Description: It inserts the specified value with the specified key in the map only if it is not already specified. Method: V remove(Object key) Description:It is used to delete an entry for the specified key. Method: boolean remove(Object key, Object value) Description: It removes the specified values with the associated specified keys from the map. Method: V compute(K key, BiFunction<? super K,? super V,? extends V> remappingFunction) Description: It is used to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping). Method:V computeIfAbsent(K key, Function<? super K,? extends V> mappingFunction) Description:It is used to compute its value using the given mapping function, if the specified key is not already associated with a value (or is mapped to null), and enters it into this map unless null. Method: V computeIfPresent(K key, BiFunction<? super K,? super V,? extends V> remappingFunction) Description: It is used to compute a new mapping given the key and its current mapped value if the value for the specified key is present and non-null. Method: boolean containsValue(Object value) Description: This method returns true if some value equal to the value exists within the map, else return false. Method: boolean containsKey(Object key) Description: This method returns true if some key equal to the key exists within the map, else return false. Method: boolean equals(Object o) Description: It is used to compare the specified Object with the Map. Method: void forEach(BiConsumer<? super K,? super V> action) Description: It performs the given action for each entry in the map until all entries have been processed or the action throws an exception. Method: V get(Object key) Description: This method returns the object that contains the value associated with the key. Method: V getOrDefault(Object key, V defaultValue) Description: It returns the value to which the specified key is mapped, or defaultValue if the map contains no mapping for the key. Method: boolean isEmpty() Description: This method returns true if the map is empty; returns false if it contains at least one key. Method: V merge(K key, V value, BiFunction<? super V,? super V,? extends V> remappingFunction) Description:If the specified key is not already associated with a value or is associated with null, associates it with the given non-null value. Method: V replace(K key, V value) Description: It replaces the specified value for a specified key. Method: boolean replace(K key, V oldValue, V newValue) Description: It replaces the old value with the new value for a specified key. Method: void replaceAll(BiFunction<? super K,? super V,? extends V> function) Description: It replaces each entry's value with the result of invoking the given function on that entry until all entries have been processed or the function throws an exception. Method: Collection<V> values() Description: It returns a collection view of the values contained in the map. Method: int size() Description: This method returns the number of entries in the map.
Can you provide an example of Java HashMap?
Let's see a simple example of HashMap to store key and value pair. import java.util.*; public class HashMapExample1{ public static void main(String args[]){ HashMap<Integer,String> map=new HashMap<Integer,String>();//Creating HashMap map.put(1,"Mango"); //Put elements in Map map.put(2,"Apple"); map.put(3,"Banana"); map.put(4,"Grapes"); System.out.println("Iterating Hashmap..."); for(Map.Entry m : map.entrySet()){ System.out.println(m.getKey()+" "+m.getValue()); } } } Iterating Hashmap... 1 Mango 2 Apple 3 Banana 4 Grapes In this example, we are storing Integer as the key and String as the value, so we are using HashMap<Integer,String> as the type. The put() method inserts the elements in the map. To get the key and value elements, we should call the getKey() and getValue() methods. The Map.Entry interface contains the getKey() and getValue() methods. But, we should call the entrySet() method of Map interface to get the instance of Map.Entry
What is HashMap?
HashMap is a part of the Java collection framework. It uses a technique called Hashing. It implements the map interface. It stores the data in the pair of Key and Value. HashMap contains an array of the nodes, and the node is represented as a class. It uses an array and LinkedList data structure internally for storing Key and Value. There are four fields in HashMap.
What is Java LinkedHashMap class?
Java LinkedHashMap class is Hashtable and Linked list implementation of the Map interface, with predictable iteration order. It inherits HashMap class and implements the Map interface. Points to remember -Java LinkedHashMap contains values based on the key. –Java LinkedHashMap contains unique elements. Java LinkedHashMap may have one null key and multiple null values. -Java LinkedHashMap is non synchronized. -Java LinkedHashMap maintains insertion order. -The initial default capacity of Java HashMap class is 16 with a load factor of 0.75.
What is the class declaration for LinkedHashMap?
Let's see the declaration for java.util.LinkedHashMap class. public class LinkedHashMap<K,V> extends HashMap<K,V> implements Map<K,V>
What is LinkedHashMap class Parameters?
Let's see the Parameters for java.util.LinkedHashMap class. -K: It is the type of keys maintained by this map. -V: It is the type of mapped values.
What are the Constructors of the Java LinkedHashMap class?
Constructor: LinkedHashMap() Description:It is used to construct a default LinkedHashMap. Constructor:LinkedHashMap(int capacity) Description:It is used to initialize a LinkedHashMap with the given capacity. Constructor:LinkedHashMap(int capacity, float loadFactor) Description:It is used to initialize both the capacity and the load factor. Constructor:LinkedHashMap(int capacity, float loadFactor, boolean accessOrder) Description:It is used to initialize both the capacity and the load factor with specified ordering mode. Constructor:LinkedHashMap(Map<? extends K,? extends V> m) Description:It is used to initialize the LinkedHashMap with the elements from the given Map class m.
What are the Methods of Java LinkedHashMap class?
Method: V get(Object key) Description: It returns the value to which the specified key is mapped. Method: void clear() Description: It removes all the key-value pairs from a map. Method: boolean containsValue(Object value) Description: It returns true if the map maps one or more keys to the specified value. Method: Set<Map.Entry<K,V>> entrySet() Description: It returns a Set view of the mappings contained in the map. Method: void forEach(BiConsumer<? super K,? super V> action) Description: It performs the given action for each entry in the map until all entries have been processed or the action throws an exception. Method: V getOrDefault(Object key, V defaultValue) Description: It returns the value to which the specified key is mapped or defaultValue if this map contains no mapping for the key. Method: Set<K> keySet() Description: It returns a Set view of the keys contained in the map Method: protected boolean removeEldestEntry(Map.Entry<K,V> eldest) Description: It returns true on removing its eldest entry. Method: void replaceAll(BiFunction<? super K,? super V,? extends V> function) Description: It replaces each entry's value with the result of invoking the given function on that entry until all entries have been processed or the function throws an exception. Method: Collection<V> values() Description: It returns a Collection view of the values contained in this map.
Can you provide an example of Java LinkedHashMap?
import java.util.*; class LinkedHashMap1{ public static void main(String args[]){ LinkedHashMap<Integer,String> hm=new LinkedHashMap<Integer,String>(); hm.put(100,"Amit"); hm.put(101,"Vijay"); hm.put(102,"Rahul"); for(Map.Entry m:hm.entrySet()){ System.out.println(m.getKey()+" "+m.getValue()); } } } Output:100 Amit 101 Vijay 102 Rahul
What is Java TreeMap class?
Java TreeMap class is a red-black tree based implementation. It provides an efficient means of storing key-value pairs in sorted order. The important points about Java TreeMap class are: -Java TreeMap contains values based on the key. It implements the NavigableMap interface and extends AbstractMap class. -Java TreeMap contains only unique elements. -Java TreeMap cannot have a null key but can have multiple null values. -Java TreeMap is non synchronized. -Java TreeMap maintains ascending order.
What is the class declaration for TreeMap class?
Let's see the declaration for java.util.TreeMap class. public class TreeMap<K,V> extends AbstractMap<K,V> implements NavigableMap<K,V>, Cloneable, Serializable
What is TreeMap class Parameters?
Let's see the Parameters for java.util.TreeMap class. -K: It is the type of keys maintained by this map. -V: It is the type of mapped values.
What are the Constructors of the Java TreeMap class?
Constructor:TreeMap() Description:It is used to construct an empty tree map that will be sorted using the natural order of its key. Constructor:TreeMap(Comparator<? super K> comparator) Description:It is used to construct an empty tree-based map that will be sorted using the comparator comp. Constructor:TreeMap(Map<? extends K,? extends V> m) Description:It is used to initialize a treemap with the entries from m, which will be sorted using the natural order of the keys. Constructor:TreeMap(SortedMap<K,? extends V> m) Description:It is used to initialize a treemap with the entries from the SortedMap sm, which will be sorted in the same order as sm.
What are the Methods of Java TreeMap class?
Method: Map.Entry<K,V> ceilingEntry(K key) Description: It returns the key-value pair having the least key, greater than or equal to the specified key, or null if there is no such key. Method: K ceilingKey(K key) Description: It returns the least key, greater than the specified key or null if there is no such key. Method: void clear() Description: It removes all the key-value pairs from a map. Method: Object clone() Description: It returns a shallow copy of TreeMap instance. Method: Comparator<? super K> comparator() Description: It returns the comparator that arranges the key in order, or null if the map uses the natural ordering. Method: NavigableSet<K> descendingKeySet() Description: It returns a reverse order NavigableSet view of the keys contained in the map. Method: NavigableMap<K,V> descendingMap() Description: It returns the specified key-value pairs in descending order. Method: Map.Entry firstEntry() Description: It returns the key-value pair having the least key. Method:Map.Entry<K,V> floorEntry(K key) Description: It returns the greatest key, less than or equal to the specified key, or null if there is no such key. Method: void forEach(BiConsumer<? super K,? super V> action) Description: It performs the given action for each entry in the map until all entries have been processed or the action throws an exception. Method: SortedMap<K,V> headMap(K toKey) Description: It returns the key-value pairs whose keys are strictly less than toKey. Method:NavigableMap<K,V> headMap(K toKey, boolean inclusive) Description: It returns the key-value pairs whose keys are less than (or equal to if inclusive is true) toKey. Method: Map.Entry<K,V> higherEntry(K key) Description: It returns the least key strictly greater than the given key, or null if there is no such key. Method: K higherKey(K key) Description: It is used to return true if this map contains a mapping for the specified key Method: Set keySet() Description: It returns the collection of keys exist in the map. Method: Map.Entry<K,V> lastEntry() Description: It returns the key-value pair having the greatest key, or null if there is no such key. Method: Map.Entry<K,V> lowerEntry(K key) Description: It returns a key-value mapping associated with the greatest key strictly less than the given key, or null if there is no such key. Method: K lowerKey(K key) Description: It returns the greatest key strictly less than the given key, or null if there is no such key. Method: NavigableSet<K> navigableKeySet() Description: It returns a NavigableSet view of the keys contained in this map. Method: Map.Entry<K,V> pollFirstEntry() Description: It removes and returns a key-value mapping associated with the least key in this map, or null if the map is empty. Method: Map.Entry<K,V> pollLastEntry() Description: It removes and returns a key-value mapping associated with the greatest key in this map, or null if the map is empty. Method: V put(K key, V value) Description: It inserts the specified value with the specified key in the map. Method: void putAll(Map<? extends K,? extends V> map) Description: It is used to copy all the key-value pair from one map to another map. Method: V replace(K key, V value) Description: It replaces the specified value for a specified key. Method: boolean replace(K key, V oldValue, V newValue) Description: It replaces the old value with the new value for a specified key. Method: void replaceAll(BiFunction<? super K,? super V,? extends V> function) Description: It replaces each entry's value with the result of invoking the given function on that entry until all entries have been processed or the function throws an exception. Method: NavigableMap<K,V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) Description: It returns key-value pairs whose keys range from fromKey to toKey. Method: SortedMap<K,V> subMap(K fromKey, K toKey) Description: It returns key-value pairs whose keys range from fromKey, inclusive, to toKey, exclusive. Method: SortedMap<K,V> tailMap(K fromKey) Description: It returns key-value pairs whose keys are greater than or equal to fromKey. Method: NavigableMap<K,V> tailMap(K fromKey, boolean inclusive) Description: It returns key-value pairs whose keys are greater than (or equal to, if inclusive is true) fromKey. Method: boolean containsKey(Object key) Description: It returns true if the map contains a mapping for the specified key. Method: boolean containsValue(Object value) Description:It returns true if the map maps one or more keys to the specified value. Method: K firstKey() Description: It is used to return the first (lowest) key currently in this sorted map. Method: V get(Object key) Description: It is used to return the value to which the map maps the specified key. Method: K lastKey() Description: It is used to return the last (highest) key currently in the sorted map. Method: V remove(Object key) Description: It removes the key-value pair of the specified key from the map. Method: Set<Map.Entry<K,V>> entrySet() Description: It returns a set view of the mappings contained in the map. Method: int size() Description: It returns the number of key-value pairs exists in the hashtable. Method: Collection values() Description: It returns a collection view of the values contained in the map.
Can you provide an example of Java TreeMap?
import java.util.*; class TreeMap1{ public static void main(String args[]){ TreeMap<Integer,String> map=new TreeMap<Integer,String>(); map.put(100,"Amit"); map.put(102,"Ravi"); map.put(101,"Vijay"); map.put(103,"Rahul"); for(Map.Entry m:map.entrySet()){ System.out.println(m.getKey()+" "+m.getValue()); } } } Output:100 Amit 101 Vijay 102 Ravi 103 Rahul
What is Java Hashtable class?
Java Hashtable class implements a hashtable, which maps keys to values. It inherits Dictionary class and implements the Map interface. Points to remember -A Hashtable is an array of a list. Each list is known as a bucket. The position of the bucket is identified by calling the hashcode() method. A Hashtable contains values based on the key. -Java Hashtable class contains unique elements. -Java Hashtable class doesn't allow null key or value. -Java Hashtable class is synchronized. -The initial default capacity of Hashtable class is 11 whereas loadFactor is 0.75.
What is the class declaration for Hashtable class?
Let's see the declaration for java.util.Hashtable class. public class Hashtable<K,V> extends Dictionary<K,V> implements Map<K,V>, Cloneable, Serializable
What is Hashtable class Parameters?
Let's see the Parameters for java.util.Hashtable class. -K: It is the type of keys maintained by this map. -V: It is the type of mapped values.
What are the Constructors of the Java Hashtable class?
Constructor:Hashtable() Description:It creates an empty hashtable having the initial default capacity and load factor. Constructor:Hashtable(int capacity) Description:It accepts an integer parameter and creates a hash table that contains a specified initial capacity. Constructor:Hashtable(int capacity, float loadFactor) Description:It is used to create a hash table having the specified initial capacity and loadFactor. Constructor:Hashtable(Map<? extends K,? extends V> t) Description:It creates a new hash table with the same mappings as the given Map.
What are the Methods of Java Hashtable class?
Method: void clear() Description: It is used to reset the hash table. Method: Object clone() Description: It returns a shallow copy of the Hashtable. Method: V compute(K key, BiFunction<? super K,? super V,? extends V> remappingFunction) Description: It is used to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping). Method: V computeIfAbsent(K key, Function<? super K,? extends V> mappingFunction) Description: It is used to compute its value using the given mapping function, if the specified key is not already associated with a value (or is mapped to null), and enters it into this map unless null. Method: V computeIfPresent(K key, BiFunction<? super K,? super V,? extends V> remappingFunction) Description: It is used to compute a new mapping given the key and its current mapped value if the value for the specified key is present and non-null. Method: Enumeration elements() Description: It returns an enumeration of the values in the hash table. Method: Set<Map.Entry<K,V>> entrySet() Description: It returns a set view of the mappings contained in the map. Method: boolean equals(Object o) Description: It is used to compare the specified Object with the Map. Method: void forEach(BiConsumer<? super K,? super V> action) Description: It performs the given action for each entry in the map until all entries have been processed or the action throws an exception. Method: V getOrDefault(Object key, V defaultValue) Description: It returns the value to which the specified key is mapped, or defaultValue if the map contains no mapping for the key. Method: int hashCode() Description: It returns the hash code value for the Map Method: Enumeration<K> keys() Description: It returns an enumeration of the keys in the hashtable. Method: Set<K> keySet() Description: It returns a Set view of the keys contained in the map. Method: V merge(K key, V value, BiFunction<? super V,? super V,? extends V> remappingFunction) Description: If the specified key is not already associated with a value or is associated with null, associates it with the given non-null value. Method: V put(K key, V value) Description: It inserts the specified value with the specified key in the hash table. Method: void putAll(Map<? extends K,? extends V> t)) Description: It is used to copy all the key-value pair from map to hashtable. Method: V putIfAbsent(K key, V value) Description: If the specified key is not already associated with a value (or is mapped to null) associates it with the given value and returns null, else returns the current value. Method: boolean remove(Object key, Object value) Description: It removes the specified values with the associated specified keys from the hashtable. Method: V replace(K key, V value) Description: It replaces the specified value for a specified key. Method: boolean replace(K key, V oldValue, V newValue) Description: It replaces the old value with the new value for a specified key. Method: void replaceAll(BiFunction<? super K,? super V,? extends V> function) Description: It replaces each entry's value with the result of invoking the given function on that entry until all entries have been processed or the function throws an exception. Method: String toString() Description: It returns a string representation of the Hashtable object. Method: Collection values() Description: It returns a collection view of the values contained in the map. Method: boolean contains(Object value) Description: This method returns true if some value equal to the value exists within the hash table, else return false. Method: boolean containsValue(Object value) Description: This method returns true if some value equal to the value exists within the hash table, else return false. Method: boolean containsKey(Object key) Description: This method return true if some key equal to the key exists within the hash table, else return false. Method: boolean isEmpty() Description: This method returns true if the hash table is empty; returns false if it contains at least one key. Method: protected void rehash() Description: It is used to increase the size of the hash table and rehashes all of its keys. Method: V get(Object key) Description: This method returns the object that contains the value associated with the key. Method: V remove(Object key) Description: It is used to remove the key and its value. This method returns the value associated with the key. Method: int size() Description: This method returns the number of entries in the hash table.
Can you provide an example of Java Hashtable?
import java.util.*; class Hashtable1{ public static void main(String args[]){ Hashtable<Integer,String> hm=new Hashtable<Integer,String>(); hm.put(100,"Amit"); hm.put(102,"Ravi"); hm.put(101,"Vijay"); hm.put(103,"Rahul"); for(Map.Entry m:hm.entrySet()){ System.out.println(m.getKey()+" "+m.getValue()); } } } Output: 103 Rahul 102 Ravi 101 Vijay 100 Amit
What are the Difference between HashMap and Hashtable?
HashMap and Hashtable both are used to store data in key and value form. Both are using hashing technique to store unique keys. But there are many differences between HashMap and Hashtable classes that are given below. 1) HashMap is non synchronized. It is not-thread safe and can't be shared between many threads without proper synchronization code while Hashtable is synchronized. It is thread-safe and can be shared with many threads. 2) HashMap allows one null key and multiple null values while Hashtable doesn't allow any null key or value. 3) HashMap is a new class introduced in JDK 1.2 while Hashtable is a legacy class. 4) HashMap is fast while Hashtable is slow. 5) We can make the HashMap as synchronized by calling this code Map m = Collections.synchronizedMap(hashMap); while Hashtable is internally synchronized and can't be unsynchronized. 6) HashMap is traversed by Iterator while Hashtable is traversed by Enumerator and Iterator. 7) Iterator in HashMap is fail-fast while Enumerator in Hashtable is not fail-fast. 8) HashMap inherits AbstractMap class while Hashtable inherits Dictionary class.
What is Java EnumSet class?
Java EnumSet class is the specialized Set implementation for use with enum types. It inherits AbstractSet class and implements the Set interface.
What is the class declaration for EnumSet class?
Let's see the declaration for java.util.EnumSet class. public abstract class EnumSet<E extends Enum<E>> extends AbstractSet<E> implements Cloneable, Serializable
What are the Methods of Java EnumSet class?
Method: static <E extends Enum<E>> EnumSet<E> allOf(Class<E> elementType) Description: It is used to create an enum set containing all of the elements in the specified element type. Method: static <E extends Enum<E>> EnumSet<E> copyOf(Collection<E> c) Description: It is used to create an enum set initialized from the specified collection. Method: static <E extends Enum<E>> EnumSet<E> noneOf(Class<E> elementType) Description: It is used to create an empty enum set with the specified element type. Method: static <E extends Enum<E>> EnumSet<E> of(E e) Description: It is used to create an enum set initially containing the specified element. Method: static <E extends Enum<E>> EnumSet<E> range(E from, E to) Description: It is used to create an enum set initially containing the specified elements. Method: EnumSet<E> clone() Description: It is used to return a copy of this set.
Can you provide an example of Java EnumSet?
import java.util.*; enum days { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY } public class EnumSetExample { public static void main(String[] args) { Set<days> set = EnumSet.of(days.TUESDAY, days.WEDNESDAY); // Traversing elements Iterator<days> iter = set.iterator(); while (iter.hasNext()) System.out.println(iter.next()); } } Output: TUESDAY WEDNESDAY
What is Java EnumMap class?
Java EnumMap class is the specialized Map implementation for enum keys. It inherits Enum and AbstractMap classes.
What is the class declaration for EnumMap class?
Let's see the declaration for java.util.EnumMap class. public class EnumMap<K extends Enum<K>,V> extends AbstractMap<K,V> implements Serializable, Cloneable
What is EnumMap class Parameters?
Let's see the Parameters for java.util.EnumMap class. -K: It is the type of keys maintained by this map. -V: It is the type of mapped values.
What are the Constructors of the Java EnumMap class?
Constructor: EnumMap(Class<K> keyType) Description: It is used to create an empty enum map with the specified key type. Constructor: EnumMap(EnumMap<K,? extends V> m) Description: It is used to create an enum map with the same key type as the specified enum map. Constructor: EnumMap(Map<K,? extends V> m) Description:It is used to create an enum map initialized from the specified map.
What are the Methods of Java EnumMap class?
Sn:1 Method: clear() Description: It is used to clear all the mapping from the map. Sn:2 Method:clone() Description: It is used to copy the mapped value of one map to another map. Sn:3 Method:containsKey() Description:It is used to check whether a specified key is present in this map or not. Sn:4 Method:containsValue() Description: It is used to check whether one or more key is associated with a given value or not. Sn:5 Method:entrySet() Description:It is used to create a set of elements contained in the EnumMap. Sn:6 Method:equals() Description: It is used to compare two maps for equality. Sn:7 Method: get() Description: It is used to get the mapped value of the specified key. Sn:8 Method: hashCode() Description: It is used to get the hashcode value of the EnumMap. Sn:9 Method:keySet() Description: It is used to get the set view of the keys contained in the map. Sn:10 Method: size() Description: It is used to get the size of the EnumMap. Sn:11 Method:Values() Description: It is used to create a collection view of the values contained in this map. Sn:12 Method: put() Description: It is used to associate the given value with the given key in this EnumMap Sn:13 Method: putAll() Description: It is used to copy all the mappings from one EnumMap to a new EnumMap. Sn:14 Method: remove() Description: It is used to remove the mapping for the given key from EnumMap if the given key is present.
Can you provide an example of Java EnumMap?
import java.util.*; public class EnumMapExample { // create an enum public enum Days { Monday, Tuesday, Wednesday, Thursday }; public static void main(String[] args) { //create and populate enum map EnumMap<Days, String> map = new EnumMap<Days, String>(Days.class); map.put(Days.Monday, "1"); map.put(Days.Tuesday, "2"); map.put(Days.Wednesday, "3"); map.put(Days.Thursday, "4"); // print the map for(Map.Entry m:map.entrySet()){ System.out.println(m.getKey()+" "+m.getValue()); } } } Output: Monday 1 Tuesday 2 Wednesday 3 Thursday 4
What is Java Collections class?
Java collection class is used exclusively with static methods that operate on or return collections. It inherits Object class. The important points about Java Collections class are: -Java Collection class supports the polymorphic algorithms that operate on collections. -Java Collection class throws a NullPointerException if the collections or class objects provided to them are null.
What is the class declaration for Collections class?
Let's see the declaration for java.util.Collections class. public class Collections extends Object
Can you provide an example of Java Collections?
import java.util.*; public class CollectionsExample { public static void main(String a[]){ List<String> list = new ArrayList<String>(); list.add("C"); list.add("Core Java"); list.add("Advance Java"); System.out.println("Initial collection value:"+list); Collections.addAll(list, "Servlet","JSP"); System.out.println("After adding elements collection value:"+list); String[] strArr = {"C#", ".Net"}; Collections.addAll(list, strArr); System.out.println("After adding array collection value:"+list); } } Output: Initial collection value:[C, Core Java, Advance Java] After adding elements collection value:[C, Core Java, Advance Java, Servlet, JSP] After adding array collection value:[C, Core Java, Advance Java, Servlet, JSP, C#, .Net]
What is Sorting in Collection?
We can sort the elements of: -String objects -Wrapper class objects -User-defined class objects Collections class provides static methods for sorting the elements of a collection. If collection elements are of a Set type, we can use TreeSet. However, we cannot sort the elements of List. Collections class provides methods for sorting the elements of List type elements.
What is the Method of Collections class for sorting List elements?
public void sort(List list): is used to sort the elements of List. List elements must be of the Comparable type.
Can you provide an example to sort string objects?
import java.util.*; class TestSort1{ public static void main(String args[]){ ArrayList<String> al=new ArrayList<String>(); al.add("Viru"); al.add("Saurav"); al.add("Mukesh"); al.add("Tahir"); Collections.sort(al); Iterator itr=al.iterator(); while(itr.hasNext()){ System.out.println(itr.next()); } } } Mukesh Saurav Tahir Viru
What is Java Comparable interface?
Java Comparable interface is used to order the objects of the user-defined class. This interface is found in java.lang package and contains only one method named compareTo(Object). It provides a single sorting sequence only, i.e., you can sort the elements on the basis of single data member only. For example, it may be rollno, name, age or anything else.
What is compareTo(Object obj) method?
public int compareTo(Object obj): It is used to compare the current object with the specified object. It returns -positive integer, if the current object is greater than the specified object. -negative integer, if the current object is less than the specified object. -zero, if the current object is equal to the specified object.
What is Java Comparator interface?
Java Comparator interface is used to order the objects of a user-defined class. This interface is found in java.util package and contains 2 methods compare(Object obj1,Object obj2) and equals(Object element). It provides multiple sorting sequences, i.e., you can sort the elements on the basis of any data member, for example, rollno, name, age or anything else.
What are the Methods of Java Comparator Interface?
Method: public int compare(Object obj1, Object obj2) Description: It compares the first object with the second object. Method: public boolean equals(Object obj) Description: It is used to compare the current object with the specified object. Method: public boolean equals(Object obj) Description: It is used to compare the current object with the specified object.
Can you provide an example of Java Comparator (Non-generic Old Style)?
Let's see the example of sorting the elements of List on the basis of age and name. In this example, we have created 4 java classes: 1.Student.java 2..AgeComparator.java 3.NameComparator.java 4.Simple.java Student.java This class contains three fields rollno, name and age and a parameterized constructor. class Student{ int rollno; String name; int age; Student(int rollno,String name,int age){ this.rollno=rollno; this.name=name; this.age=age; } } AgeComparator.java This class defines comparison logic based on the age. If the age of the first object is greater than the second, we are returning a positive value. It can be anyone such as 1, 2, 10. If the age of the first object is less than the second object, we are returning a negative value, it can be any negative value, and if the age of both objects is equal, we are returning 0. import java.util.*; class AgeComparator implements Comparator{ public int compare(Object o1,Object o2){ Student s1=(Student)o1; Student s2=(Student)o2; if(s1.age==s2.age) return 0; else if(s1.age>s2.age) return 1; else return -1; } } NameComparator.java This class provides comparison logic based on the name. In such case, we are using the compareTo() method of String class, which internally provides the comparison logic. import java.util.*; class NameComparator implements Comparator{ public int compare(Object o1,Object o2){ Student s1=(Student)o1; Student s2=(Student)o2; return s1.name.compareTo(s2.name); } } Simple.java In this class, we are printing the values of the object by sorting on the basis of name and age. import java.util.*; import java.io.*; class Simple{ public static void main(String args[]){ ArrayList al=new ArrayList(); al.add(new Student(101,"Vijay",23)); al.add(new Student(106,"Ajay",27)); al.add(new Student(105,"Jai",21)); System.out.println("Sorting by Name"); Collections.sort(al,new NameComparator()); Iterator itr=al.iterator(); while(itr.hasNext()){ Student st=(Student)itr.next(); System.out.println(st.rollno+" "+st.name+" "+st.age); } System.out.println("Sorting by age"); Collections.sort(al,new AgeComparator()); Iterator itr2=al.iterator(); while(itr2.hasNext()){ Student st=(Student)itr2.next(); System.out.println(st.rollno+" "+st.name+" "+st.age); } } } Sorting by Name 106 Ajay 27 105 Jai 21 101 Vijay 23 Sorting by age 105 Jai 21 101 Vijay 23 106 Ajay 27
Can you provide an example of Java Comparator (Generic)?
Student.java class Student{ int rollno; String name; int age; Student(int rollno,String name,int age){ this.rollno=rollno; this.name=name; this.age=age; } } AgeComparator.java import java.util.*; class AgeComparator implements Comparator<Student>{ public int compare(Student s1,Student s2){ if(s1.age==s2.age) return 0; else if(s1.age>s2.age) return 1; else return -1; } } NameComparator.java This class provides comparison logic based on the name. In such case, we are using the compareTo() method of String class, which internally provides the comparison logic. import java.util.*; class NameComparator implements Comparator<Student>{ public int compare(Student s1,Student s2){ return s1.name.compareTo(s2.name); } } Simple.java In this class, we are printing the values of the object by sorting on the basis of name and age. import java.util.*; import java.io.*; class Simple{ public static void main(String args[]){ ArrayList<Student> al=new ArrayList<Student>(); al.add(new Student(101,"Vijay",23)); al.add(new Student(106,"Ajay",27)); al.add(new Student(105,"Jai",21)); System.out.println("Sorting by Name"); Collections.sort(al,new NameComparator()); for(Student st: al){ System.out.println(st.rollno+" "+st.name+" "+st.age); } System.out.println("Sorting by age"); Collections.sort(al,new AgeComparator()); for(Student st: al){ System.out.println(st.rollno+" "+st.name+" "+st.age); } } } Sorting by Name 106 Ajay 27 105 Jai 21 101 Vijay 23 Sorting by age 105 Jai 21 101 Vijay 23 106 Ajay 27
What is Properties class in Java?
The properties object contains key and value pair both as a string. The java.util.Properties class is the subclass of Hashtable. It can be used to get property value based on the property key. The Properties class provides methods to get data from the properties file and store data into the properties file. Moreover, it can be used to get the properties of a system
What is the Advantage of the properties file?
Recompilation is not required if the information is changed from a properties file: If any information is changed from the properties file, you don't need to recompile the java class. It is used to store information which is to be changed frequently.
What are the Constructors of the Properties class?
Constructor:Properties() Description: It creates an empty property list with no default values. Constructor:Properties(Properties defaults) Description:It creates an empty property list with the specified defaults.
What are the Methods of Properties class?
Method: public void load(Reader r) Description: It loads data from the Reader object. Method: public void load(InputStream is) Description: It loads data from the InputStream object Method: public void loadFromXML(InputStream in) Description: It is used to load all of the properties represented by the XML document on the specified input stream into this properties table. Method: public String getProperty(String key) Description: It returns value based on the key. Method:public String getProperty(String key, String defaultValue) Description: It searches for the property with the specified key. Method:public void setProperty(String key, String value) Description: It calls the put method of Hashtable. Method: public void list(PrintStream out) Description: It is used to print the property list out to the specified output stream. Method: public void list(PrintWriter out)) Description: It is used to print the property list out to the specified output stream. Method: public Enumeration<?> propertyNames()) Description: It returns an enumeration of all the keys from the property list. Method: public Set<String> stringPropertyNames() Description: It returns a set of keys in from property list where the key and its corresponding value are strings. Method:public void store(Writer w, String comment) Description: It writes the properties in the writer object. Method: public void store(OutputStream os, String comment) Description: It writes the properties in the OutputStream object. Method: public void storeToXML(OutputStream os, String comment) Description: It writes the properties in the writer object for generating XML document. Method: public void storeToXML(Writer w, String comment, String encoding) Description: It writes the properties in the writer object for generating XML document with the specified encoding.
Can you provide an example of Properties class to get information from the properties file?
To get information from the properties file, create the properties file first. db.properties user=system password=oracle Now, let's create the java class to read the data from the properties file. Test.java import java.util.*; import java.io.*; public class Test { public static void main(String[] args)throws Exception{ FileReader reader=new FileReader("db.properties"); Properties p=new Properties(); p.load(reader); System.out.println(p.getProperty("user")); System.out.println(p.getProperty("password")); } } Output:system oracle Now if you change the value of the properties file, you don't need to recompile the java class. That means no maintenance problem.
What are the Difference between ArrayList and Vector?
ArrayList and Vector both implements List interface and maintains insertion order. However, there are many differences between ArrayList and Vector classes that are given below. 1) ArrayList is not synchronized while Vector is synchronized. 2) ArrayList increments 50% of current array size if the number of elements exceeds from its capacity while Vector increments 100% means doubles the array size if the total number of elements exceeds than its capacity. 3) ArrayList is not a legacy class. It is introduced in JDK 1.2 while Vector is a legacy class. 4) ArrayList is fast because it is non-synchronized while Vector is slow because it is synchronized, i.e., in a multithreading environment, it holds the other threads in runnable or non-runnable state until current thread releases the lock of the object. 5) ArrayList uses the Iterator interface to traverse the elements while A Vector can use the Iterator interface or Enumeration interface to traverse the elements.
What is Java Vector?
Vector is like the dynamic array which can grow or shrink its size. Unlike array, we can store n-number of elements in it as there is no size limit. It is a part of Java Collection framework since Java 1.2. It is found in the java.util package and implements the List interface, so we can use all the methods of List interface here. It is recommended to use the Vector class in the thread-safe implementation only. If you don't need to use the thread-safe implementation, you should use the ArrayList, the ArrayList will perform better in such case. The Iterators returned by the Vector class are fail-fast. In case of concurrent modification, it fails and throws the ConcurrentModificationException. It is similar to the ArrayList, but with two differences- -Vector is synchronized. -Java Vector contains many legacy methods that are not the part of a collections framework.
What is the class declaration for Java Vector class?
public class Vector<E> extends Object<E> implements List<E>, Cloneable, Serializable
What are the Constructors of the Java Vector?
SN:1 Constructor: vector() Description: It constructs an empty vector with the default size as 10. SN:2 Constructor: vector(int initialCapacity) Description: It constructs an empty vector with the specified initial capacity and with its capacity increment equal to zero. SN:3 Constructor: vector(int initialCapacity, int capacityIncrement) Description: It constructs an empty vector with the specified initial capacity and capacity increment. SN:4 Constructor: Vector( Collection<? extends E> c) Description: It constructs a vector that contains the elements of a collection c.
Can you provide an example of Java Vector?
import java.util.*; public class VectorExample { public static void main(String args[]) { //Create a vector Vector<String> vec = new Vector<String>(); //Adding elements using add() method of List vec.add("Tiger"); vec.add("Lion"); vec.add("Dog"); vec.add("Elephant"); //Adding elements using addElement() method of Vector vec.addElement("Rat"); vec.addElement("Cat"); vec.addElement("Deer"); System.out.println("Elements are: "+vec); } } Output: Elements are: [Tiger, Lion, Dog, Elephant, Rat, Cat, Deer]
What are the methods of Java Stack?
SN:1 Method: add() Description: It is used to append the specified element in the given vector. SN:2 Method: addAll() Description:It is used to append all of the elements in the specified collection to the end of this Vector. SN:3 Method:addElement() Description:It is used to append the specified component to the end of this vector. It increases the vector size by one. SN:4 Method: capacity() Description:It is used to get the current capacity of this vector. SN:5 Method: clear() Description:It is used to delete all of the elements from this vector. SN:6 Method: clone() Description:It returns a clone of this vector. SN:7 Method: contains() Description:It returns true if the vector contains the specified element. SN:8 Method: containsAll() Description:It returns true if the vector contains all of the elements in the specified collection. SN:9 Method: copyInto() Description:It is used to copy the components of the vector into the specified array. SN:10 Method: elementAt() Description:It is used to get the component at the specified index. SN:11 Method: elements() Description: It returns an enumeration of the components of a vector. SN:12 Method: ensureCapacity() Description:It is used to increase the capacity of the vector which is in use, if necessary. It ensures that the vector can hold at least the number of components specified by the minimum capacity argument. SN:13 Method: equals() Description:It is used to compare the specified object with the vector for equality. SN:14 Method: firstElement() Description:It is used to get the first component of the vector. SN:15 Method: forEach() Description:It is used to perform the given action for each element of the Iterable until all elements have been processed or the action throws an exception. SN:16 Method: get() Description:It is used to get an element at the specified position in the vector. SN:17 Method: hashCode() Description:It is used to get the hash code value of a vector SN:18 Method: indexOf() Description:It is used to get the index of the first occurrence of the specified element in the vector. It returns -1 if the vector does not contain the element. SN:19 Method: insertElementAt() Description:It is used to insert the specified object as a component in the given vector at the specified index. SN:20 Method: isEmpty() Description:It is used to check if this vector has no components. SN:21 Method: iterator() Description: It is used to get an iterator over the elements in the list in proper sequence. SN:22 Method:lastElement() Description:It is used to get the last component of the vector. SN:23 Method: lastIndexOf() Description: It is used to get the index of the last occurrence of the specified element in the vector. It returns -1 if the vector does not contain the element. SN:24 Method: listIterator() Description:It is used to get a list iterator over the elements in the list in proper sequence. SN:25 Method: remove() Description:It is used to remove the specified element from the vector. If the vector does not contain the element, it is unchanged. SN:26 Method: removeAll() Description: It is used to delete all the elements from the vector that are present in the specified collection. SN:27 Method: removeAllElements() Description:It is used to remove all elements from the vector and set the size of the vector to zero. SN:28 Method: removeElement() Description:It is used to remove the first (lowest-indexed) occurrence of the argument from the vector. SN:29 Method: removeElementAt() Description:It is used to delete the component at the specified index. SN:30 Method: removeIf() Description:It is used to remove all of the elements of the collection that satisfy the given predicate. SN:31 Method: removeRange() Description:It is used to delete all of the elements from the vector whose index is between fromIndex, inclusive and toIndex, exclusive. SN:32 Method: replaceAll() Description:It is used to replace each element of the list with the result of applying the operator to that element. SN:33 Method: retainAll() Description:It is used to retain only that element in the vector which is contained in the specified collection. SN:34 Method: set() Description:It is used to replace the element at the specified position in the vector with the specified element. SN:35 Method: setElementAt() Description:It is used to set the component at the specified index of the vector to the specified object. SN:36 Method: setSize() Description:It is used to set the size of the given vector. SN:37 Method: size() Description:It is used to get the number of components in the given vector. SN:38 Method: sort() Description:It is used to sort the list according to the order induced by the specified Comparator. SN:39 Method: spliterator() Description:It is used to create a late-binding and fail-fast Spliterator over the elements in the list. SN:40 Method: subList() Description:It is used to get a view of the portion of the list between fromIndex, inclusive, and toIndex, exclusive. SN:41 Method: toArray() Description:It is used to get an array containing all of the elements in this vector in correct order. SN:42 Method: toString() Description:It is used to get a string representation of the vector. SN:43 Method: trimToSize() Description:It is used to trim the capacity of the vector to the vector's current size.
What is Java Stack Class?
In Java, Stack is a class that falls under the Collection framework that extends the Vector class. It also implements interfaces List, Collection, Iterable, Cloneable, Serializable. It represents the LIFO stack of objects. Before using the Stack class, we must import the java.util package. The stack class arranged in the Collections framework hierarchy.
What are the Constructors of the Stack Class?
The Stack class contains only the default constructor that creates an empty stack. public Stack()
How to Creat a Stack?
If we want to create a stack, first, import the java.util package and create an object of the Stack class. Stack stk = new Stack(); Or Stack<type> stk = new Stack<>();
What are the Methods of the Stack Class?
We can perform push, pop, peek and search operation on the stack. The Java Stack class provides mainly five methods to perform these operations. Along with this, it also provides all the methods of the Java Vector class. Method: empty() Modifier and Type: boolean Description: The method checks the stack is empty or not. Method: push(E item) Modifier and Type: E Description: The method pushes (insert) an element onto the top of the stack. Method: pop() Modifier and Type: : E Description: The method removes an element from the top of the stack and returns the same element as the value of that function. Method: peek() Modifier and Type: : E Description: The method looks at the top element of the stack without removing it. Method: search(Object o) Modifier and Type: int Description: The method searches the specified object and returns the position of the object.
What is Java Collection Interface?
Collection is a group of objects, which are known as elements. It is the root interface in the collection hierarchy. This interface is basically used to pass around the collections and manipulate them where the maximum generality is desired.
What is Iterator in Java?
In Java, an Iterator is one of the Java cursors. Java Iterator is an interface that is practiced in order to iterate over a collection of Java object components entirety one by one. It is free to use in the Java programming language since the Java 1.2 Collection framework. It belongs to java.util package. Though Java Iterator was introduced in Java 1.2, however, it is still not the oldest tool available to traverse through the elements of the Collection object. The oldest Iterator in the Java programming language is the Enumerator predated Iterator. Java Iterator interface succeeds the enumerator iterator that was practiced in the beginning to traverse over some accessible collections like the ArrayLists. The Java Iterator is also known as the universal cursor of Java as it is appropriate for all the classes of the Collection framework. The Java Iterator also helps in the operations like READ and REMOVE. When we compare the Java Iterator interface with the enumeration iterator interface, we can say that the names of the methods available in Java Iterator are more precise and straightforward to use.
What are the Advantages of Java Iterator?
Iterator in Java became very prevalent due to its numerous advantages. The advantages of Java Iterator are given as follows : -The user can apply these iterators to any of the classes of the Collection framework. -In Java Iterator, we can use both of the read and remove operations. -If a user is working with a for loop, they cannot modernize(add/remove) the Collection, whereas, if they use the Java Iterator, they can simply update the Collection. -The Java Iterator is considered the Universal Cursor for the Collection API. -The method names in the Java Iterator are very easy and are very simple to use.
What are the Disadvantages of Java Iterator?
Despite the numerous advantages, the Java Iterator has various disadvantages also. The disadvantages of the Java Iterator are given below : -The Java Iterator only preserves the iteration in the forward direction. In simple words, the Java Iterator is a uni-directional Iterator. -The replacement and extension of a new component are not approved by the Java Iterator. -In CRUD Operations, the Java Iterator does not hold the various operations like CREATE and UPDATE. -In comparison with the Spliterator, Java Iterator does not support traversing elements in the parallel pattern which implies that Java Iterator supports only Sequential iteration. -In comparison with the Spliterator, Java Iterator does not support more reliable execution to traverse the bulk volume of data.
How to use Java Iterator?
When a user needs to use the Java Iterator, then it's compulsory for them to make an instance of the Iterator interface from the collection of objects they desire to traverse over. After that, the received Iterator maintains the trail of the components in the underlying collection to make sure that the user will traverse over each of the elements of the collection of objects. If the user modifies the underlying collection while traversing over an Iterator leading to that collection, then the Iterator will typically acknowledge it and will throw an exception in the next time when the user will attempt to get the next component from the Iterator.
What are the methods of Java Iterator?
The following figure perfectly displays the class diagram of the Java Iterator interface. It contains a total of four methods that are: -hasNext() -next() -remove() -forEachRemaining() The forEachRemaining() method was added in the Java 8. Let's discuss each method in detail. -boolean hasNext(): The method does not accept any parameter. It returns true if there are more elements left in the iteration. If there are no more elements left, then it will return false. If there are no more elements left in the iteration, then there is no need to call the next() method. In simple words, we can say that the method is used to determine whether the next() method is to be called or not. -E next(): It is similar to hasNext() method. It also does not accept any parameter. It returns E, i.e., the next element in the traversal. If the iteration or collection of objects has no more elements left to iterate, then it throws the NoSuchElementException. -default void remove(): This method also does not require any parameters. There is no return type of this method. The main function of this method is to remove the last element returned by the iterator traversing through the underlying collection. The remove () method can be requested hardly once per the next () method call. If the iterator does not support the remove operation, then it throws the UnSupportedOperationException. It also throws the IllegalStateException if the next method is not yet called. -default void forEachRemaining(Consumer action): It is the only method of Java Iterator that takes a parameter. It accepts action as a parameter. Action is nothing but that is to be performed. There is no return type of the method. This method performs the particularized operation on all of the left components of the collection until all the components are consumed or the action throws an exception. Exceptions thrown by action are delivered to the caller. If the action is null, then it throws a NullPointerException.
Can you provide an example of Java Iterator?
Now it's time to execute a Java program to illustrate the advantage of the Java Iterator interface. The below code produces an ArrayList of city names. Then we initialize an iterator applying the iterator () method of the ArrayList. After that, the list is traversed to represent each element. JavaIteratorExample.java import java.io.*; import java.util.*; public class JavaIteratorExample { public static void main(String[] args) { ArrayList<String> cityNames = new ArrayList<String>(); cityNames.add("Delhi"); cityNames.add("Mumbai"); cityNames.add("Kolkata"); cityNames.add("Chandigarh"); cityNames.add("Noida"); // Iterator to iterate the cityNames Iterator iterator = cityNames.iterator(); System.out.println("CityNames elements : "); while (iterator.hasNext()) System.out.print(iterator.next() + " "); System.out.println(); } } Output: CityNames elements: Delhi Mumbai Kolkata Chandigarh Noida
What is Java Deque?
A deque is a linear collection that supports insertion and deletion of elements from both the ends. The name 'deque' is an abbreviation for double-ended queue. There are no fixed limits on the deque for the number of elements they may contain. However, this interface supports capacity restricted deques as well as the deques with no fixed size limits. There are various methods which are provided to insert, remove and examine the elements. These methods typically exist in two forms: the one that throws an exception when the particular operation fails and the other returns a special value which can be either null or false depending upon the operations.
What are the methods of Java Deque?
Method: add(E e) Description: This method is used to insert a specified element into the queue represented by the deque Method: addAll(Collection<? Extends E>c) Description: Adds all the elements in the specified collection at the end of the deque. Method: addFirst(E e) Description: Inserts the specified element at the front of the deque. Method: addLast(E e) Description: Inserts the specified element at the end of the deque. Method: contains(object o) Description: Returns true if the deque contains the specified element. Method: descendingIterator() Description: Returns an iterator over the elements in reverse sequential order. Method: element() Description: Retrieves the head of the queue represented by the deque. Method: getFirst() Description: Retrieves but does not remove the first element of the deque Method: getLast() Description: Retrieves but does not remove the last element of the deque. Method:iterator() Description: Returns an iterator over the element in the deque in a proper sequence. Method: offer(E e) Description: Inserts the specified element into the deque, returning true upon success and false if no space is available. Method:offerFirst() Description: Inserts the specified element at the front of the deque unless it violates the capacity restriction. Method: offerLast() Description: Inserts the specified element at the end of the deque unless it violates the capacity restriction. Method: peek() Description: Retrieves but does not move the head of the queue represented by the deque or may return null if the deque is empty. Method: peekFirst() Description: Retrieves but does not move the first element of the deque or may return null if the deque is empty. Method: peekLast() Description: Retrieves but does not move the last element of the deque or may return null if the deque is empty. Method: poll() Description: Retrieves and remove the head of the queue represented by the deque or may return null if the deque is empty. Method: pollFirst() Description: Retrieves and remove the first element of the deque or may return null if the deque is empty. Method: pollLast() Description: Retrieves and remove the last element of the deque or may return null if the deque is empty. Method: pop() Description: Pops an element from the stack represented by the deque. Method: push() Description: Pushes an element onto the stack represented by the deque. Method: remove() Description: Retrieves and remove the head of the queue represented by the deque. Method: remove(Object o) Description: Removes the first occurrence of the specified element from the deque. Method: removeFirst() Description: Retrieves and remove the first element from the deque. Method: removeFirstOccurrence(Object o) Description: Remove the first occurrence of the element from the deque. Method: removeLast() Description: Retrieve and remove the last element from the deque. Method: removeLastOccurrence(Object o) Description: Remove the last occurrence of the element from the deque. Method: size() Description: Returns the total number of elements in the deque.
What is Java ConcurrentHashMap class?
A hash table supporting full concurrency of retrievals and high expected concurrency for updates. This class obeys the same functional specification as Hashtable and includes versions of methods corresponding to each method of Hashtable. However, even though all operations are thread-safe, retrieval operations do not entail locking, and there is not any support for locking the entire table in a way that prevents all access. This class is fully interoperable with Hashtable in programs that rely on its thread safety but not on its synchronization details..
What is the class declaration for Java ConcurrentHashMap class?
public class ConcurrentHashMap<K,V> extends AbstractMap<K,V> implements ConcurrentMap<K,V>, Serializable