Monday, July 16, 2018

Can you write code for the implementation of Fail Fast Iteration in java?

Problem statement: how do you write code for Fail Fast Iteration in java?
#HashMap:
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class FailFastExample {
    public static void main(String[] args) {
        Map<String, String> city = new HashMap<String, String>();
        city.put("Bangalore", "India");
        city.put("Tokyo", "Japan");
        city.put("Dubai", "UAE");
        city.put("New Jersey", "USA");

        Iterator iterator = city.keySet().iterator();

        while (iterator.hasNext()) {
            System.out.println(city.get(iterator.next()));
            // adding an element to HashMap exception will be thrown on next 
            // call of next() method.            
            city.put("Istanbul", "Turkey");
        }
    }
}

Output:
Exception in thread "main" java.util.ConcurrentModificationException
Japan
 at java.util.HashMap$HashIterator.nextNode(HashMap.java:1429)
 at java.util.HashMap$KeyIterator.next(HashMap.java:1453)
 at com.com.interview.FailFastExample.main(FailFastExample.java:18)
#ArrayList:
import java.util.ArrayList;
import java.util.Iterator;

public class FailFastExample {
    public static void main(String[] args) {
        ArrayList<Integer> lists = new ArrayList<>();
        lists.add(1);
        lists.add(2);
        lists.add(3);
        lists.add(4);
        lists.add(5);

        Iterator<Integer> itr = lists.iterator();
        while (itr.hasNext()) {
            if (itr.next() == 2) {
                // will not throw Exception

             itr.remove();
            }
        }

        System.out.println(lists);

        itr = lists.iterator();
        while (itr.hasNext()) {
            if (itr.next() == 3) {
                // will throw Exception on next call of next() method
lists.remove(3); } } } } Output: [1, 3, 4, 5] Exception in thread "main" java.util.ConcurrentModificationException at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901) at java.util.ArrayList$Itr.next(ArrayList.java:851) at com.com.interview.FailFastExample.main(FailFastExample.java:27)

No comments:

Post a Comment

Blueprint for self-improvement

To learn faster: Make the process fun To understand yourself : Write To understand the world better : Read To build deeper connection : Lis...