How to Synchronize ArrayList in Java with Example

ArrayList is a very useful Collection in Java, I guess most used one as well but it is not synchronized. What this mean? It means you cannot share an instance of ArrayList between multiple threads if they are not just reading from it but also writing or updating elements. So how can we synchronize ArrayList? Well, we'll come to that in a second but did you thought why ArrayList is not synchronized in the first place? Since multi-threading is a core strength of Java and almost all Java programs have more than one thread, why Java designer does not make it easy for ArrayList to be used in such environment? The answer lies in performance, there is performance cost associated with synchronization and making ArrayList synchronized would have made it slower. So, they definitely thought about it and left ArrayList as non-synchronized to keep it fast, but at the same time they have provided easy ways to make it synchronized and this is what we are going to learn in this tutorial.

How to break from nested loop in Java

There are situations we need to be nested loops in Java, one loop containing another loop e.g. to implement many O(n^2) or quadratic algorithms e.g. bubble sort, insertion sort, selection sort, and searching in a two-dimensional array. There are a couple of more situations where you need nesting looping e.g.  printing pascal triangle and printing those star structures exercises from school days. Sometimes depending upon some condition we also like to come out of both inner and outer loop. For example, while searching a number in a two-dimensional array, once you find the number, you want to come out of both loops. The question is how can you break from nested loop in Java. You all know about break right? you have seen a break in switch statements, or terminating for, while and do-while loop, but not many Java developer know but there is a feature called labeled break, which you can use to break from nested loop.

2 Ways to Print Custom String Value of Java Enum

We all know that how powerful enumeration type in Java is, and one of the main strength of enum is that they can implement an interface, they can have an instance variable and you can also override any method inside enum instance. In Java programs, we often need to convert Enum to String type, sometimes just to print values in log file and other time for storing log into database.  By default, when you print an enum constant, it print its literal value e.g. if name of enum instance is RED, then it will print RED. This is also the value which is returned by name() method of java.lang.Enum class. But, there are situations when we want a custom String value for enum constant. For example, I want to print Red instead of RED when I convert Enum to String. How do you do that? Well, there are two ways you can achieve this, first by overriding toString() method for each enum constant and second by using an instance variable to hold custom String value. You can provide custom value while creating Enum constants and later you can call that method which returns custom  String value. In this article, we will see example of these two ways.

Right way to Compare String in Java

The String is a special class in Java, so is String comparison. When I say comparing String variables, it can be either to compare two String object to check if they are same, i.e. contains same characters or compare them alphabetically to check which comes first or second. In this article, we are going to talk about the right way of comparing String variables, but what is the wrong way? The wrong way is to compare String using == operator. It is one area in which almost every Java programmer  has made mistakes sometimes by comparing two String variable using == operator. Many Java developers are exposed to string comparison very early in their Java journey,  It's often required in their first few programming assignments e.g. write a program to print hello if the user enters "John".  When you first start with String in Java, you create an object using String literal syntax e.g. name = "John" and then compare using == operator, you will get the right answer, but if you take same String as user input, you will not get the correct answer.  Why? because equality operator compares references i.e. if two reference variable points to the same object in the heap then it returns true, otherwise, it returns false.

Difference between instance and Object in Java

In Java or other object-oriented programming languages, we often use Object and instance word interchangeably, but sometimes it confuses beginners like hell. I have been often asked several times, whether object and instance are the same things or different? Why we sometimes use object and sometimes instance if they are same thing etc? This gives me the idea to write a little bit about it. I will mostly talk about Java conventions perspective. Just like we use word function in C or C++   for a block of code, which can be called by its same, but in Java, we refer them as methods. In Java functions are known as methods, similarly, objects are known as instances in Java. You have a class, which represent a blueprint of a real-world thing e.g. Car, and object represents a real-world car e.g. your car, my car, a red car or a blue car. They are also known as instances of the car.

How to create User Defined Exception class in Java

Java has the very good support of handling Error and Exception, It has a well-defined Exception hierarchy and language level support to throw and catch Exception and deal with them. Java Programmers often deals with built-in exceptions from java.lang package and several others which are already defined in JDK API e.g. NullPointerException. If you have read Effective Java, you may remember the advice of Joshua Bloch regarding Exception. According to him, you should try to reuse the Exception classes provided in the JDK, e.g., IndexOutOfBoundException, ArithmeticException, IOException, and java.lang.ArrayIndexOutOfBoundsException , instead of creating new ones for a similar purpose. But there are cases when a user-defined, the custom exception provides a better opportunity to deal with special cases.

How to Convert a Double to Long in Java - Example Tutorial

We often need to convert a floating point number into integral number e.g. a double or float value 234.50d to long value 234L or 235L. There are a couple of ways to convert a double value to long value in Java e.g. you can simply cast a double value to long or you can wrap a double value into a Double object and call it's longValue() method, or using Math.round() method to round floating point value to a nearest integer. Te right way to convert a double value to a long in Java really depends on upon what you want to do with the floating point value. If you just want to truncate the double value to remove zero and take an integer value, you can simply cast double to long. If you have Double object instead of the double primitive type then you can also Double.longValue() method, this doesn't do anything but just cast the double primitive wrapped inside the Double object to long.

Modulo or Remainder Operator in Java

Modulo Operator is one of the fundamental operators in Java. It's a binary operator i.e. it requires two operands. In a division operation, the remainder is returned by using modulo operator. It is denoted by % (percentage) sign. For example 5%2 will return 1 because if you divide 5 with 2, the remainder will be 1. For a programmer it's very important to know how to use this operator, they are very important to build logic. For example, in many cases like reversing a number or checking if a number is a palindrome, you can use modulus operator with 10 to get the last digit, for example, 101%10 will return 1 or 1234%10 will return 4, the last digit. It is one of a rather less used arithmetic operators in comparison of +, -, * and /.  One of the important points about the remainder operator which is not known by many Java programmer is that it can also be used with floating point numbers.

2 Examples to Add Zeros at the Beginning of a Number in Java (Padding)

How do you left pad an integer value with zeroes in Java when converting to a string? This is a common requirement if you are working in finance domain. There are so many legacy systems out there which expect the input of certain length, and if your input is shorter than specified length, you got to add zeros at the beginning of number to make them off right length. Java has rich API and thankfully neither converting an integer to String is difficult nor formatting String to add leading zeros. In fact, there are multiple ways to add zeros at the start of a number or numeric String, you can either use powerful String.format() method or it's close cousin printf() method, or you can go back to DecimalFormat class if you are still working in JDK 4. Formatting, in general, is a very useful concept and as Java developer, you must have a good understanding of that.

How to use Static Method in Java with Example

Static methods are one of the important programming concepts in any programming language but unfortunately it is also most misunderstood and misused one. Talking about Java, almost all programmers knows that. static methods belong to the class and non-static methods belong to the objects of the class, but hardly all of them understand what it means. That's why this is one of the popular weed out questions on programming interviews. If a Java programmer doesn't know difference between static and non-static method, he is probably not ready yet, and needs more practice and experience. With half knowledge, making a method static can have serious repercussion , especially in today's heavily multi-threaded Java application. Today, one of my reader message me this question on my Facebook account of Javarevisited, which prompted me to to write this tutorial cum discussion post to give a good explanation or example to clarify the concept. What you have learned is totally find, all we do here is to elaborate your learning by understanding key differences between static methods and instance methods in Java.

How to Read, Write XLSX File in Java - Apach POI Example

No matter how Microsoft is doing in comparison with Google, Microsoft Office is still the most used application in software world. Other alternatives like OpenOffice and LiberOffice have failed to take off to challenge MS Office. What this mean to a Java application developer? Because of huge popularity of MS office products you often need to support Microsoft office format such as word, Excel, PowerPoint and additionally Adobe PDF. If you are using JSP Servlet, display tag library automatically provides Excel, Word and PDF support. Since JDK doesn't provide direct API to read and write Microsoft Excel and Word document, you have to rely on third party library to do your job. Fortunately there are couple of open source library exists to read and write Microsoft Office XLS and XLSX file format, Apache POI is the best one. It is widely used, has strong community support and it is feature rich.

Why Constructor is Important in Java?

In simple word, Constructor is a method like a block of code which is called by Java runtime during object creation using new() operator. Constructor are special in the sense that they have the same name as the Class they are part of. They are also special in a sense that they are called by JVM automatically when you create an object. Have you ever thought about Why do you need a constructor? What benefits it provide? One reason is to initialize your object with default or initial state since default values for primitives may not be what you are looking for. One more reason you create constructor is to inform the world about dependencies, a class needs to do its job. Anyone by looking at your constructors should be able to figure out, what he needs in order to use this class.  For example, following class OrderProcessor needs a Queue and Database to function properly.

What is the difference between a Class and an Object in Java?

This article is solely for all beginner programmers, who are learning object oriented programming language e.g. Java, C++ or C# and aspire to do well on any programming interview. The difference between class and object is one of the most common questions, you would like to ask a fresher coming out from college or training institute, but you would be surprised how many beginner Java programmers struggle with this question. Class and Object are two pillars of Object Oriented Programming (OOPS) and a good understanding is a must, but when you ask this question apart from the theoretical and bookish answer that "class is a blueprint and objects are actual things created out of that blueprint", you would hardly get anything substantial. Though that answer is correct and works perfectly, it doesn't differentiate between a programmer, who has just mugged the answer, or the one who truly understand the difference between class and object.

Difference between String literal and New String object in Java

The String class or java.lang.String is a special class in Java API and has so many special behaviors which are not obvious to many programmers. In order to master Java, the first step is to master the String class, and one way to explore is checking what kind of String related questions are asked on Java interviews. Apart from usual questions like why String is final or equals vs == operator, one of the most frequently asked questions is what is the difference between String literal and String object in Java

Write a Program to Find Sum of Digits in Java

One of the common programming practice question thrown to beginners is to write a program to calculate the sum of digits in an integral number. For example, if the input is 123456 then output or sum of the digit is (1+2+3+4+5+6) = 21. An additional condition is you can not use any third party or library method to solve this problem. This program is not as simple as it looks and that's why it's a good exercise, you must know some basic programming techniques e.g. loops, operators, and logic formation to solve this problem. Let's see how we can solve this problem using Java programming language. In order to calculate the sum of digits, we must get digits as numbers. So your first challenge is how do you get the digits as numbers?  How do we extract 6 out of 123456?

Why Abstract class is Important in Java with Example

Abstract class is a special class in Java, it can not be instantiated and that's why can not be used directly. At first concept of abstraction, abstract class and interface all look useless to many developers, because you can not implement any method in an interface, you can not create an object of the abstract class, so why do you need them. Once they face biggest constant of software development, yes that is CHANGE, they understand how abstraction at the top level can help in writing flexible software. A key challenge while writing software (Java Programs, C++ programs) is not just to cater today's requirement but also to ensure that nurture requirement can be handled without any architectural or design change in your code. In short, your software must be flexible enough to support future changes.

5 Examples of Formatting Float or Double Numbers to String in Java

Formatting floating point numbers is a common task in software development and Java programming is no different. You often need to pretty print float and double values up-to 2 to 4 decimal places in console, GUI or JSP pages. Thankfully Java provides lots of convenient methods to format a floating point number up to certain decimal places. For example you can use method printf() to format a float or double number to a output stream. However, it does not return a String. In JDK 1.5, a new static method format() was added to the String class, which is similar to printf(), but returns a String. By the way there are numerous way to format numbers in Java, you can use either DecimalFormat class, or NumberFormat or even Formatter class to format floating point numbers in Java. Coming back to String's format method, here is a quick example of using it :
String strDouble = String.format("%.2f", 1.23456);
This will format the floating point number 1.23456 up-to 2 decimal places, because we have used two after decimal point in formatting instruction %.2f, f is for floating point number, which includes both double and float data type in Java. Don't try to use "d" for double here, because that is used to format integer and stands for decimal in formatting instruction. By the way there is a catch here, format() method will also arbitrarily round the number. For example if you want to format 1.99999 up-to 2 decimal places then it will return 2.0 rather than 1.99, as shown below.

Difference between StringBuilder and StringBuffer in Java

If you are in a hurry and heading straight to interview then I won't take much of your time, In a couple of words, the main difference between StringBuffer and StringBuilder is between four parameters, synchronization, speed, thread-safety, and availability. StringBuffer is synchronized and that's why thread-safe, but StringBuilder is not synchronized, not thread-safe and that's why fast. Regarding availability, StringBuffer is available from Java 1.0 while StringBuilder was added in Java 5. Now we can take a breath, and can continue with rest of this article. In Java, there are three classes to deal with String data type, String, StringBuffer and StringBuilder. All of three belongs to java.lang package, which is automatically imported into every Java program thus you don't need to do any import for using StringBuilder and StringBuffer.

3 Examples to Read FileInputStream as String in Java - JDK7, Guava and Apache Commons

Java programming language provides streams to read data from a file, a socket and from other sources e.g. byte array, but developers often find themselves puzzled with several issues e.g. how to open connection to read data, how to close connection after reading or writing into file, how to handle IOException e.g. FileNotFoundException, EOFFileException etc. They are not confident enough to say that this code will work perfectly.  Well, not everyone expect you to make that comment, but having some basics covered always helps. For example In Java, we read data from file or socket using InputStream and write data using OutputStream. Inside Java program, we often use String object to store and pass file data, that's why we need a way to convert InputStream to String in Java. As a Java developer, just keep two things in mind while reading InputStream data as String :

3 Examples to Loop Map in Java - Foreach vs Iterator

There are multiple ways to loop through Map in Java, you can either use a foreach loop or Iterator to traverse Map in Java, but always use either Set of keys or values for iteration. Since Map by default doesn't guarantee any order, any code which assumes a particular order during iteration will fail. You only want to traverse or loop through a Map, if you want to transform each mapping one by one. Now Java 8 release provides a new way to loop through Map in Java using Stream API and forEach method. For now, we will see 3 ways to loop through each element of Map. Though Map is an interface in Java, we often loop through common Map implementation like HashMap, Hashtable, TreeMap and LinkedHashMap. By the way, all the ways of traversing Map discussed in this article is pretty general and valid for any Map implementation, including proprietary and third-party Map classes.

2 Ways to sort HashMap in Java? Example

So you have a Map in your Java program and you want to process its data in sorted order. Since Map doesn't guarantee any order for its keys and values, you always end up with unsorted keys and Map. If you really need a sorted Map then think about using TreeMap, which keeps all keys in a sorted order. This could be either natural order of keys (defined by Comparable) or a custom order (defined by Comparator), which you can provide while creating an instance of TreeMap. If you don't have your data in a sorted Map then only option remains is to get the keys, sort them and then process data in that order. Since keys are unique in Map, it returns a Set of keys, which means you cannot sort them by using Collections.sort() method, which accept a List. So what to do? Well, we can convert our Set into List as shown in this example, then sort them using sort() method in any order and process them accordingly.

Array length vs ArrayList Size in Java

One of the confusing part in learning Java for a beginner to understand how to find the length of array and ArrayList in Java? Main reason for the confusion is an inconsistent way of calculating length between two. Calling size() method on arrays and length, or even length() on ArrayList is common programming error made by beginners. The main reason for confusion is the special handling of an array in Java.  Java native arrays have built-in length attribute but no size() method while the Java library containers, known as Collection classes e.g. ArrayList<>, Vector<>, etc,  all have a size() method. There is one more thing which adds to this confusion, that is capacity, at any point capacity of any collection class is the maximum number of elements collection can hold. the size of collection must be less than or equal to its capacity.

How to Make Executable JAR file in Eclipse IDE - Java

If you are Java programmer then you know what is the purpose of JAR file, but for those who are unaware, JAR file is deliverables of Java application. Just like C and C++  application produce EXE files, Java produces JAR files. In other words, A JAR (Java Archive) file is a ZIP format file that bundles Java classes into a single unit, it may contain all the resource needed by Java application as well. There are mainly two types of JAR file in Java:  Library JAR (normal JAR) files: JARs which are reusable libraries e.g. Apache commons JAR file, guava.jar itself or even JDBC drivers e.g. ojdbc6_g.jar. There is another type as well, Executable JAR files: JARs which can be executed as a standalone Java applications. The main difference between normal and executable JAR file is that later contains a mainfest file, which specifies a main-class entry. When you run that JAR file, Java starts your application by reading that main-class entry, because you need the main method to execute Java programs.

Difference between Polymorphism and Inheritance in Java and OOP

Programmers often confused among different object-oriented concepts e.g. between Composition and Inheritance, between abstraction and encapsulation and sometime between Polymorphism and Inheritance. In this article, we will explore third one, Polymorphism vs Inheritance. Like in the real world, Inheritance is used to define the relationship between two classes. It's similar to Father-Son relationship. In object-oriented programming, we have a Parent class (also known as the superclass) and a Child class (also known as the subclass). Similar to the real world, Child inherits Parents qualities, e.g. it's attribute, methods, and code. Inheritance is actually meant for code-reuse. A child can reuse all the codes written in Parent class, and only write code for behavior which is different than the parent. Though it’s possible to restrict something to parent itself by using the private and final keyword in Java.On the other hand, Polymorphism is an ability of Object to behave in multiple forms.

How to Print Array with elements in Java?

You cannot print array elements directly in Java, you need to use Arrays.toString() or Arrays.deepToString() to print array elements. Use toString() if you want to print one-dimensional array and use deepToString() method if you want to print two-dimensional array. Have you tried printing array in Java before? What did you do? just passed an array to println() method and expecting it prints its elements? Me too, but surprisingly array despite being Object and providing a length field, doesn't seem overriding toString() method from java.lang.Object class. All it prints is type@somenumber. This is not at all useful for anyone who is interested in seeing whether an array is empty or not, if not then what elements it has etc.

2 Ways to Remove Elements/Objects From ArrayList in Java

There are two ways to remove objects from ArrayList in Java, first, by using remove() method, and second by using Iterator. ArrayList provides overloaded remove() method, one accept index of the object to be removed i.e. remove(int index), and other accept object to be removed, i.e. remove(Object obj). Rule of thumb is, If you know the index of the object, then use the first method, otherwise use the second method. By the way, you must remember to use ArrayList remove methods, only when you are not iterating over ArrayList if you are iterating then use Iterator.remove() method, failing to do so may result in ConcurrentModificationException in Java. Another gotcha can have occurred due to autoboxing. If you look closely that two remove methods, remove(int index) and remove(Object obj) are indistinguishable if you are trying to remove from an ArrayList of Integers.

Decimal to Binary Conversion in Java

This week's programming exercise is to write a program to convert a decimal number to binary in Java. It's a simple exercise for beginners who has just started learning Java programming language. Decimal numbers are base 10 numbers, which means there are exactly 10 digits to represent a number, starting from 0 to 9, on the other hand, binary number system has just two digits 0 and 1, which is known as bits. Binary numbers have lot of use in the digital world, in fact, binary is the language of computers where 0 and 1 represent true/false, on/off and becomes key for logic formation. In order to convert a decimal number into binary, we will use modules operator in Java, represented by a percentage sign (%). This is also known as a remainder operator because it returns the remainder of a division operation, for example, 5%,2 will return 1 while 7%4 will return 3.

Java Program to Print Alphabets in Upper and Lower Case

One of the textbook exercise to get start with any programming language is writing a program to print alphabets in both upper and lower case. This program allows you to explore the String class in Java with toUpperCase() and toLowerCase() method but normally when you start, it's asked to do this without any API methods. This kind of exercise actually improves your understanding of programming language e.g. basic operators, data types like int and char. It's similar to your prime number, Fibonacci series, and factorial program exercise. I strongly suggest doing this textbook exercises to anyone who is just started learning a new programming language. Coming back to this program, Java has a datatype called char, which is 2-byte unsigned integer type. It is used to store characters in Java  e.g. char A = 'A'.

What is the Actual Use of interface in Java?

An interface in Java has remained a complex topic for many beginners to understand. The first thing which puzzles many programmers is the fact that you cannot define any method inside interface, it a just declaration. By rule, all method inside interface must be abstract (Well, this rule is changing in Java 8 to allow lambda expressions, now interface can have one non-abstract method, also known as a default method). So, if you can't define anything, Why we need an interface?  what's the use of an interface, if we are anyway going to write a class and override them to provide behaviour, Can't we declare those methods inside the class itself without using interface etc. Well, if you are thinking in terms of behaviour then you are really missing the point of interface.

Difference between Static and Dynamic Binding in Java

When you call a method in Java, it is resolved either at compile time or at runtime, depending upon whether it's a virtual method or a static method. When a method call is resolved at compile time, it is known as static binding, while if method invocation is resolved at runtime, it is known as Dynamic binding or Late binding. Since Java is an object-oriented programming language and by virtue of that it supports Polymorphism. Because of polymorphism, a reference variable of type Parent can hold an object of type Child, which extends Parent.

How to Convert java.util.Date to java.sql.Date - Example

There are two date classes in Java, one in java.util package and other in the java.sql package. Though both are known as Date class, there is some difference between java.util.Date and java.sql.Date e.g. Former is used whenever a Date is required in Java application while later is used to read and store DATE SQL type from the database. There is one more important difference is, java.util.Date stores both date and time values, while only stores date information, without any time part. As per Javadoc, is a thin wrapper around a millisecond value that allows JDBC to identify this as an SQL DATE value. To conform with the definition of SQL DATE, the millisecond values wrapped by a java.sql.Date instance must be 'normalized' by setting the hours, minutes, seconds, and milliseconds to zero in the particular time zone with which the instance is associated. See SQL date vs Util date for few more differences.

How to Create File and Directory in Java with Example

Many beginners confused with the fact that same class is used to create both file and directory in Java. I agree, this is not very intuitive and  junior developers probably start looking for a class called, which doesn't exists. On the other hand, creating file and directory are simple in Java, as provides methods like createNewFile() and mkdir() to create new file and directory in Java. These method returns boolean, which is the result of that operation i.e. createNewFile() returns true if it successfully created file and mkdir() returns true if the directory is created successfully. There is another method called mkdirs(), which you can use if parent directory doesn't exist, it's like mkdir -p option from UNIX mkdir command. In this Java program, we will learn how to create file and directory, only if they don't exist already.

How HashSet Internally Works in Java

Not many programmer know that HashSet is internally implemented using HashMap in Java, so if you know How HashMap works internally in Java, more likely you can figure out how HashSet works in Java. But, now a curious Java developer can question that, how come HashSet uses HashMap, because you need a key value pair to use with Map, while in HashSet we only store one object. Good question, isn't it? If you remember some functionality of earlier class, then you know that HashMap allows duplicate values and this property is exploited while implementing HashSet in Java.

Java Regular Expression to Check If String contains at least One Digit

This week's task is to write a regular expression in Java to check if a String contains any digit or not. For example, passing "abcd" to pattern should false, while passing "abcd1" to return true, because it contains at least one digit. Similarly passing "1234" should return true because it contains more than one digit. Though java.lang.String class provides a couple of methods with an inbuilt support of regular expression e.g.split method, replaceAll() and  matches method, which can be used for this purpose, but they have a drawback.  They create a new regular expression pattern object, every time you call. Since most of the time we can just reuse the pattern, we don't need to spend time on creating and compiling pattern, which is expensive compared to testing a String against the pattern.

How to Fix java.lang.OufOfMemoryError: Direct Buffer Memory

Java allows an application to access non-heap memory by using direct byte buffer. Many high-performance applications use direct byte buffer, along with a memory-mapped file for high-speed IO. And, while the ByteBuffer object is small itself, it can hold a large chunk of non-heap memory, which is outside of the Garbage collection scope.  Which means garbage collector can not reclaim this memory. It is often used to store large data e.g. order or static data cache. Since generally your program allocates the large buffer e.g. size of 1GB or 2GB, you get "Exception in thread "main" java.lang.OutOfMemoryError: Direct buffer memory" error, when you try to allocate memory by running the following code

Why String Class is made Immutable or Final in Java - 5 Reasons

There is hardly any Java Interview, where no questions are asked from String, and Why String is Immutable in Java is I think most popular one. This question is also asked as Why String class is made final in Java or simply, Why String is final. In order to answer these questions, Java programmer must have a solid understanding of How String works, what are special features of this class and some key fundamentals. The String class is a God class in Java, It has got special features which is not available to other classes e.g. String literals are stored in pools, You can concatenate strings using + operator. Given its importance in Java programming, Java designer has made it final, which means you can not extend java.lang.String class, this also helps to make String object Immutable.

java.lang.UnsatisfiedLinkError: Library not found tibrvnative or android

When I was working in JNI and using native code, actually an in-house library,  I realized that java.lang.UnsatisfiedLinkError: Library not found comes mainly due to two reasons

1) First reason, which happens in 90% scenarios is that the library which you are using directly or indirectly (some external JAR is using native library or native dll e.g. if your Java application is using TIBCO libraries for messaging or fault tolerance then tibrv.jar uses tibrvnative.dll library and throws java.lang.UnsatisfiedLinkError: Library not found tibrvnative if that library (the dll) is not in the path. In order to fix this problem, you need to update your PATH environment variable to include native libraries binary. see last section for more details.

6 Difference between LinkedHashSet vs TreeSet vs HashSet in Java

LinkedHashSet, TreeSet, and HashSet are three of most popular implementation of Set interface in Java Collection Framework. Since they implement Set interface, they follow its contracts for not allowing duplicates. All these implementation except, TreeSet uses equals() method to check for duplicates, on the other hand TreeSet use compareTo() or compare() method for comparing objects and can break Set interface contract of unique element, if equals method is not consistent with compareTo() or compare() method. In this Java Collection tutorial, we will see the difference between LinkedHashSet vs TreeSet vs HashSet on different points e.g. speed, performance, ordering, synchronization etc. Based upon these differences we can also decide when to use LinkedHashSet vs TreeSet vs HashSet in Java.