Author: Editorial Team
-
How to convert String to int in Java ?
In some cases there is a need to convert String to Integer. For example, when client is sending String for key’s value where Integer is expected. There are following two ways to do it: parseInt() This is a static method of Integer class. There are two overloaded methods: One major difference between two methods is…
-
How to remove duplicates from ArrayList?
The task is to remove duplicate elements from the ArrayList. For Example: Approach 1 – Using Iterator Approach 2 – LinkedHashSet We have used LinkedHashSet because it maintains insertion order. Approach 3 You can use Java 8 Streams to remove duplicate elements from a list by using the distinct() method.
-
How can we create a synchronized collection from given collection?
java.util.Collections class provides static methods to return synchroni collection backed by the specified collection. Following are the methods provided by Collections class: For example, to create synchronized list:
-
What is Collections class in Java?
This class is a member of the Java Collections Framework. This class directly extends java.lang.Object and consists static methods that operate on or return collections. It contains polymorphic algorithms that operate on collections, “wrappers”, which return a new collection backed by a specified collection. The methods of this class all throw a NullPointerException if the…
-
Which collection classes are thread-safe?
synchronized is not a class property. It is only applicable to methods and blocks. Following are the few implementations which can be safely used in multi-threaded environment: You can get a synchronized version of a Java Collection with
-
What is EnumSet?
EnumSet can be explained with following points: EnumSet example Output EnumSet allOf() and noneOf() example Output EnumSet add() example Output
-
Why there is no method like Iterator.add() to add elements to the collection?
The purpose of iterator is to traverse elements of collection. An Iterable object might be immutable. In this case iterator add method will be trying to insert an element in an immutable collection. Consider the case of HashSet and TreeSet. There is no prediction in general whether the insert will be “after” or “before” the…
-
Can we have an empty catch block?
It is legal to have an empty catch block. If we have empty catch block then nothing happens. Empty catch block is something like silently ignoring the exception without doing anything and informing anyone. Which is a bad idea. Generally we do the following in catch blocks: It all depends on the issue and workflow…
-
What happens when exception is thrown by main method?
When program starts, the JVM sets a default uncaught exception handler that prints the exception to standard console and terminates. So when exception is thrown by main method then JVM prints the exception to standard console and terminates. Output
