How HashSet works internally in Java

Hello Friends,

In this tutorial,we will see how java.util.HashSet works internally.

I would strongly recommend anybody reading this tutorial to read first How HashMap works Internally in java

How HashMap Works internally in Java

Dear Friends,

In this post,we will discuss about java.util.HashMap.How does HashMap works internally in Java.



Fail-Safe,Fail-Fast Iterators in Java and ConcurrentModificationException

In this article ,I would try to explain FAIL-FAST and FAIL-SAFE behaviour of iterators.

What is Iterator






Iterator is an interface defined in java.util package,with following methods declared in it :

boolean hasNext();
E next();
void remove();

8 Must Know ArrayList Read Operations for Java Developers

Hello Friends,

In this article,we will see all the read operations which can be performed on one of the very commonly used collection i.e. ArrayList.If you want to see all the write operations which can be performed on an ArrayList,you can go through my previous article ArrayList Write operations explored.



Must Know ArrayList Write Operations for Java developers

Hello Friends,

In this post, We will discuss on various write operations which can be performed on an ArrayList.

1) How to add elements in the list

Adding elements one by one and one after other using add method
List<String> list = new ArrayList<String>();
list.add("a");
This will add element "a" at zeroth index.
list.add("b");
This will add element "b" at first index.
list.add("c");
This will add element "c" at second index.
So we conclude from this that ArrayList use zero based indexing just like arrays. Here we should remember that ArrayList is actually implemented using arrays only. To know more about how ArrayList works ,you can read ArrayList features every java developer must know.
I would discuss indexOf() method later, but to check if the index is actually zero based, we can check as follow :
System.out.println("List Size:"+list.size());
System.out.println("Index of a:"+list.indexOf("a"));
System.out.println("Index of b:"+list.indexOf("b"));
System.out.println("Index of c:"+list.indexOf("c"));
Output : 
Index of a:0
Index of c:1
Index of d:2
Adding element at specific index using add method
list.add(1,"b");
This will add element "b" at 1st position in the ArrayList. But if this is going to insert element "b" at 1st position then what is going to happen with element "c" which is already there at 1st position.

I think you guessed it right.....

So below are the sequence of events that will happen when element "b" is added at 1st position.

Element at position 2 ("d") is moved to position 3.
Element at position 1("c") is moved to position 2
Newly added element "b" is inserted into position 1.

So basically it shifts element at the current position and subsequent elements towards one position right and inserts new element at the specified index.

Now lets try to add all element starting from index zero using this method.
List<String> list = new ArrayList<String>();
System.out.println("List Size:"+list.size());
list.add(0,"a");
list.add(1,"b");
list.add(2,"c");

for (String str : list){
   System.out.println(str);
}
Output :
List Size:0
a
b
c
So far so good.....Now lets start elements directly from index 1
List<String> list = new ArrayList<String>();
System.out.println("List Size:"+list.size());
list.add(1,"a");
list.add(2,"b");
list.add(3,"c");

for (String str : list){
   System.out.println(str);
}
Output :
List Size:0
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 1, Size: 0
 at java.util.ArrayList.add(ArrayList.java:367)
 at com.test.TestComment.main(TestComment.java:15)
So from above code we can see that when we instantiate ArrayList, it is created with default capacity of 10 but initial size of zero and we can't start adding element in ArrayList from position 1,we have to start with inserting element from position zero.

If we see source code for add(index, element) method, it says 
if (index > size || index < 0) 
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); 
Now when we are adding element directly from position 1,that time size of the ArrayList is still zero, so above condition will be true(1(index) > 0(size)),so IndexOutOfBoundException,but when we start adding elements from position zero, above condition will be false(0(index) > 0(size)),so no IndexOutOfBoundException.

So what if we want to have ArrayList with some initial size as non zero. We can do something like as below
 
List<Integer> list = new ArrayList<Integer>(Arrays.asList(new Integer[15]));
This will create ArrayList with initial size of 15 and we can add elements like
list.add(1,1);

Adding elements of another collection at the end of existing list  using addAll method
List<String> list = new ArrayList<String>();
list.add(0,"a");
list.add(1,"b");
list.add(2,"c");

List<String>  newList = new ArrayList<String>();
newList.add(0,"d");
newList.add(1,"e");

list.addAll(newList);
for(String str : list){
  System.out.println(str);
}
Output :
a
b
c
d
e
Lets try to add a Set to list
List<String> list = new ArrayList<String>();
list.add(1,"a");
list.add(2,"b");
list.add(3,"c");

Set<String> set = new HashSet<String>();
set.add("d");
set.add("e");

list.addAll(set);

for(String str : list){
  System.out.println(str);
}
Output :
a
b
c
d
e
We need to note here that order in which elements of set will be displayed can be different from the order in which they are inserted as HashSet does not maintain the insertion order. Basically addAll() method appends all the elements of  collection passed as parameter to it ,to the end of list ,in the order returned by the iterator of that collection.

Adding elements of another collection at the specified position in existing list  using addAll method
List<String> list = new ArrayList<String>();
list.add(0,"a");
list.add(1,"b");
list.add(2,"c");

List<String> anotherList = new ArrayList<String>();
anotherList.add("d");
anotherList.add("e");
list.addAll(2, anotherList);

for(String str : list){
   System.out.println(str);
}
Output :
a
b
d
e
c

Adding element at specific position using Set method
List<String> list = new ArrayList<String>();

list .add ("a");
list.add("b");
list.add("c");
System.out.println("Before adding element by calling set method");
for(String str : list){
              System.out.println(str);
}

//Using Set method to add element in lits

list.set(1,"d");
System.out.println("After adding element at position 1 by calling set method");
for(String str : list){
              System.out.println(str);
}
Output : 
Before adding element by calling set method
a
b
c
After adding element at position 1 by calling set method
a
d
c
As you can see from above output, set method replaces the element at the specified location with the element that is passed to it.

Difference between add(index, element) and set(index, element) method

While add(index, element) adds element at specified position and moves existing element at that position and next elements by 1 position towards right, set method simply replaces element at the specified position with the element that is passed to set method. So use add method when you want to insert element in the existing list such that you don't want to overwrite any existing element, however use set method when you want to replace element at specified location with  new element.

You can add elements in the list from zeroth index as below using add method

list.add(0,"a");
but you can not add elements to list using set method like below
list.set(0,"a");
This will give you following exception 
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
It makes sense that set method is implemented like this, as set method is for replacing an existing element in the list. In the above case we are trying to say that replace element at position zero with element "a" when there is actually no element at position zero, so it is throwing exception.

2) How to remove elements from ArrayList

Removing first occurrence of element from a list using remove method 
List<String> list = new ArrayList<String>();
list.add(0,"a");
list.add(1,"b");
list.add(2,"c");
list.add(3,"a");

System.out.println("List before removal of elements");

for(String str : list){
   System.out.println(str);
}
list.remove("a");

System.out.println("List after removal of first occurrence of element a");

for(String str : list){
   System.out.println(str);
}
Output :
List before removal of elements
a
b
c
a
List after removal of element a
b
c
a

Removing all occurrence of element from a list using removeAll method 
List<String> list = new ArrayList<String>();
list.add(0,"a");
list.add(1,"b");
list.add(2,"c");
list.add(3,"a");

System.out.println("List before removal of elements");

for(String str : list){
    System.out.println(str);
}
List<String> eleToBeRemoved = new ArrayList<String>();
eleToBeRemoved.add("a");
list.removeAll(eleToBeRemoved);

System.out.println("List after removal of element a");

for(String str : list){
    System.out.println(str);
}
Output:
List before removal of elements
a
b
c
a
List after removal of element a
b
c

Removing multiple occurrences of multiple elements using removeAll method 
List<String> list = new ArrayList<String>();
list.add(0,"a");
list.add(1,"b");
list.add(2,"c");
list.add(3,"a");
list.add(4,"b");

System.out.println("List before removal of elements");

for(String str : list){
     System.out.println(str);
}

List<String> eleToBeRemoved = new ArrayList<String>();
eleToBeRemoved.add("a");
eleToBeRemoved.add("b");
list.removeAll(eleToBeRemoved);

System.out.println("List after removal of element a");

for(String str : list){
      System.out.println(str);
}
Output :
List before removal of elements
a
b
c
a
b
List after removal of element a
c

Removing element from a specific index using remove method
List<String> list = new ArrayList<String>();
list.add(0,"a");
list.add(1,"b");
list.add(2,"c");
 
System.out.println("List before removal of element");

for(String str : list){
   System.out.println(str);
}
list.remove(1);
System.out.println("List after removal of element at index 1");

for(String str : list){
   System.out.println(str);
}
Ouput :
List before removal of element
a
b
c
List after removal of element at index 1
a
c

Retaining only particular elements in the list and removing rest using retainAll method
List<String> list = new ArrayList<String>();
list.add(0,"a");
list.add(1,"b");
list.add(2,"c");
list.add(3,"d");
list.add(4,"e");
 
System.out.println("Original List before call to retainAll....");
ListIterator lstitr = list.listIterator();
while(lstitr.hasNext()){
 System.out.print("Index:"+lstitr.nextIndex()+"\t");
        String str  = (String)lstitr.next();
 System.out.print("Elemnent:"+str);
 System.out.println();
}
 
System.out.println("Retain All..............");
List<String> retainList = new ArrayList<String>();
retainList.add("d");
retainList.add("e");
System.out.println("List of elements to be retained");
ListIterator lstitr1 = retainList.listIterator();
while(lstitr1.hasNext()){
 System.out.print("Index:"+lstitr1.nextIndex()+"\t");
        String str  = (String)lstitr1.next();
 System.out.print("Elemnent:"+str);
 System.out.println();
}
list.retainAll(retainList);
System.out.println("Original List after call to retainAll....");
ListIterator lstitr2 = list.listIterator();
while(lstitr2.hasNext()){
 System.out.print("Index:"+lstitr2.nextIndex()+"\t");
        String str  = (String)lstitr2.next();
 System.out.print("Elemnent:"+str);
 System.out.println();
}

Output :
Original List before call to retainAll....
Index:0 Elemnent:a
Index:1 Elemnent:b
Index:2 Elemnent:c
Index:3 Elemnent:d
Index:4 Elemnent:e
Retain All..............
List of elements to be retained
Index:0 Elemnent:d
Index:1 Elemnent:e
Original List after call to retainAll....
Index:0 Elemnent:d
Index:1 Elemnent:e
So from above example we can see that only element which were there in the retainList are retained in the original list and rest are removed.

What if we retainList have elements which are not present in the original list
List<String> list = new ArrayList<String>();                       list.add(0,"a");
list.add(1,"b");
list.add(2,"c");
list.add(3,"d");
list.add(4,"e");
 
System.out.println("Original List before call to retainAll....");
ListIterator lstitr = list.listIterator();
while(lstitr.hasNext()){
 System.out.print("Index:"+lstitr.nextIndex()+"\t");
        String str  = (String)lstitr.next();
 System.out.print("Elemnent:"+str);
 System.out.println();
}
 
System.out.println("Retain All..............");
List<String> retainList = new ArrayList<String>();
retainList.add("f");
retainList.add("g");
System.out.println("List of elements to be retained");
ListIterator lstitr1 = retainList.listIterator();
while(lstitr1.hasNext()){
 System.out.print("Index:"+lstitr1.nextIndex()+"\t");
        String str  = (String)lstitr1.next();
 System.out.print("Elemnent:"+str);
 System.out.println();
}
list.retainAll(retainList);
System.out.println("List size after call to retainAll:"+list.size());
System.out.println("Original List after call to retainAll....");

ListIterator lstitr2 = list.listIterator();
while(lstitr2.hasNext()){
 System.out.print("Index:"+lstitr2.nextIndex()+"\t");
 String str  = (String)lstitr2.next();
 System.out.print("Elemnent:"+str);
 System.out.println();
}
System.out.println("Nothing");
Output :
Original List before call to retainAll....
Index:0 Elemnent:a
Index:1 Elemnent:b
Index:2 Elemnent:c
Index:3 Elemnent:d
Index:4 Elemnent:e
Retain All..............
List of elements to be retained
Index:0 Elemnent:f
Index:1 Elemnent:g
List size after call to retainAll:0
Original List after call to retainAll....
Nothing
From above example we can see that as elements f and g which we wanted to retain were not there in the original list, so there is basically nothing to be retained from original list, hence all the elements from original list are removed. We checked size also after we made call to retainAll, it verifies that original list does not have any element in it after call to retainAll.

That's all on Write operations on ArrayList. For read operations on ArrayList, please read ArrayList Read Operations explored.Hope this article was helpful to you guys. Any suggestions,questions are welcome.

ArrayList features every Java developer must know

Hello Friends,

In this tutorial ,we will discuss following features of one of the very commonly and vastly used collection ArrayList.

1. What is ArrayList
2. What is the capacity of ArrayList.
3. How ArrayList capacity grows dynamically.
4. What is difference between capacity and size of ArrayList.
5. Ordered nature of ArrayList.
6. Duplicate values are allowed in ArrayList.
7. Null values are allowed in ArrayList.
8. ArrayList is not synchronized

Various ways to iterate over commonly used collections viz ArrayList,HashMap,HashSet

Hello Friends,


In this tutorial ,we will see how to iterate over very commonly used collections viz. ArrayList, HashMap and HashSet.



How to make object eligible for garbage collection

Dear Friends,

In this tutorial I would try to explain what is garbage collection in Java and How to make objects eligible for Garbage collection.

In the language like C, a programmer need to manually do the memory management himself/herself by allocating memory programmatically and then de-allocating memory programmatically, but Java provides automatic memory management facility, wherein a programmer need not take care of allocating/de-allocating memory, but there is utility which is part of JVM which do it for programmer automatically and we call is as Mr. Garbage Collector. Don't go on its name, it's a big guy actually, which does pretty decent job for programmer :)


What are Exceptions and types of Exceptions in Java

Hi Friends,

In this tutorial I would try to explain what are exceptions and types of exceptions in Java.

What are Exceptions?

Exception as its name suggest is the exceptional flow in your program rising due to the unexpected run time condition. For Example : FileNotFoundException. You may have written a code which would be reading a file placed at file system and source of that file is some other system. While writing code you are expecting that file at that particular location will always be there, but it is possible due to some issue in another system, that system or application would not have placed file at that location, which will result in FileNotFoundException in your program. Now this is a exceptional flow, as in normal or happy scenario, file would have been there and your program would have read the file and would have exit gracefully. Now you would like your program to complete gracefully if such kind of exceptional scenario arises. For that you can surround your code which is prone to exception by try block and can handle exceptional scenario in Catch block.

Java 7 language features - Try with Resources statement

Hi Friends,

Java has come up with really cool features in version 1.7.Code was named as Dolphin and released on July 28,2011.If you are interested in knowing history of all Java releases, you can go throw my earlier post History of java language.                                      


How to Install Java/JDK on your windows machine

Dear Friends,

Let  us see how we can install Java on a windows machine.I am taking here an example of 32 bit Windows 7 machine and the version of Java that we are going to install here is 1.6

Step 1 : Go to Oracle site .I am pasting here the direct link from where Java6 exe can be downloaded.

http://www.oracle.com/technetwork/java/javase/downloads/java-archive-downloads-javase6-419409.html#jdk-6u45-oth-JPR

Adding Custom templates in Eclipse for faster Java development

Dear Friends,

As we saw in the last tutorial Eclipse templates for faster java development that eclipse provides some inbuilt templates which we can use to expedite the coding.Apart from that we can create our own custom templates as well for the code which we find repetitive in nature and thus can save our precious time.

History of Java language

Dear  Friends,

Let us see evaluation of one of the most used programming language today i.e Java.

  • Java language project was started in June 1991 by team of engineers in Sun microsystem including James Gosling, Mike Sheridan, and Patrick Naughton known by Green Team and lead by James Gosling.

How Java is Platform Independent

Anyone who starts learning Java will agree that the first thing they will hear is that Java is Platform Independent language.

SO WHAT DOES THAT MEAN BY PLATFORM INDEPENDENT.

For this to understand ,first we need to understand what do we mean by platform.

Platform = Hardware + Operating System

Eclipse templates for faster Java development

Dear Friends,

In this fast pace world of IT,where one need to deliver within tight schedules,shortcuts are nice way to expedite the task.Let us see some eclipse templates which can act as a shortcut and help in faster development in Java .

All the below screenshots are self explanatory.What you need to do is to press ctrl + space keys after typing the word.

Writing your first Java Program

Hello Friends,

If you have come to this page so that means you are Java enthusiast and looking forward to learn Java. Let me tell you Java is very easy to learn, if you learn some core concepts well.

Okay, Let us create a Java project and write a java program step by step as follow :

How to get value of xml tags from a File

Hi Friends,

Sometime back I cam across situation where I had a very big file(it was log file actually) having multiple xml requests on multiple lines,so that means one xml request per line and I wanted to get values from one particular tag from each request.So I wrote program mentioned in below post,which gave me FileNames from each request.

Let us see now how we can get value of  xml tags from a big file.