Wednesday, 30 September 2015

Setter-based dependency injection in Spring

In the post Dependency Injection in Spring I have already talked about dependency injection. Dependency Injection exists in two variants.

In this post we'll see one of the type of the dependency injection called Setter-based DI.

In setter-based dependency injection, the Spring IOC container will call setter methods on your beans after invoking a no-arg constructor or no-arg static factory method to instantiate your bean.

The <property> sub-element of <bean> is used for setter injection. If you need to inject an object dependency use ref element, for primitive and String values use value element.

Let's see an example to understand it better. There is a PayServiceImpl class which uses Payment Class object to process payment, it has two fields one for Payment class object and another is amount which is an integer field.

Code for PayServiceImpl class, note that it has two fields for which values will be injected using setter dependency injection. For that reason setters are required.

 
public interface IPayService {
 void performPayment();
}
 
public class PayServiceImpl implements IPayService {
 private IPayment payment;
 private int amount;
 
 public void performPayment() {
  payment.executePayment(amount);
 }
 
 public IPayment getPayment() {
  return payment;
 }


 public void setPayment(IPayment payment) {
  this.payment = payment;
 }


 public int getAmount() {
  return amount;
 }


 public void setAmount(int amount) {
  this.amount = amount;
 }
}

Code for CashPayment class

 
public interface IPayment {
 void executePayment(int amount);
}
 
public class CashPayment implements IPayment{
 public void executePayment(int amount) {
  System.out.println("Perform Cash Payment - " + amount); 
 }
}

XML Configuration file (XML file name - appcontext.xml)

 
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
 
 <!-- defining CashPayment bean -->
  <bean id="cashPaymentBean" class="org.netjs.prog.maven_spring.CashPayment" />
 
  <!-- Defining PayServiceImpl bean and injecting payment bean -->
  <bean id="paymentBean" class="org.netjs.prog.maven_spring.PayServiceImpl">
      <property name="payment" ref="cashPaymentBean" />
      <property name="amount" value="100" />
  </bean>
  
</beans>

Here you can see that the properties defined in the PayServiceImpl class are used in the name attribute of the property element. Note that same name as given in the class should be used in the configuration file.

To run this you can use the class App -

public class App {
    public static void main( String[] args ){   
     ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("appcontext.xml");
        IPayService bean = (IPayService) context.getBean("paymentBean");
        bean.performPayment();
        context.close();
    }
}

Note that it is always recommended to use interfaces rather than concrete classes, more so with Spring as whole idea of dependency injection is to have loose coupling and interfaces help in achieving that.

That's all for this topic Setter Dependency Injection in Spring. If you have any doubt or any suggestions to make please drop a comment. Thanks!

Reference : Spring framework reference documentation


Related Topics

  1. What is Dependency Injection in Spring
  2. Constructor-based dependency injection in Spring
  3. Spring example program using XML configuration
  4. Wiring collections in Spring
  5. How to inject prototype scoped bean in singleton bean
  6. Different bean scopes in Spring

You may also like -

>>>Go to Spring tutorial page

Tuesday, 29 September 2015

Constructor dependency injection in Spring

In the post Dependency Injection in Spring I have already talked about dependency injection. In this post we'll see one of the type of the dependency injection called Constructor-based DI.

In Constructor-based dependency injection Spring IOC container invokes a class' constructor with arguments that represent the dependencies of that class.

Let's see it with an example, there is one class called Payment service which is dependent on Payment class and also has integer amount and those constructor arguments are injected through a constructor DI.

Payment Service class code

public class PayServiceImpl implements IPayService {
 private IPayment payment;
 private int amount;
 // Constructor
 PayServiceImpl(IPayment payment, int amount){
  this.payment = payment;
  this.amount = amount;
 }
 public void performPayment() {
  payment.executePayment(amount);
 }
}
public interface IPayService {
 void performPayment();
}

Code for the Payment class

public class CashPayment implements IPayment{

 public void executePayment(int amount) {
  System.out.println("Perform Cash Payment - " + amount);
  
 }

}
public interface IPayment {
 void executePayment(int amount);
}

Let's see the XML configuration file appcontext.xml, it has the declaration for the class beans and the constructor dependency injections-

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
 
 <!-- defining CashPayment bean -->
  <bean id="cashPaymentBean" class="org.netjs.prog.maven_spring.CashPayment" />

  <!-- Defining PayServiceImpl bean and injecting payment bean -->
  <bean id="paymentBean" class="org.netjs.prog.maven_spring.PayServiceImpl">
      <constructor-arg ref="cashPaymentBean" />
      <constructor-arg value="20" />
  </bean>
</beans>

Here note that ref element is used while providing reference to another bean managed by the container. Since cashPaymentBean is declared in the configuration and will be managed by the container, it can be given as value of ref element.

For primitives and Strings value element is used.

If you want to see how it all works use this class -

public class App {
    public static void main( String[] args ){   
     ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("appcontext.xml");
        IPayService bean = (IPayService) context.getBean("paymentBean");
        bean.performPayment();
        context.close();
    }
}

How Constructor arguments are resolved

Constructor argument resolution matching occurs using the argument's type. The order in which the constructor arguments are defined in a bean definition is the order in which those arguments are supplied to the appropriate constructor and there they are matched using type.
So, even if order is not same in bean definition and in the class' constructor arguments will be correctly matched. But arguments may not be resolved correctly if some ambiguity exists as exp. when the arguments are related by inheritance.

Let's say I have 2 classes CashPayment and CreditPayment and they are not related by inheritance.

public class CashPayment{

 public void executePayment() {
  System.out.println("Perform Cash Payment");
  
 }

}
public class CreditPayment{

 public void executePayment() {
  System.out.println("Performing credit payment");

 }

}

XML Config file

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
 
 <!-- defining CashPayment bean -->
  <bean id="cashPaymentBean" class="org.netjs.prog.maven_spring.CashPayment" />
  <bean id="creditPaymentBean" class="org.netjs.prog.maven_spring.CreditPayment" />
  <!-- Defining PayServiceImpl bean and injecting payment bean -->
  <bean id="paymentBean" class="org.netjs.prog.maven_spring.PayServiceImpl">
      <constructor-arg ref="creditPaymentBean" />
      <constructor-arg ref="cashPaymentBean" />    
  </bean>
</beans>

Here I have first provided reference for CreditPayment class and then for CashPayment class. Whereas in the PayServiceImpl class' constructor CashPayment is first and then CreditPayment. Still it will be resolved correctly.

 
public class PayServiceImpl implements IPayService {
 private CashPayment payment1;
 private CreditPayment payment2;
 private int amount;
 
 PayServiceImpl(CashPayment payment1, CreditPayment payment2){
  this.payment1 = payment1;
  this.payment2 = payment2;
 }
 public void performPayment() {
  payment1.executePayment();
  payment2.executePayment();
 }
}

Output

Perform Cash Payment
Performing credit payment

Now if CashPayment and CreditPayment classes are related by inheritance then there will be ambiguity.

public interface IPayment {
 void executePayment();
}
public class CreditPayment implements IPayment {
 public void executePayment() {
  System.out.println("Performing credit payment");
 }

}
public class CashPayment implements IPayment{
 public void executePayment() {
  System.out.println("Perform Cash Payment"); 
 }
}
public class PayServiceImpl implements IPayService {
 private IPayment payment1;
 private IPayment payment2;
 
 
 PayServiceImpl(IPayment payment1, IPayment payment2){
  this.payment1 = payment1;
  this.payment2 = payment2;
 }
 public void performPayment() {
  payment1.executePayment();
  payment2.executePayment();
 }
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
 
 <!-- defining CashPayment bean -->
  <bean id="cashPaymentBean" class="org.netjs.prog.maven_spring.CashPayment" />
  <bean id="creditPaymentBean" class="org.netjs.prog.maven_spring.CreditPayment" />
  <!-- Defining PayServiceImpl bean and injecting payment bean -->
  <bean id="paymentBean" class="org.netjs.prog.maven_spring.PayServiceImpl">
      <constructor-arg ref="creditPaymentBean" />
      <constructor-arg ref="cashPaymentBean" />    
  </bean>
</beans>
public class App {
    public static void main( String[] args ){   
     ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("appcontext.xml");
        IPayService bean = (IPayService) context.getBean("paymentBean");
        bean.performPayment();
        context.close();
    }
}

Output

Performing credit payment
Perform Cash Payment

Here it can be seen that in class PayServiceImpl both CashPayment and CreditPayment have reference through IPayment, so type is same thus whichever class comes first in the bean definition will be configured first.
You can change the reference in the config file and then CashPayment will be called first.

When a primitive type or String is used, we need to explicitly specify the type of the constructor arg using the type attribute.

Let's see an example

public class AmountBean {
 private int amount;
 private String year;
 public AmountBean(int amount, String year) {
  this.amount = amount;
  this.year = year;
 }
 
 public void displayValue(){
  System.out.println("amount - " + amount);
  System.out.println("year - " + year);
 }
}

In the XML config file you can add the bean declaration for the AmountBean class.

<bean id="amountBean" class="org.netjs.prog.maven_spring.AmountBean">
   <constructor-arg value="2015" />    
   <constructor-arg value="200" />
</bean>

In the configuration I have provided value for the string argument year first and then for integer argument amount.

 
public class App {
    public static void main( String[] args ){   
     ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("appcontext.xml");
     AmountBean bean = (AmountBean)context.getBean("amountBean");
     bean.displayValue();
        context.close();
    }
}

Output

amount - 2015
year - 200

It can be seen that without specifying the type attribute, container can't resolve it correctly. 2015 is assigned to integer arg and 200 is assigned to String arg.

Using type attribute

type matching can be provided by explicitly specifying the type of the constructor argument using the type attribute.

 
<bean id="amountBean" class="org.netjs.prog.maven_spring.AmountBean">
   <constructor-arg type="java.lang.String" value="2015" />    
   <constructor-arg type="int" value="200" />
</bean>

Using index attribute

Another option is using the index attribute to specify explicitly the index of constructor arguments. Note that index is 0 based.

<bean id="amountBean" class="org.netjs.prog.maven_spring.AmountBean">
   <constructor-arg index="1" value="2015" />    
   <constructor-arg index="0" value="200" />
</bean>

Here I am explicitly saying that first value should be assigned to the second constructor argument and the second value to the first constructor argument.

Reference : Spring framework reference documentation

That's all for this topic Constructor Dependency Injection in Spring. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. What is Dependency Injection in Spring
  2. Setter-based dependency injection in Spring
  3. Spring example program using XML configuration
  4. Spring example program using JavaConfig and Annotations
  5. How to inject prototype scoped bean in singleton bean
  6. Different bean scopes in Spring

You may also like -

>>>Go to Spring tutorial page

Monday, 28 September 2015

What is Dependency Injection in Spring

Dependency injection is one of the core concept of Spring and it is imperative to understand "What is Dependecy Injection" and how Spring uses it. It is hard to explain it in theory so I'll take a simple example and go step by step to explain what Dependency injection is.

As the name suggests Dependency injection means injecting the dependencies but what does that mean? When we create any application there are many classes in it which depend on each other to execute some business logic. In that case any object which needs other objects to do its work, is responsible for getting those dependencies itself.

Let's see it with an example -

Suppose there is a payment service through which you can execute several kind of payments - cash payment, credit card payment, debit card payment etc.

So you create an interface which every Payment class should implement -

public interface IPayment {
    void executePayment();
}

And you create one of the class CashPayment for processing cash payments.

public class CashPayment implements IPayment{
 public void executePayment() {
  System.out.println("Perform Cash Payment"); 
 }
}

Then you create an interface for your Payment Service class and the PaymentService class itself -

public interface IPayService {
 void performPayment();
}
public class PayServiceImpl implements IPayService {
 private CashPayment cashPayment;
 PayServiceImpl(){
  this.cashPayment = new CashPayment();
 }

 public void performPayment() { 
  cashPayment.executePayment();
 }
}

Now you can see the problems here in the PaySerivceImpl class -

  • It is creating its own CashPayment reference, so it is tightly coupled only to cash payment functionality. How about Credit card payment or debit card payment or any other mode of payment?
  • We started well with creating separate classes for separate behaviours and using interfaces but then we introduced CashPayment class itself in PaySerivceImpl, with that one step separation of concern is gone!
  • What if we need to unit test this class? We can't mock its dependencies (i.e. the Payment class) as PayServiceImpl class is tightly coupled to CashPayment class.

Now you know the hazards of tightly coupled dependencies but at the same time you also know that dependencies will always be there in any applications, Objects will refer to each other in order to execute the business logic.

So, how about getting those dependencies injected in your code by some other class, in that case objects won't be creating their dependencies themselves but the dependencies will be injected into the objects. Again let's see the same example with some changes to facilitate dependency injection.

How about writing your PayServiceImpl class like this -

public class PayServiceImpl implements IPayService {
 private IPayment payment;
 
 PayServiceImpl(IPayment payment){
  this.payment = payment;
 }
 public void performPayment() {
  payment.executePayment();
 }
}

Just compare it with the previous implementation of PayServiceImpl class.

  • There it was tightly coupled with the specific implementation (CashPayment) of the IPayment interface. In this class it is not tightly coupled with any specific implementation.
  • In this class specific implementation is given (injected) in the constructor of the class.
    IPayService payService = new PayServiceImpl(new CashPayment());
    payService.performPayment();
    
    This will call the CashPayment implementation.
    payService = new PayServiceImpl(new CreditPayment());
    payService.performPayment()
    
    This will call the CreditPayment implementation.
  • Here the code is loosely coupled as PayServiceImpl is not tied to any specific implementation, here it only knows the interface which can easily be swapped by specific implementation at run time as we just saw in point 2

CreditPayment implementation

public class CreditPayment implements IPayment {
    public void executePayment() {
 System.out.println("Performing credit payment");
    }
}

How Spring comes in the picture

Now we know what dependency injection is and how objects can be injected rather than created by the object itself. So how about having a framework which will manage these associations for you and inject dependencies too. That's where Spring comes in the picture.

Though there are many ways in Spring to manage these associations (term used in Spring is wiring) here I'll given an example with XML configuration, that should give you an idea how dependency injection works through Spring.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
   http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
 
 <!-- defining CashPayment bean -->
  <bean id="cashPaymentBean" class="org.netjs.prog.CashPayment" />
  <!-- Defining PayServiceImpl bean and injecting payment bean -->
  <bean id="paymentBean" class="org.netjs.prog.PayServiceImpl">
      <constructor-arg ref="cashPaymentBean" />
  </bean>
</beans>

Here it can be seen that CashPayment and PayServiceImpl are declared as beans in spring XML configuration. In PayServiceImpl bean, reference of CashPayment is passed as a constructor argument. With that configuration Spring framework will take care of wiring the associations and injecting the dependencies needed by an object.

If you want to test and see how it is done this class can be used -

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App 
{
    public static void main( String[] args )
    {   
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("appcontext.xml");
        IPayService bean = (IPayService) context.getBean("paymentBean");
        bean.performPayment();
        context.close();
    }
}

In Spring framework, Dependency Injection exits in two major types:

You can mix both, Constructor-based and Setter-based DI but it is a good rule of thumb to use constructor arguments for mandatory dependencies and setters for optional dependencies.

That's all for this topic What is Dependency Injection. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Constructor-based dependency injection in Spring
  2. Setter-based dependency injection in Spring
  3. Spring example program using XML configuration
  4. Spring example program using JavaConfig and Annotations
  5. Spring example program using automatic configuration
  6. How to inject prototype scoped bean in singleton bean

You may also like -

>>>Go to Spring tutorial page

Friday, 25 September 2015

LinkedHashSet in Java

LinkedHashSet is also one of the implementation of the Set interface. Actually LinkedHashSet class extends the HashSet and has no other methods of its own.

Just like other implementations of the Set interface HashSet and TreeSet, LinkedHashSet also stores unique elements. How LinkedHashSet differs from the HashSet is that it maintains the insertion-order; that is elements in the LinkedHashSet are stored in the sequence in which they are inserted. Note that insertion order is not affected if an element is re-inserted into the set.

How it is implemented

LinkedHashSet is the Hash table and linked list implementation of the Set interface, with predictable iteration order. This implementation differs from HashSet in that it maintains a doubly-linked list running through all of its entries. If you have idea about how HashSet works internally in Java, you must be knowing internally HashSet uses HashMap for storing its elements.
In case of LinkedHashSet it will call the methods of HashSet only for all the operations but it will use LinkedHashMap internally.

Just take any of the Constructor of the LinkedHashSet and you will see all those contructors will ultimatey call the Constructor of the HashSet where map will be initialized as a LinkedHashMap.

LinkedHashSet Example code

public class LinkedHSDemo {

    public static void main(String[] args) {
        // Using Diamond operator Which is available from Java 7
        // Use LinkedHashSet<String> if using less than version 7
        Set<String> citySet = new LinkedHashSet<>();
        
        citySet.add("Delhi");
        citySet.add("Mumbai");
        citySet.add(null);
        citySet.add("Bangalore");
        citySet.add("Delhi");
        citySet.add(null);
        
        // Iterating the Set
        for(String str : citySet){
            System.out.println("" + str);
        }     

    }

}

Output

Delhi
Mumbai
null
Bangalore

Points to note here -

  • It can be seen that the insertion order is maintained. While iterating the LinkedHashSet elements are displayed in the order they were inserted.
  • Even though Delhi is inserted twice it is displayed only once which shows that the insertion order is not affected if an element is re-inserted into the set.
  • Only one null is allowed in the LinkedHashSet, even if I have tried to insert null twice it can be seen that only one is stored.

LinkedHashSet is not synchronized

LinkedHashSet is not thread safe. In case we need to Synchronize it, it should be synchronized externally. That can be done using the Collections.synchronizedSet method.

Set s = Collections.synchronizedSet(new LinkedHashSet(...));

LinkedHashSet class's iterator is fail-fast

The iterators returned by this class's iterator method are fail-fast: if the set is modified at any time after the iterator is created, in any way except through the iterator's own remove method, the iterator will throw a ConcurrentModificationException.

Performance of LinkedHashSet

The performance of LinkedHashSet is likely to be just slightly below that of HashSet, due to the added expense of maintaining the linked list. But there is one exception: Iteration over a LinkedHashSet requires time proportional to the size of the set, regardless of its capacity. Iteration over a HashSet is likely to be more expensive, requiring time proportional to its capacity as in the case of HashSet based on the Hashing function it may have to go through all the buckets .

That's all for this topic LinkedHashSet in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. How HashSet works internally in Java
  2. TreeSet in Java
  3. EnumSet in Java
  4. Overriding hashCode() and equals() method in Java
  5. How Linked List class works internally in Java
  6. Java Collections interview questions

You may also like -

Monday, 21 September 2015

How HashSet works internally in Java

This post goes into details about the internal implementation of the HashSet. Before going into internal working of HashSet it is important to know two points about HashSet.

  • HashSet only stores unique values i.e. no duplicates are allowed.
  • HashSet too works on the concept of hashing just like HashMap but how it differs from the HashMap is; in HashMap a (Key, Value) pair is added and the hash function is calculated using key. Where as in the HashSet hash function is calculated using the value itself. Note that in HashSet we have add(E e) method which takes just the element to be added as parameter.
    Also you may have guessed by now, since hash function is calculated using value that is why only unique values are stored in the HashSet. If you try to store the same element again, the calculated hash function would be same, thus the element will be overwritten.

Now coming back to internal working of HashSet, which is also an important Java Collections interview question, the most important point is HashSet internally uses HashMap to store it's objects. Within the HashSet there are many constructors one without any parameter and several more with initial capacity or load factor but every one of these constructor creates a HashMap. If you know how HashMap works internally in Java it is easy to understand how HashSet works internally.

HashSet Constructor snippets

In the HashSet class you can see that constructors of the class do create a HashMap.

/**
* Constructs a new, empty set; the backing <tt>HashMap</tt> instance has
* default initial capacity (16) and load factor (0.75).
*/
public HashSet() {
    map = new HashMap<>();
}
public HashSet(int initialCapacity, float loadFactor) {
    map = new HashMap<>(initialCapacity, loadFactor);
}

And the map, which is used for storing values, is defined as

private transient HashMap<E,Object> map;

In the constructor, if you have noticed, there are parameters named initial capacity and load factor. For HashSet, default initial capacity is 16, that is an array (or bucket) of length 16 would be created and default load factor is 0.75. Where load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased.

How elements are added in HashSet

I stated in the point 2 above that HashSet calculates the hash function using value itself and there is no (Key, Value) pair in HashSet and then came the statement that HashSet internally uses HashMap to store objects. These two statements may sound contradictory as HashMap stores (key, value) pair so let's see how these these two contradictory statements hold true.

Actually in HashSet, from add method, put method of HashMap is called where the value which has to be added in the Set becomes Key and a constant object "PRESENT" is used as value.

That's how PRESENT is defined in HashSet implementation -

// Dummy value to associate with an Object in the backing Map
private static final Object PRESENT = new Object();

And that's how add method is implemented in HashSet class -

public boolean add(E e) {
    return map.put(e, PRESENT)==null;
} 

So you can see with in the internal implementation of the HashSet it's a (key, value) pair which is actually getting added. It's just that the actual value (which is added to the HashSet) becomes the key and a dummy value "PRESENT" is added as value when storing it in the backing HashMap.

One thing to note here is, in HashMap value may be duplicate but Key should be unique. That's how HashSet makes sure that only unique values are stored in it, since the value which is to be stored in the HashSet becomes the key while storing it in HashMap.

How Object is removed from a HashSet

When we need to remove an element from the HashSet, internally again remove method of HashSet calls remove(Object key) method of the HashMap.

That is how it is implemented in HashSet class.

public boolean remove(Object o) {
    return map.remove(o)==PRESENT;
}

Here note that remove(Object key) method of the HashMap returns the Value associated with the key. Whereas the remove(Object o) method of the HashSet returns Boolean value. Also we know that for every value added in HashSet that value becomes Key and the value is always an object called PRESENT. Therefore the value that is returned from the remove(Object key) method of the HashMap is always PRESENT thus the condition map.remove(o)==PRESENT.

How Object is retrieved from HashSet

In HashSet there is no get method as provided in Map or List. In HashSet iterator is there which will iterate through the values of the Set. Internally it will call the keyset of the HashMap, as values are stored as keys in the HashMap so what we'll get is the values stored in the HashSet.

That's how iterator is implemented in the HashSet

/**
* Returns an iterator over the elements in this set.  The elements
* are returned in no particular order.
*
* @return an Iterator over the elements in this set
* @see ConcurrentModificationException
*/
public Iterator<E> iterator() {
    return map.keySet().iterator();
}

Points to note

  1. Unlike HashMap where hash function is calculated using key HashSet uses the value itself to calculate the hash function.
  2. Since hash function is calculated using value that is why only unique values are stored in the HashSet.
  3. HashSet internally uses HashMap to store its elements.
  4. When element is added to HashSet using add(E e) method internally HashSet calls put() method of the HashMap where the value passed in the add method becomes key in the put() method. A dummy value “PRESENT” is passed as value in the put() method.

That's all for this topic How HashSet internally works in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. How ArrayList works internally in Java
  2. How HashMap internally works in Java
  3. How Linked List class works internally in Java
  4. LinkedHashSet in Java
  5. TreeSet in Java
  6. EnumSet in Java

You may also like -

Friday, 18 September 2015

How to convert ArrayList to Array in Java

While working with ArrayList, there may be a need to get the actual array that holds the elements of the list. It may be required because -

  • You have to pass the List to some third party method which takes array as parameter.
  • For faster processing of certain operations.

First approach

Well there is always brute force approach to loop through the list, get the elements of the list using get method and assign them to array.

Example code

public class ConvertArray {
    public static void main(String[] args) {
        List<String> cityList = new ArrayList<String>();
        cityList.add("Delhi");
        cityList.add("Mumbai");
        cityList.add("Bangalore");
        cityList.add("Hyderabad");
        cityList.add("Chennai");
        
        // Create an array of the same size as list
        String cityArray[] = new String[cityList.size()];   
        
        // Loop through the list and assign values to array
        for(int i =0; i < cityList.size(); i++){
            cityArray[i] = cityList.get(i);
        }
        
        //Displaying Array values
        for(String name : cityArray)
        {
            System.out.println("City : " + name);
        }
    }
}

Output

City : Delhi
City : Mumbai
City : Bangalore
City : Hyderabad
City : Chennai

Better approach

But there is another option provided by Collection interface itself. Within Collection interface there are two versions of toArray() which can be used to convert ArrayList to array.

  • Object[] toArray()
  • <T> T[] toArray(T array[])

The first version returns an array of Object. The second version returns an array containing the elements of the list. Normally we go with the second version because it returns the array of the same type as List.

Let's see the same example as above with the second version of toArray()

Example code

public class ConvertArray {
    public static void main(String[] args) {
        List<String> cityList = new ArrayList<String>();
        cityList.add("Delhi");
        cityList.add("Mumbai");
        cityList.add("Bangalore");
        cityList.add("Hyderabad");
        cityList.add("Chennai");
        
        // Create an array of the same size as list
        String cityArray[] = new String[cityList.size()];   
        
        cityArray = cityList.toArray(cityArray);
        
        //Displaying Array values
        for(String name : cityArray)
        {
            System.out.println("City : " + name);
        }
    }
}

So that's how we can get an array from ArrayList.

That's all for this topic How to convert ArrayList to Array in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. How to convert Array to ArrayList in Java
  2. Difference between Array and ArrayList in Java
  3. ArrayList in Java
  4. Difference between ArrayList and LinkedList in Java
  5. How to loop/iterate an arraylist in Java
  6. Java Collections interview questions

You may also like -

Tuesday, 15 September 2015

Joining lists in Java

Sometimes we do have a need to join the lists constructed through different queries or received through different sources.

Though the first thing that comes to mind in this scenario is loop the second list, retrieve the elements from the second list and add them to the first list.

Some thing like this -
List<String> cityList = new ArrayList<String>();
cityList.add("Delhi");
cityList.add("Mumbai");
cityList.add("Kolkata");
List<String> anotherCityList = new ArrayList<String>();
anotherCityList.add("Hyderabad");
anotherCityList.add("Bangalore");
anotherCityList.add("Mumbai");    
for(int i = 0; i < anotherCityList.size() ; i++){
    cityList.add(anotherCityList.get(i));
}
for(String cityName : cityList){
    System.out.println("City Name " + cityName);
}

But why even write a loop and add elements one by one when List provides a method addAll to do that.

According to Java Docs

addAll method appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's Iterator.

General form of addAll

addAll(Collection<? extends E> c)

Using Apache Commons Collections

There is another way to join lists using Apache Commons Collections. Only thing we need is to add commons-collections jar to our project. It provides a ListUtils class which has a static method union to merge two lists.

According to the description of this method -

Returns a new list containing the second list appended to the first list. The List.addAll(Collection) operation is used to append the two given lists into a new list.

General form of union method

public static java.util.List union(java.util.List list1, java.util.List list2)

Though the name "union" may suggest otherwise please note that it will retain the duplicate elements in both the lists.

Let's see some example code using the above two options to merge two (or more) lists -

import java.util.ArrayList;
import java.util.List;
import org.apache.commons.collections4.ListUtils;

public class JoinListDemo {
    public static void main(String[] args) {
        List<String> cityList = new ArrayList<String>();
        cityList.add("Delhi");
        cityList.add("Mumbai");
        cityList.add("Kolkata");
        List<String> anotherCityList = new ArrayList<String>();
        anotherCityList.add("Hyderabad");
        anotherCityList.add("Bangalore");
        anotherCityList.add("Mumbai");
        
        // Using ListUtils.union
        System.out.println("Using ListUtils.union");
        List<String> newCityList = ListUtils.union(cityList, anotherCityList);
        for(String cityName : newCityList){
            System.out.println("City Name " + cityName);
        }
        
        // Using addAll method, here adding with in the first list
        // we can create a new list and use addAll method to 
        // add both lists to the new List
        System.out.println("Using addAll method");
        cityList.addAll(anotherCityList);
        for(String cityName : cityList){
            System.out.println("City Name " + cityName);
        }
    }
}

Output

Using ListUtils.union
City Name Delhi
City Name Mumbai
City Name Kolkata
City Name Hyderabad
City Name Bangalore
City Name Mumbai
Using addAll method
City Name Delhi
City Name Mumbai
City Name Kolkata
City Name Hyderabad
City Name Bangalore
City Name Mumbai

You can see that duplicates are retained when the union method is used, union is a bit misleading as generally it suggests that duplicates will be counted once.
addAll method is used to append second list to the first list, if there is a requirement that original lists should not be altered then you can create a new list and use addAll method to add both the lists to a new list.

That's all for this topic Joining lists in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. How ArrayList works internally in Java
  2. How HashMap internally works in Java
  3. How HashSet works internally in Java
  4. How to remove elements from an ArrayList in Java
  5. How to loop/iterate an arraylist in Java
  6. How to sort arraylist of custom objects in Java
  7. Java Collections interview questions

You may also like -

Saturday, 12 September 2015

ListIterator in Java

Though there is already an iterator provided for the list, which will iterate sequentially through all the elements in a list but it is uni-directional.

Iteration of a list

So if we are iterating this ArrayList we can only go from left to right. If we have any such requirement where we want to iterate the list in both directions we can use ListIterator. ListIterator provides both next() and previous() methods to iterate in both directions.

The interesting point about Listiterator is that it has no current element. Its current cursor position always lies between the element that would be returned by a call to previous() and the element that would be returned by a call to next(). An iterator for a list of length n has n+1 possible cursor positions.

Iterating a list using list iterator

ListIterator methods summary

  1. add(E e) - Inserts the specified element into the list (optional operation).
  2. hasNext() - Returns true if this list iterator has more elements when traversing the list in the forward direction.
  3. hasPrevious() - Returns true if this list iterator has more elements when traversing the list in the reverse direction.
  4. next() - Returns the next element in the list and advances the cursor position.
  5. nextIndex() - Returns the index of the element that would be returned by a subsequent call to next().
  6. previous() - Returns the previous element in the list and moves the cursor position backwards.
  7. previousIndex() - Returns the index of the element that would be returned by a subsequent call to previous().
  8. remove() - Removes from the list the last element that was returned by next() or previous() (optional operation).
  9. set(E e) - Replaces the last element returned by next() or previous() with the specified element (optional operation).

Note that the remove() and set(object) methods are not defined in terms of the cursor position, they are defined to operate on the last element returned by a call to next() or previous().

public class ListIteratorDemo {
    public static void main(String[] args) {
        List<Integer> numberList = new ArrayList<Integer>();
        ListIterator<Integer> ltr = null;
        numberList.add(25);
        numberList.add(17);
        numberList.add(108);
        numberList.add(76);
        numberList.add(2);
        numberList.add(36);
        ltr = numberList.listIterator();
        //forward iteration
        System.out.println("Iterating list in forward direction");
        while(ltr.hasNext()){
            System.out.println(ltr.next());
        }
        // backward iteration 
        System.out.println("Iterating list in backward direction");
        while(ltr.hasPrevious()){
            System.out.println(ltr.previous());
        }
    }
}

Here we are first going forward using next() method. When the forward iteration is done cursor is after the last element so we can go backward using previous method() till the start of the list and that's what is done in the code.

Points to note

  • ListIterator provides an add(E e) method which is not there in Iterator. add(E e) inserts the specified element into the list (optional operation). The element is inserted immediately before the element that would be returned by next(), if any, and after the element that would be returned by previous(), if any.
  • ListItearator also provides set method. void set(E e) replaces the last element returned by next() or previous() with the specified element (optional operation). This call can be made only if neither remove() nor add(E) have been called after the last call to next or previous.
  • ListIterator is fail-fast and will throw a ConcurrentModificationException if the underlying collection is structurally modified in any way except through the iterator's own remove or add methods.

That's all for this topic ListIterator in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. How ArrayList works internally in Java
  2. How to loop/iterate an arraylist in Java
  3. How to join lists in Java
  4. How to remove duplicate elements from an ArrayList in Java
  5. How to sort arraylist in Java
  6. How to sort arraylist of custom objects in Java
  7. Java Collections interview questions

You may also like -

Wednesday, 9 September 2015

How to resolve Local variable defined in an enclosing scope must be final or effectively final error

This post talks about how to resolve "local variable defined in an enclosing scope must be final or effectively final" error while trying to write a lambda expression.

Let's first get some background on what is effectively final; that will help you to get an idea why this error is coming.

Effectively Final

When a lambda expression uses an assigned local variable from its enclosing space there is an important restriction.
A lambda expression may only use local variable whose value doesn't change. That restriction is referred as "variable capture" which is described as; lambda expression capture values, not variables. The local variables that a lambda expression may use are known as "effectively final".
An effectively final variable is one whose value does not change after it is first assigned. There is no need to explicitly declare such a variable as final, although doing so would not be an error. Since there is no need to explicitly declare such a variable as final thus the name effectively final. If there is an attempt to change such a variable, anyway compiler will throw an error.

Let's see it with an example. Here I have a functional interface IFunc which has a single abstract method display. Since it has a single abstract method it is a functional interface and lambda expression can be used to implement this functional interface. Just to make it clear I have also used the @Functional interface annotation.
In the code lambda expression that implements the display method of the interface just prints the value of the local variable on the console. It can be noted that there is no need to declare variable i as final which was a requirement before Java 8 (in case of anonymous class).

@FunctionalInterface
interface  IFunc{
    void display();
}

public class InnerDemo {
    
    public static void main(String[] args) {
        int i = 7;
        // lambda expression that implements the display method 
        // of the IFunc functional interface 
        IFunc ifunc = ()-> System.out.println("Value of i is " + i);
        // Calling the display method
        ifunc.display();
    }
    
}

Output

Value of i is 7

It can be seen if we are not changing the value of local variable i, it can be used with lambda expression and there is no need to declare i as final.

When will it give error

As already pointed out while discussing effectively final "A lambda expression may only use local variable whose value doesn't change". So if you try to change the value of i with in the lambda expression you'll get the error "Local variable i defined in an enclosing scope must be final or effectively final".

Code which will give compiler error

@FunctionalInterface
interface  IFunc{
    void display();
}

public class InnerDemo {
    public static void main(String[] args) {
        int i = 7;
        // lambda expression that implements the display method 
        // of the IFunc functional interface 
        IFunc ifunc = ()-> System.out.println("Value of i is " + i++);
        // Calling the display method
        ifunc.display();
    }   
}

Here I have changed the i to i++ in System.out thus the program will give compiler error "Local variable i defined in an enclosing scope must be final or effectively final".

So it should be clear by now what it means for a variable to be effectively final and why do you get this error "local variable defined in an enclosing scope must be final or effectively final".

That's all for this topic How to resolve "Local variable defined in an enclosing scope must be final or effectively final" error. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Overview of lambda expressions
  2. Functional interfaces & lambda expression
  3. Functional interface annotation in Java 8
  4. Lambda expression and variable scope
  5. How to fix the target type of this expression must be a functional interface error

You may also like -

Monday, 7 September 2015

How and why to synchronize ArrayList in Java

ArrayList is one of the most used Collections and why shouldn't it be? It's easy to use, has many implemented methods to provide all the important functionality and it is fast. But that fast performance comes at a cost, ArrayList is not synchronized. What does that mean? That means sharing an instance of ArrayList among many threads where those threads are modifying (by adding or removing the values) the collection may result in unpredictable behaviour.

So in this post we'll see why we may need to synchronize an ArrayList and how to synchronize an ArrayList.

Sharing an ArrayList among multiple threads

First of all let's see what will happen if an instance of ArrayList is shared among many threads. In the given code an ArrayList instance is shared among three threads and each thread is trying to insert ten elements in the ArrayList.

So the expected output is - Size of arraylist should be 30 and on looping the list I should get values 0..9 three times. As I said it may give unpredictable result so let's see what happens when we run it.

Example Code

public class SynchroProblem implements Runnable{
    private List<Integer> numList;
    
    //Constructor
    public SynchroProblem(List<Integer> numList){
        this.numList = numList;
    }
    @Override
    public void run() {
        System.out.println("in run method");
        for(int i = 0; i < 10; i++){
            numList.add(i);
            try {
                // introducing some delay
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    
    public static void main(String[] args) {
        List<Integer> numList = new ArrayList<Integer>();
        // Creating three threads
        Thread t1 = new Thread(new SynchroProblem(numList));
        Thread t2 = new Thread(new SynchroProblem(numList));
        Thread t3 = new Thread(new SynchroProblem(numList));
        t1.start();
        t2.start();
        t3.start();
        try {
            t1.join();
            t2.join();
            t3.join();
        } catch (InterruptedException e) {    
            e.printStackTrace();
        }
        System.out.println("Size of list is " + numList.size());
        for(Integer i : numList){
            System.out.println("num - " + i);
        }    
    }
}

Output

in run method
in run method
in run method
Size of list is 27
num - null
num - 0
num - 0
num - 1
num - 1
num - 1
num - 2
num - 2
num - 2
num - 3
num - null
num - 3
num - 4
num - 4
num - 4
num - 5
num - 5
num - 5
num - 6
num - 6
num - 7
num - 7
num - 7
num - 8
num - 9
num - 9
num - 9

It can be seen from the output that size is 27 (not 30) and two of the values are NULL where as 6 is inserted only twice and 8 only one time. So you can see the effect of multi-threading on an arraylist. Note that if you run this program on your system you may get different result. Well it is supposed to be unpredictable!

Alternatives

Now when we know ArrayList is not synchronized and sharing its instance among many threads may give unpredictable result we have to look for the alternatives. We can of course use a Vector which is synchronized, Collections class also provides a method synchronizedList(), which returns a synchronized (thread-safe) list backed by the specified list. Another alternative is CopyOnWriteArrayList which is part of the java.util.concurrent Package.

Let's see the same example used above where Collections.synchronizedList is used.

public class SynchroProblem implements Runnable{
    private List<Integer> numList;
    
    //Constructor
    public SynchroProblem(List<Integer> numList){
        this.numList = numList;
    }
    @Override
    public void run() {
        System.out.println("in run method");
        for(int i = 0; i < 10; i++){
            numList.add(i);
            try {
                // introducing some delay
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    
    public static void main(String[] args) {
        //List<Integer> numList = new Vector<Integer>();
        // Synchronizing the list
        List<Integer> numList = Collections.synchronizedList(new ArrayList<Integer>());
        // Creating three threads
        Thread t1 = new Thread(new SynchroProblem(numList));
        Thread t2 = new Thread(new SynchroProblem(numList));
        Thread t3 = new Thread(new SynchroProblem(numList));
        t1.start();
        t2.start();
        t3.start();
        try {
            t1.join();
            t2.join();
            t3.join();
        } catch (InterruptedException e) {    
            e.printStackTrace();
        }
        System.out.println("Size of list is " + numList.size());
        for(Integer i : numList){
            System.out.println("num - " + i);
        }    
    }
}

Output

Size of list is 30

Now everytime I get the size of the list as 30. Also elements are displayed properly 0..9 three times (I have omitted the display here).
We can also use the Vector class. It is already there in the code just uncomment the line with the vector and comment the Collections.synchronized line to see how it works with vector class. Note that Vector class is also retrofitted to use List interface that is why List reference is used to hold the Vector class.

Iterating a list in multi-threaded environment

When iterating an arraylist in a multi-threaded environment while one thread is iterating over a list there's a chance that another thread may remove a value which will disrupt the serial access.

In that case also we need to synchronize the list, In order to guarantee serial access, it is critical that all access to the backing list is accomplished through the returned list. It is imperative that the user manually synchronize on the returned list when iterating over it. Failure to follow this advice may result in non-deterministic behavior.
Reference : http://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#synchronizedList-java.util.List-

List list = Collections.synchronizedList(new ArrayList());
      ...
  synchronized (list) {
      Iterator i = list.iterator(); // Must be in synchronized block
      while (i.hasNext())
          foo(i.next());
  }

That's all for this topic How and why to synchronize ArrayList in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. How ArrayList works internally in Java
  2. How to sort arraylist of custom objects in Java
  3. How to remove elements from an ArrayList in Java
  4. CopyOnWriteArrayList in Java
  5. Synchronization in Java multithreading
  6. Java Collections interview questions

You may also like -