Showing posts with label java collection tutorial. Show all posts
Showing posts with label java collection tutorial. Show all posts

Friday 30 August 2013

Top Most Difference between EnumMap and HashMap in Java

HashMap vs EnumMap in Java
What is difference between EnumMap and HashMap in Java is the latest Java collection interview question which has been asked to couple of my friends. This is one of the tricky Java question, specially if you are not very much familiar with EnumMap in Java, which is not uncommon, given you can use it with only Enum keys. Main difference between EnumMap and HashMap is that EnumMap is a specialized Map implementation exclusively for Enum as key. Using Enum as key, allows to do some implementation level optimization for high performance which is generally not possible with other object's as key. We have seen lot of interview questions on HashMap in our article How HashMap works in Java but what we missed there is this question which is recently asked to some of my friend. Unlike HashMap, EnumMap is not applicable for every case but its best suited when you have Enum as key. We have already covered basics of EnumMap and some EnumMap example in my last article What is EnumMap in Java and In this post we will focus on key differences between HashMap and EnumMap in Java.
Read more »

Top Most How to compare Arrays in Java – Equals vs deepEquals Example

java.util.Arrays class provides equals() and deepEquals() method to compare two Arrays in Java. Both of these are overloaded method to compare primitive arrays e.g. int, long, float, double and Object arrays e.g. Arrays.equals(Object[] , Object[]). Arrays.equals() returns true if both Arrays which it is comparing are null, If both array pointing to same Array Object or they must be of same length and contains same element in each index. In all other cases it returns false. Arrays.equals() calls equals() method of each Object while comparing Object arrays. One of the tricky question in Java related to Array comparison is Difference between Arrays.equals() and Arrays.deepEquals() method.  Since both equals and deepEquals is used for array comparison, what is difference between them becomes important. Short answer of this questions is that, Array's equals() method does not perform deep comparison and fails logical comparison in case of nested Array,  on other hand deepEquals() perform deep comparison and returns logical comparison in case of nested array.
Read more »

Wednesday 28 August 2013

Top Most Difference between IdentityHashMap and HashMap in Java

IdentityHashMap in Java was added in Java 1.4 but still its one of those lessor known class in Java. Main difference between IdentityHashMap and HashMap in Java is that IdentityHashMap is a special implementation of Map interface which doesn't use equals() and hashCode() method for comparing object unlike other implementation of Map e.g. HashMap. Instead IdentityHashMap use equality operator "=="  to compare keys and values in Java which makes it faster compare to HashMap and suitable where you need reference equality check and instead of logical equality. By the way IdentityHashMap is special implementation of Map interface much like EnumMap but it also violates general contract of Map interface which mandates using equals method for comparing Object. Also IdentityHashMap vs HashMap is a good Java question and have been asked couple of times.  Though this question is not as popular as How HashMap works in Java or Difference between Hashtable and HashMap, it’s still a good question to ask. In this Java tutorial we will see example of IdentityHashMap and explores some key differences between IdentityHashMap and HashMap in Java.
Read more »

Tuesday 27 August 2013

Top Most How to use ConcurrentHashMap in Java - Example Tutorial and Working

ConcurrentHashMap in Java is introduced as an alternative of Hashtable in Java 1.5 as part of Java concurrency package. Prior to Java 1.5 if you need a Map implementation, which can be safely used in a concurrent and multi-threaded Java program, than, you only have Hashtable or synchronized Map because HashMap is not thread-safe. With ConcurrentHashMap, now you have better choice; because, not only it can be safely used in concurrent multi-threaded environment but also provides better performance over Hashtable and synchronizedMap. ConcurrentHashMap performs better than earlier two because it only locks a portion of Map, instead of whole Map, which is the case with Hashtable and synchronized Map. CHM allows concurred read operations and same time, maintains integrity by synchronizing write operations. We have seen basics of ConcurrentHashMap on Top 5 Java Concurrent Collections from JDK 5 and 6 and in this Java tutorial, we will learn :

Ø       How ConcurrentHashMap works in Java or how it is implemented in Java.
Ø       When to use ConcurrentHashMap in Java
Ø       ConcurrentHashMap examples in Java
Ø       And some important properties of CHM .
Read more »

Top Most 3 Example to print array values in Java - toString and deepToString from Arrays

Printing array values in Java or values of array element in Java would have been much easier if  arrays are allowed to directly prints its values whenever used inside System.out.println() or format and printf method, Similar to various classes in Java do this by overriding toString() method. Despite being an object, array in Java doesn't print any meaningful representation of its content when passed to System.out.println() or any other print methods. If you are using array in method argument or any other prominent place in code and actually interested in values of array then you don't have much choice than for loop until Java 1.4. Things has been changed since Java 5 because it introduced two extremely convenient methods for printing values of both primitive and object arrays in Java. Arrays.toString(array) and Arrays.deepToString(twoDimensionArray) can print values of any array. Main difference between Arrays.toString() and Arrays.deepToString  is that deepToString is used to print values of multidimensional array which is far more convenient than nesting of multiple for loops. In this Java tutorial we will see 3 different ways of printing array values in Java or value of element from Array in Java.
Read more »

Sunday 25 August 2013

Top Most How to initialize List with Array in Java - One Liner Example

Initializing list while declaring it is very convenient for quick use. If you have been using Java programming language for quite some time then you must be familiar with syntax of array in Java and how to initialize an arrayin the same line while declaring it as show below:

String[] oldValues = new String[] {"list" , "set" , "map"};

or even shorter :

String[] values = {"abc","bcd", "def"};

Similarly we can also create List  and initialize it at same line, popularly known as initializing List in one line example. Arrays.asList() is used for that purpose which returns a fixed size List backed by Array. By the way don’t confuse between Immutable or read only List which doesn’t allow any modification operation including set(index) which is permitted in fixed length List.Here is an example of creating and initializing List in one line :
Read more »

Friday 23 August 2013

Top Most How to Convert Collection to String in Java - Spring Framework Example

How to convert Collection to String in Java
Many times we need to convert any Collection like Set or List into String like comma separated or any other delimiter delimited String. Though this is quite a trivial job for a Java programmer as you just need to Iterate through loop and create a big String where individual String are separated by delimiter, you still need to handle cases like last element should not have delimiter or at bare minimum you need to test that code. I like Joshua Bloach advise on Effective Java to use libraries for those common task let it be internal proprietary library or any open source library as used in previous examples of  Spring, Apache Commons or Google’s Guava but point is that you should avoid converting ArrayList to String like common task by yourself on application code.
Read more »

Top Most 3 example of converting array to ArrayList and ArrayList to array in Java program

How to change from array to ArrayList and ArrayList to array in java
Have you encountered any situation where you quickly wanted to convert your array to ArrayList or ArrayList to array ? I have faced many such situations which motivate me to write these quick Java tips about converting array to ArrayList and ArrayList to array in Java. Both array and ArrayList are quite common and every Java developer is familiar with this. Former is used to store object and primitive type while later can only hold objects. Array is part of standard Java  fundamental data structure while ArrayList is part of collection framework in Java. Most of the time we store data in form of object in either Array or ArrayList or sometime we find either of them suitable for processing and we want to convert from one array to ArrayList or ArrayList to array in Java. This short array to ArrayList tutorial in Java will explain how quickly you can convert data from each other. So when you face such situation don't bother just remember this tips and you will get through it. If you compare array vs ArrayList only significant different is one is fixed size while other is not. This article is in continuation of my post Difference between Vector and ArrayList in Java and How to Sort ArrayList in Java on descending order. On related not from Java 5 onwards ArrayList class supports Generics in Java, which means you can convert an ArrayList to String into an String array or ArrayList of Integer into an Integer Array. Generics provides type safety and remove casting during runtime.
Read more »

Top Most How to remove duplicates elements from ArrayList in Java

You can remove duplicates or repeated elements from ArrayList in Java by converting ArrayList into HashSet in Java. but before doing that just keep in mind that Set doesn't preserver insertion order which is guaranteed by List, in fact that’s the main difference between List and Set in Java. So when you convert ArrayList to HashSet all duplicates elements will be removed but insertion order will be lost. Let’s see this in action by writing a Java program to remove duplicates from ArrayList in Java. In this Java collection tutorial we will see both approach of deleting duplicates from ArrayList e.g using Hashset and LinkedHashSet and compare order of elements in final ArrayList which contains no duplicates. If you are not very familiar of What is an ArrayList and HashSet in Java collection framework, I suggest reading Java ArrayList Example and 10 HashSet Example in Java. These articles contains good introduction of most common used collection in Java i.e. ArrayList and HashSet.
Read more »

Monday 19 August 2013

Top Most How to sort HashMap by key and value in Java - Hashtable, Map Example Tutorial

Sorting HashMap in Java is not as easy as it sounds because unfortunately Java API doesn't provide any utility method to sort HashMap based on keys and values. Sorting HashMap is not like sorting ArrayList or sorting Arrays in Java. If you are wondering why we can not use Collections.sort() method than for your information it only accepts List<E>, which leaves us to write our own utility methods to sort Map in Java. This is true for all types of Map like Hashtable, HashMapand LinkedHashMap. TreeMap is an already a sorted Map so we don't need to sort it again. Why we need to sort HashMap in Java, Why can't we use TreeMap in place of HashMap is the question appears in most Java programmer's mind when they asked to sort HashMap in Java. Well TreeMapis way slower than HashMap because it runs sorting operation with each insertion, update and removal and some time you don't really need an all time sorted Map, What you need is an ability to sort any Map implementation based upon its key and value. In last couple of articles we have seen How to loop or traverse Map in Java and in this Java tutorial we will see couple of ways to sort HashMap in Java.
Read more »

Friday 16 August 2013

Top Most What is EnumMap in Java – Example Tutorial

What is EnumMap in Java
EnumMap in Java is added on JDK  5 release along with other important features like  Autoboxing, varargs and Generics. EnumMap is specialized Map implementation designed and optimized for using Java Enum as key. Since enum can represent a type (like class or interface)  in Java and it can also override equals() and hashCode() , It can be used inside HashMap or any other collection but using  EnumMap brings implementation specific benefits which is done for enum keys, In short EnumMap is optimized Map implementation exclusively for enum keys . As per javadoc Enum is implemented using Arrays and common operations result in constant time. So if you are thinking of an high performance Map, EnumMap could be decent choice for enumeration data. We have already seen many examples of Java enum in our article 10 Examples of enum in Java  and using Enum as thread-safe Singleton. In this Java tutorial we will see simple examples of using EnumMap in Java. On related note Difference between EnumMap and HashMap is also getting popular as one of advanced Java collection interviews questions and most of Java IDE like Eclipse and Netbeans will also suggest to use EnumMap if you use Enum keys along with HashMap as part of there code improvement suggestion.
Read more »

Saturday 10 August 2013

Top Most Union and Intersection of two Set in Java - Google Guava Example

Google Guava is an open source library which provides lots of useful utility to Java programmer,  one of them is easy way to find intersection and union of two Set in Java. You might have used Google Guava for other functionality e.g. for overriding toString in easy way or Immutable Collection provided by Guava library. Along with Apache commons and Spring, Google Guava is a library you definitely want to include in your Project. Guava provides couple of static method to operate on Set in Java on package com.google.common.collect.Sets. There are two methods called intersection() and union() which provides intersection and union of two Sets in Java. In this example we have used HashSetas Set implementation but it will work with any Set implementation e.g. TreeSet or LinkedHashSet.
Read more »

Thursday 8 August 2013

Top Most How to convert List of Integers to int array in Java - Coding Tips

So, you have a List of Integers and you want to convert them into int array? Yes you read it write, not on Integer array but int array. Though in most practical purpose, Integer array can be used in place of int[] because ofautoboxing in Java, you still need an int[] if your method accepts it. In Java, you can not type cast an Integer array into int array. Many Java programmer think about toArray() method from java.util.List to convert a List into Array, but unfortunately toArray() is useless in most of times. It doesn't allow you to convert List into primitive arrays. Though you can convert List of Integers to array of Integers, but not array of primitive int. This is true for List of all wrapper class e.g. List of Float, Double, Long, toArray() method can return array of wrapper class but not primitives. After looking into Java Collection API, It seems that only traditional for loop or foreach can help, which involves iterating over Integer arrayand storing them into int[], but fortunately, I came across Apache Commons ArrayUtils class. ArrayUtils can do this work for us, It has several overloaded methods to convert Object arrays into primitive arrays. For example, you can convert an array of Double i.e. Double[] to primitive double array e.g. double[]. This example once again reinforced my thinking to include Apache Commons lang and Google's Guava by default in any Java project, they are rich and effectively complement standard JDK library.
Read more »

Wednesday 7 August 2013

Top Most Difference between TreeSet, LinkedHashSet and HashSet in Java with Example

TreeSet, LinkedHashSet and HashSet all are implementation of Set interface and by virtue of that, they follows contract of Set interface i.e. they do not allow duplicate elements. Despite being from same type hierarchy,  there are lot of difference between them; which is important to understand, so that you can choose most appropriate Set implementation based upon your requirement. By the way difference between TreeSet and HashSet or LinkedHashSet is also one of the popular Java Collection interview question, not as popular as Hashtable vs HashMap or ArrayList vs Vector but still appears in various Java interviews. In this article we will see difference between HashSet, TreeSet and LinkedHashSet on various points e.g. Ordering of elements, performance, allowing null etc and then we will see When to use TreeSet or LinkedHashSet or simply HashSet in Java.
Read more »

Top Most Top 5 Concurrent Collections from JDK 5 and 6 Java Programmer Should Know

Several new Collection classes are added in Java 5 and Java 6 specially concurrent alternatives of standard synchronized ArrayList, Hashtableand  synchronized HashMap collection classes. Many Java programmer still not familiar with these new collection classes from java.util.concurrent package and misses a whole new set of functionality which can be utilized to build more scalable and high performance Java application. In this Java tutorial we will some of useful collection classes e.g. ConcurrentHashMap, BlockingQueuewhich provides some of the very useful functionalities to build concurrent Java application. By the way this is not a comprehensive article explaining each feature of all these concurrent collections, Instead I will just try to list out why they are there, which Collection class they replace or provides alternative for. Idea is to keep it short and simple while highlighting key points of those useful java.util.concurrent collections.
Read more »

Monday 5 August 2013

Top Most BlockingQueue in Java – ArrayBlockingQueue vs LinkedBlockingQueue Example program Tutorial

BlockingQueue in Java is added in Java 1.5 along with various other concurrent Utility classes like ConcurrentHashMap, Counting Semaphore, CopyOnWriteArrrayListetc. BlockingQueue is a unique collection type which not only store elements but also supports flow control by introducing blocking if either BlockingQueue is full or empty. take() method of BlockingQueue will block if Queue is empty and put() method of BlockingQueue will block if Queue is full. This property makes BlockingQueue an ideal choice for implementing Producer consumer design pattern where one thread insert element into BlockingQueue and other thread consumes it. In this Java tutorial we will learn about What is BlockingQueue in Java, How to use BlockingQueue, ArrayBlockingQueue and LinkedBlockingQueue and some important properties of it.
Read more »

Sunday 4 August 2013

Top Most What is NavigableMap in Java 6 - Creating subMap from Map with Example

NavigableMap in Java 6 is an extension of SortedMap  like TreeMapwhich provides convenient navigation method like lowerKey, floorKey, ceilingKey and higherKey. NavigableMap is added on Java 1.6 and along with these popular navigation method it also provide ways to create a Sub Map from existing Map in Java e.g. headMap whose keys are less than specified key, tailMap whose keys are greater than specified key and a subMap which is strictly contains keys which falls between toKey and fromKey. All of these methods also provides a boolean to include specified key or not. TreeMapand ConcurrentSkipListMap are two concrete implementation of NavigableMap in Java 1.6 API. Though NavigableMap is not as popular as HashMap, ConcurrentHashMapor Hashtablebut given that TreeMap implements NavigableMap you already get all good things in a well known Map implementation.
Read more »

Top Most 4 ways to search Java Array to find an element or object - Tutorial Example

Searching in Java Array sounds familiar? should be,  because its one of frequently used operations in Java programming. Array is an index based data structure which is used to store elements but unlike Collection classes like ArrayList or HashSet which has contains() method, array in Java doesn't have any method to check whether an element is inside array or not. Java programming language provides several ways to search any element in Java array. In this Java tutorial we will see 4 examples of searching Array in Java for an element or object.  Every example is different than other and some of them are faster and others are slow but take less memory. These technique also valid for different types of array e.g. primitive and object array. I always suggest to prefer List over Array until you need every bit of performance from your Java application, it not only convenient to work but also more extensible.
Read more »

LinkWithin

Related Posts Plugin for WordPress, Blogger...

Labels

Core Java programming core java interview question Core Java Faq's Servlets coding database jsp-servlet spring Java linux unix interview questions java investment bank Web Services Interview investment bank mysql Senior java developer interviews best practices java collection tutorial RMI SQL Eclipse FIX protocol tutorial tibco J2EE groovy java questions SCJP grails java 5 tutorial jdbc beginner error and exception Design Patterns Java Programming Tutorials fundamentals general object oriented programming xml Java Programs Hibernate Examples Flex JAMon Java xml tutorial logging Jsp Struts 2.0 Sybase and SQL Server debugging java interviews performance FIX Protocol interview questions JUnit testing WebSphere date and time tutorial experienced java IO tutorial java concurrency thread Ejb Freshers Papers IT Management Java Exapmle Java Script SQL and database tutorial examples Scwcd ant tutorials concurrency example and tutorial future state homework java changes java threading tricky Agile Business of IT Development JSTL Java JSON tutorial Java multithreading Tutorials PM Scrum data structure and algorithm java puzzles java tips testing tips windows 8 5 way to create Singleton Object Architect Interview Questions and Answers Architecture Architecure Bluetooth server as swing application that searches bluetooth device in 10 meter circle and show all devices. You can send file to any bluetooth device. C Programming CIO Callable Statement in Java Circular dependency of Objects in Java Comparable Example in Collection Custom annotation in Java Developer Interview Divide and rule example in java Drupal Example of Singleton Pattern FIX protocol ForkJoin Example in Java 7 Get data from dynamic table with Java Script Git HTML and JavaScript Health Hello World TCP Client Server Networking Program Hibernate Basics Hibernate Interview Question Answer J2EE Interview Question And Answers J2ME GUI Program JEE Interview QA JMS interview question Java J2EE Hibernate Spring Struts Interview Question Java System Property Java Threads Manager Portlets Provident Fund Read data from any file in same location and give the required result. Reading Properties File in Java Redpoint Rest WebService Client Rest Webservice Test SAL join with ven diagram SCP UNIX COMMAND SSL Singleton Pattern in Java Spring Bean Initialization methods and their order Spring Interview Questions Struts Struts 2.0 Basics Struts 2.0 Design Pattern Submit Html Form With Java Script On The Fly Unix executable For Java Program XOM DOM SAX XP books computers core java; core java; object oriented programming data structure; java investment bank; design pattern dtd duplicate rows in table get browser name with jquery grails podcast inner class java beginners tutorial java cache java networking tutorial java spring java util; java collections; java questions java.java1.5 linked list mailto function with all browser oracle database oracle duplicate rows orm schema social spring mvc questions struts transaction tricks tweet windows xslt