Wednesday, 16 December 2015

Armstrong number - Java Program

Java program to check if a given number is an Armstrong number or not can be termed as a fresher level interview question. An  Armstrong number is a number that is equal to the sum of the digits in a number raised to the power of number of digits in the number.

As Example if we take 371, it is an Armstrong number as the number of digits here is 3, so

371 = 33 + 73 + 13 = 27 + 343 + 1 = 371

Another Example is 9474, here the number of digits is 4, so

9474 = 94 + 44 + 74 + 44 = 6561 + 256 + 2401 + 256 = 9474

And obviously 0 and 1 are also Armstrong number.

So let's write a Java program to check whether a given number is an Armstrong number or not.

package org.netjs.prgrm;

import java.util.Scanner;

public class ArmstrongNumber {

 public static void main(String[] args) {
      System.out.println("Please enter a number : ");
      Scanner scanIn = new Scanner(System.in);
      int scanInput = scanIn.nextInt();
      boolean isArmstrong = checkForArmstrongNo(scanInput);
      if(isArmstrong){
       System.out.println(scanInput + "  is an Armstrong number");
      }else{
       System.out.println(scanInput + " is not an Armstrong number"); 
      }
      scanIn.close();
 }
 
 private static boolean checkForArmstrongNo(int number){
  // convert number to String
  String temp = number + "";
  int numLength = temp.length();
  int numCopy = number;
  int sum = 0;
  while(numCopy != 0 ){
   int remainder = numCopy % 10;
   // using Math.pow to get digit raised to the power
   // total number of digits
   sum = sum + (int)Math.pow(remainder, numLength);
   numCopy = numCopy/10;
  }
  System.out.println("sum is " + sum );
  return (sum == number) ? true : false;
 }
}

Some outputs -

Please enter a number : 
125
sum is 134
125 is not an Armstrong number

Please enter a number : 
371
sum is 371
371  is an Armstrong number

Please enter a number : 
54748
sum is 54748
54748  is an Armstrong number

Explanation

Here the input is taken from the user, that number is converted to String just to get the length of the number. Logic here is to get one digit of the number at a time, starting from the last digit, get the value of that number power raised to the number of the digits and then divide the number by 10 to reduce the number by one digit. You can also add some conditions like checking for negative number, integer range etc.

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


Related Topics

  1. Check whether a given String/Number is a palindrome or not
  2. How to display pyramid patterns in Java
  3. Displaying prime numbers - Java program
  4. Factorial program in Java
  5. Writing file in Java

You may also like -

>>>Go to Java Programs page

Monday, 14 December 2015

Java Multi-Threading Interview Questions

  1. What is thread in Java?

    According to JavaDoc A thread is a thread of execution in a program. The Java Virtual Machine allows an application to have multiple threads of execution running concurrently.


  2. How do we create thread in Java?

    In Java there are two ways to create thread.

    • By implementing the Runnable interface.
    • By extending the Thread class.

    Example code snippet using Runnable interface

    class MyThread implements Runnable{
        MyThread(){
            Thread t = new Thread(this, "My Thread");
            t.start();
        }
    

    Example code snippet using Thread class

    class TestThread extends Thread{
    
    and then
    TestThread t = new TestThread();
    // starting the thread
    t.start();
    
    After the new thread is created, it will not start running until you call the start( ) method.

    Read more about How to create thread in Java here.

  3. What is the difference between thread and process?

    • A process has a self-contained execution environment, Threads exist within a process - every process has at least one.
    • Process are heavyweight tasks whereas threads are referred as lightweight processes as creating a new thread requires fewer resources than creating a new process.
    • Each Process has its own separate address spaces, threads with in the same process share the process' resources, including memory and open files. This means that it's very easy to share data amongst threads, but it's also easy for the threads to bump on each other, which can lead to unpredictable scenarios.
    • Inter process communication is expensive whereas inter thread communication is inexpensive and in Java can be achieved easily using wait and notify.
    • Context switching from one process to another is expensive; context switching between threads is generally less expensive than in processes.
    • Threads are easier to create than processes as separate address space is not required for a thread.

    Read more about difference between thread and process in Java here.

  4. What are the different thread states?

    • New - When a thread is created either by extending Thread class or implementing Runnable interface it is in "New State".
    • Runnable - When we call start() method on the thread object that causes the thread to begin execution and it's the Java Virtual Machine that calls the run method of the thread.
    • Blocked - When a resource is shared among various threads then a thread may go into blocked state as the resource may be used by another thread.
    • Waiting - A thread that is waiting indefinitely for another thread to perform a particular action is in the waiting state.
    • Timed_Waiting - A thread that is waiting for another thread to perform an action for up to a specified waiting time is in timed_waiting state.

    Read more about different thread states in Java here.

  5. What are the thread priorities and how to set thread priority?

    When a Java thread is created, it inherits its priority from the thread that created it. Thread's priority can be modified at any time after its creation using the setPriority() method which is a member of Thread class.

     public final void setPriority(int newPriority)
     
    Here newPriority specifies the new priority setting for the calling thread. The priority level ranges from 1 (least important) to 10 (most important) and the default priority level is 5.
    In Thread class, three constants are provided to define min, max and default priority for a thread.
    public final static int MIN_PRIORITY = 1;
    public final static int NORM_PRIORITY = 5;
    public final static int MAX_PRIORITY = 10;
    

    Read more about thread priorities in Java here.

  6. What does isAlive() method do in Java threading?

    isAlive() method is the member of the Thread class and its general form is -

    public final boolean isAlive()
    
    isAlive() method tests if the thread it is called upon is alive. A thread is alive if it has been started and has not yet died. The isAlive( ) method returns true if the thread upon which it is called is still running, otherwise it returns false.

    If we have a thread -
    Thread t1 = new Thread(new MyRunnableClass(), "t1");
    
    Then we can use isAlive to check if it is still running or not.
    System.out.println("t1 Alive - " + t1.isAlive());
    
    Read more about isAlive() method here.

  7. What is join() method?

    Join() method is used when you want to wait for the thread to finish. Its general form is -

    public final void join() throws InterruptedException
    
    This method waits until the thread on which it is called terminates.

    Read more about join() method here.

  8. Can we call run() method directly instead of start()?

    When we call start() method on the thread that causes this thread to begin execution and it's the Java Virtual Machine that calls the run method of this thread.
    If we directly call run method it will be treated as a normal overridden method of the thread class (or runnable interface). This run method will be executed with in the context of the current thread not in a new thread.

    Read more about Can we call run() method directly here.

  9. Can we start the same thread twice in Java?

    No. A thread can only be started once and any attempt to start the same thread twice will throw IllegalThreadStateException.

    Read more about Can we start the same thread twice here.

  10. What are wait, notify, notifyall method used for in Java multi-threading?

    Java provides inter-thread communication using the wait(), notify() and notifyAll() methods of the Object class.

    • wait method - tells the current thread (thread which is executing code inside a synchronized method or block) to give up monitor and go to sleep, until another thread invokes the notify() or notifyAll() method for this object.
    • notify method - Wakes up a single thread that is waiting on this object's monitor. If more than one threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation.
    • notifyAll method - wakes up all the threads that called wait( ) on the same object.

    Read more about wait, notify, notifyall here.

  11. What is the difference between notify() and notifyAll()?

    • Notify method wakes up a single thread that is waiting to acquire a lock on the object. If more than one threads are waiting on this object, one of them is chosen to be awakened.
    • NotifyAll method wakes up all the threads that called wait on the same object. Note that only one of these threads will get a lock to the object.

  12. Why wait(), notify() and notifyAll() methods are in object class?

    wait() and notify() work at the monitor level, thread which is currently holding the monitor is asked to give up that monitor through wait and through notify (or notifyAll) thread which are waiting on the object's monitor are notified that thread can wake up. Important point to note here is that monitor is assigned to an object not to a particular thread. That's one reason why these methods are in Object class.

    wait, notify and notifyAll() are used for inter-thread communication. But threads themselves have no knowledge of each others status. It is the shared object among the threads that acts as a communicator among the threads. Threads lock an object, wait on an object and notify an object.

    Read more about Why wait(), notify() and notifyAll() methods are in object class here.

  13. When notify method is called does the thread which comes out of waiting start executing instantly?

    No, thread which comes out of waiting because of the notify() method will not be able to proceed until the current thread relinquishes the lock on this object. The awakened thread just changes to the runnable state and it is ready to be scheduled again. The awakened thread will compete in the usual manner with any other threads that might be actively competing to synchronize on this object.

    Read more about wait, notify, notifyall here.

  14. Why wait, notify and notifyAll must be called inside a synchronized method or block?

    wait method tells the current thread (thread which is executing code inside a synchronized method or block) to give up monitor. Object's lock is acquired by a thread only when it is executing in a synchronized context. So it makes sense to use wait() method, which asks thread to release the lock only in synchronized context.

    Same way; when object's notify() or notifyAll() method is called, single thread (in case of notify) or all of the threads (in case of notifyAll), waiting for the object's lock change state to runnable and contend for the object's lock, and the thread that gets the lock starts execution. Here again, notify and notifyAll can inform other threads, that the object's lock can be acquired now, only if these methods are called from the synchronized object.

    Read more about Why wait, notify and notifyAll must be called inside a synchronized method or block here.

  15. What is spurious wakeup?

    Once wait is called on an object the thread that is currently executing with in the synchronized context waits until notify or notfyAll method is called. But there is a possibility that a waiting thread resumes again even when notify() or notifyAll() are not called (this will rarely occur in practice). This is known as spurious wakeup.
    To guard against it the recommendation is that; call to wait() method should be with in a loop that checks the condition on which the thread is waiting.


  16. What does yield method do?

    Yield - A hint to the scheduler that the current thread is willing to yield its current use of a processor. The scheduler is free to ignore this hint. The executing thread is suspended and the CPU is given to some other runnable thread. This thread will wait until the CPU becomes available again.Technically, in process scheduler's terminology, the executing thread is put back into the ready queue of the processor and waits for its next turn.
    yield is a static method of the Thread class. When called it will work on the currently executing thread, not on any particular thread.

    Read more about yield method here.

  17. What is the difference between sleep and wait?

    • The very first difference is that sleep is defined as a static method in Thread class and operates on the currently executing thread. Whereas wait() method is in Object class and operates on the thread which is currently holding the lock on the object on which the wait method is called.
    • Since wait method is supposed to release the lock on an object so it has to be called from a synchronized context (with in a synchronized method or synchronized block). If not called from a synchronized context will result in a IllegalMonitorStateException being thrown. With sleep method there is no such mandatory condition it doesn't need to be called from a synchronized context.
    • Wait method will release the lock it holds on an object before going to waiting state which gives another thread a chance to enter the synchronized block. Sleep method if called from a synchronized block or method will not release the lock so another won't get a chance to enter the synchronized block.

    Read more about difference between sleep and wait here.

  18. Why Thread.sleep() and yield() are static?

    yield and sleep methods are used to work on the currently executing thread. Thus these methods are static so that you don't call it on any other thread.


  19. What is synchronization in Java multi-threading?

    In a multithreaded environment when more than one thread are trying to access a shared resource we need to have some way to ensure that the resource will be used by only one thread at a time. The process by which it is ensured is called synchronization.

    Read more about synchronization in Java multi-threading here.

  20. What is a synchronized block?

    It is not always needed to synchronize the whole method, let's say we have a 100 line code method, out of which critical section (shared resource) is only 7 lines then it makes sense to synchronize only those 7 lines rather than synchronizing the whole method. That is known as synchronized block or statement.

    class Message{
        public void displayMsg(String msg){
            System.out.println("Inside displayMsg method " +    Thread.currentThread().getName());
            synchronized(this){
                System.out.print("**" + msg);        
                try {
                    Thread.sleep(3);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("*");
            }
        }
    }
    
    
    Read more about synchronization in Java multi-threading here.

  21. What is race condition in multi-threading?

    Race condition occurs in a multi-threaded environment when more than one thread try to access a shared resource (modify, write) at the same time. Note that it is safe if multiple threads are trying to read a shared resource as long as they are not trying to change it. Since multiple threads try to race each other to finish executing a method thus the name race condition.

    Read more about race condition in Java multi-threading here.

  22. What is a deadlock in Multi-threading?

    Deadlock describes a situation where two or more threads are blocked forever, waiting for each other. To describe it in a simple manner let's assume there are two threads Thread-1 and Thread-2 and two objects obj1 and obj2. Thread-1 already holds a lock on obj1 and for further processing it needs a lock on obj2. At the same time Thread-2 holds a lock on obj2 and wants a lock on obj1. In that kind of scenario both threads will be waiting for each other forever to release lock they are already holding thus creating a deadlock.

    Read more about deadlock in Multi-threading here.

  23. Write a program to create deadlock in Java.

    A deadlock can be created by having nested synchronized blocks where lock on objects are acquired in a reverse manner. i.e. if there are two objects obj1 and obj2 then first thread tries to acquire lock in sequence obj1 and then obj2. In the same time second thread tries to acquire lock in sequence obj2 first and then obj1.

    class Test{
        private final String name;
        public Test(String name){
            this.name = name;
        }
        public String getName() {
            return this.name;
        }
    }
    
    class ThreadA implements Runnable{
        private Test test1;
        private Test test2;
        ThreadA(Test test1, Test test2){
            this.test1 = test1;
            this.test2 = test2;
        }
        @Override
        public void run() {
            synchronized(test1){
                System.out.println("" + test1.getName());
                synchronized(test2){
                    System.out.println("Reached here");
                }
            }
            
        }
        
    }
    
    class ThreadB implements Runnable{
    
        private Test test1;
        private Test test2;
        ThreadB(Test test1, Test test2){
            this.test1 = test1;
            this.test2 = test2;
        }
        @Override
        public void run() {
            synchronized(test2){
                System.out.println("" + test2.getName());
                synchronized(test1){
                    System.out.println("Reached here");
                }
            }   
        }
    }
    public class DeadLockDemo1{
    
        public static void main(String[] args) {
            Test test1 = new Test("Test-1");
            Test test2 = new Test("Test-2");
            Thread t1 = new Thread(new ThreadA(test1, test2));
            Thread t2 = new Thread(new ThreadB(test1, test2));
            t1.start();
            
            t2.start();
        }
    }
    

    Thread t1 will start execution of run method in ThreadA and acquire lock on object test1 and then try to acquire lock on object test2. Meanwhile Thread t2 will start execution of run method in ThreadB and acquire lock on object test2 and then try to acquire lock on object test1. So both threads are trying to acquire a lock which is already held by another thread. Thus causing a deadlock.

    Read more about deadlock in Multi-threading here.

  24. What is a thread local variable?

    In Java there is a class called ThreadLocal which provides another way of thread-safety apart from synchronization. Usually when we have multiple threads sharing an object we need to synchronize the critical section of the code in order to make it thread safe.
    ThreadLocal class provides thread-local variables where each thread that accesses one (via its get or set method) has its own, independently initialized copy of the variable. Since each and every threadhas its own copy of the object so explicit synchronization is not needed to provide thread safety.

    Read more about thread local variable here.

  25. What is volatile in Java?

    When a variable is declared as volatile, the compiler (even runtime) seeing the keyword volatile knows that this variable is shared. So the volatile variables are not cached in registers and read operation on a volatile variable always returns the most recent write by any thread.

    Read more about volatile here.

  26. What is thread contention in multi-threading?

    In multi-threaded application access to shared resources must be synchronized in order to avoid thread interference.

    However, synchronization can introduce thread contention. It occurs when two or more threads try to access the same resource simultaneously but can't get the lock causing the Java runtime to execute one or more threads slowly, or even suspend their execution.

    Starvation and livelock are forms of thread contention.


  27. What is thread starvation?

    In any multi-threaded application, you may come across a situation where a thread (or a bunch of threads) is unable to gain regular access to shared resources and is unable to make progress. This situation is known as thread starvation.

    Thread starvation may happen because other “greedy” threads are gaining the lock and access to the shared resource resulting in a thread (or a bunch of threads) getting starved of access to shared resources and CPU time.

    Read more about thread starvation here.

  28. What are the reasons of thread starvation?

    Some of the reasons why thread starvation may happen in Java -

    • If there is an object providing a synchronized method that requires a lots of processing time. If there is a thread invoking this method quite frequently, other threads that also need to access the synchronized method will be blocked.
    • If there are some higher priority threads those threads will get executed first rather than the threads having lower priority.
    • If you are using wait-notify signalling, then theoretically a thread that is waiting to get access to a shared resource may wait indefinitely if always some other thread is notified and get access to the shared resource.
    Read more about thread starvation here.

  29. What is livelock?

    Livelock in Java multi-threading is a situation where two or more threads are acting on a response to an action of each other and not able to make any progress because of that.

    Read more about livelock here.

  30. How livelock is different from deadlock?

    How livelock is different from deadlock is that in case of deadlock threads get blocked whereas in case of livelock threads are active but busy responding to each other thus not making any progress.

    Read more about livelock here.

Related Topics

  1. Java OOP Interview Questions
  2. Core Java Basics Interview Questions
  3. Java String Interview Questions
  4. Java Exception Handling Interview Questions
  5. Java Collections Interview Questions
  6. Java Concurrency Interview Questions

Sunday, 13 December 2015

ArrayList in Java

ArrayList is one of the most used collection and most of its usefulness comes from the fact that it grows dynamically. You don't have to anticipate, how many elements you are going to store in the arraylist, in advance like in the case of array. As and when elements are added list keeps growing.

Though internally it is not really some "elastic" array which keeps growing, it is as simple as having an array with an initial capacity (default is array of length 10). When that limit is crossed another array is created which is 1.5 times the original array and the elements from the old array are copied to the new array.

In this post I'll list out some of the salient features of the arraylist.

Hierarchy of the ArrayList

To know about the hierarchy of the ArrayList we need to know about 2 interfaces and 2 abstract classes.

  • Collection Interface - Collection interface is the core of the Collection Framework. It must be implemented by any class that defines a collection.
  • List interface - List interface extends Collection interface. Apart from extending all the methods of the Collection interface, List interface defines some methods of its own.
  • AbstractCollection - Abstract class which implements most of the methods of the Collection interface.
  • AbstractList - Abstract class which extends AbstractCollection and implements most of the List interface.

ArrayList extends AbstractList and implements List interface too. Apart from List interface, ArrayList also implements RandomAccess, Cloneable, java.io.Serializable interfaces.

Adding elements to ArrayList

List provides a method add(E e) which appends specified element to the end of the list. Using add(E e) method will mean keep adding elements sequentially to the list.

Apart from that there is another add method - add(int index, E element)
This method inserts the specified element at the specified position in this list.

Third method
addAll(int index, Collection<? extends E> c)

Inserts all of the elements in the specified collection into this list, starting at the specified position.

Allows duplicates

In list there is no such restriction that duplicates elements can not be added. List does allow duplicate elements to be added.

public class LoopListDemo {

    public static void main(String[] args) {
        // Using Diamond operator, so with ArrayList 
        // don't need to provide String, this option is available from 
        // Java 7 onwards
        List<String> cityList = new ArrayList<>();
        cityList.add("Delhi");
        cityList.add("Mumbai");
        cityList.add("Bangalore");
        cityList.add("Mumbai");
        cityList.add("Mumbai");
        
        
        // Using for-each loop 
        System.out.println("With for-each loop - Java 5");
        for(String name : cityList){
            System.out.println("City Name - " + name);
        }
    }
}

Output

With for-each loop - Java 5
City Name - Delhi
City Name - Mumbai
City Name - Bangalore
City Name - Mumbai
City Name - Mumbai

Here it can be seen that Mumbai is added 3 times and when I am looping the list and displaying the elements in the list it is showing Mumbai 3 times.

Allows any number of nulls

In ArrayList any number of nulls can be added. Let's see it with an example.

public class LoopListDemo {
    public static void main(String[] args) {
        // Using Diamond operator, so with ArrayList 
        // don't need to provide String, this option is available from 
        // Java 7 onwards
        List<String> cityList = new ArrayList<>();
        cityList.add("Delhi");
        cityList.add("Mumbai");
        cityList.add("Bangalore");
        cityList.add("Mumbai");
        cityList.add(null);
        cityList.add("Mumbai");
        cityList.add(null);
        
        // Using for-each loop 
        System.out.println("With for-each loop - Java 5");
        for(String name : cityList){
            System.out.println("City Name - " + name);
            //cityList.remove(2);
        } 
    }
}

Output

With for-each loop - Java 5
City Name - Delhi
City Name - Mumbai
City Name - Bangalore
City Name - Mumbai
City Name - null
City Name - Mumbai
City Name - null

It can be seen here that two null elements are added in the AraryList.

Removing elements from the list

ArrayList provides several methods to remove elements from the List. Since ArrayList internally uses array to store elements, one point to note here is that when an element is removed from the List internally the remaining elements are shifted to fill the gap created in the underlying array.

  • clear() - Removes all of the elements from this list.
  • remove(int index) - Removes the element at the specified position in this list.
  • remove(Object o) - Removes the first occurrence of the specified element from this list, if it is present.
  • removeAll(Collection<?> c) - Removes from this list all of its elements that are contained in the specified collection.
  • removeIf(Predicate<? super E> filter) - Removes all of the elements of this collection that satisfy the given predicate.

Note that removeIf is added in Java 8

Example code using removeIf

public class LoopListDemo {
    public static void main(String[] args) {
        // Using Diamond operator, so with ArrayList 
        // don't need to provide String, this option is available from 
        // Java 7 onwards
        List<String> cityList = new ArrayList<>();
        cityList.add("Delhi");
        cityList.add("Mumbai");
        cityList.add("Bangalore");
        cityList.add("Mumbai");
        cityList.add("Mumbai");
        
        cityList.removeIf((String name )->name.equalsIgnoreCase("Bangalore"));
        // Using for-each loop 
        System.out.println("With for-each loop - Java 5");
        for(String name : cityList){
            System.out.println("City Name - " + name);
            //cityList.remove(2);
        }
    }
}

Output

With for-each loop - Java 5
City Name - Delhi
City Name - Mumbai
City Name - Mumbai
City Name - Mumbai

It can be seen that Bangalore is removed from the list based on the condition provided with removeIf. Note that parameter for the removeIf is of type Predicate which is a functional interface, so it's method can be implemented using lambda expression.

ArrayList is not synchronized

ArrayList is not synchronized. That means sharing an instance of arrayList among many threads where those threads are modifying the collection (adding or removing the values) may result in unpredictable behaviour. If we need to synchronize an ArrayList you can use synchronizedList method provided by Collections class, which returns a synchronized (thread-safe) list backed by the specified list.

Iterator for an ArrayList

ArrayList provides iterator to traverse the list in a sequential manner. Since ArrayList implements List interface so it provides ListIterator too which is different from the iterator in a way that it provides iteration in both directions.

One point to note here is that both iterator and listiterator are fail fast, fail-fast iterator fails if the underlying collection is structurally modified at any time after the iterator is created, thus the iterator will throw a ConcurrentModificationException if the underlying collection is structurally modified in any way except through the iterator's own remove or add (if applicable as in list-iterator) methods.

Performance of ArrayList

  • Adding an element - If you are adding at the end using add(E e) method it is O(1). Even in the case of adding at the last ArrayList may give O(n) performance in the worst case. That will happen if you add more elements than the capacity of the underlying array, as in that case a new array (1.5 times the last size) is created, and the old array is copied to the new one. If you are using add(int index, E element) then it is O(n - index) and it'll become O(n) if every time element is added at the beginning of the list.
  • Retrieving an element - Since ArrayList internally uses an array to store elements so get(int index) means going to that index directly in the array. So, for ArrayList get(int index) is O(1).
  • Removing an element - If you are removing using the remove(int index) method then, in case of ArrayList getting to that index is fast but removing will mean shuffling the remaining elements to fill the gap created by the removed element with in the underlying array. It ranges from O(1) for removing the last element to O(n). Thus it can be said remove(int index) operation is O(n - index) for the arraylist.

That's all for this topic 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 in Java
  3. How to remove duplicate elements from an ArrayList in Java
  4. How Linked List class works internally in Java
  5. How to sort arraylist of custom objects in Java
  6. CopyOnWriteArrayList in Java - The thread safe variant of ArrayList
  7. Java Collections interview questions

You may also like -

How to convert Array to ArrayList in Java

There may be a situation when you want to convert an array to an ArrayList in order to use some of the methods provided by ArrayList in Java.

As example using contains() method provided by List to check if an element is there in the list.

If you have this need of converting an array to an ArrayList then Java does provide a class Arrays which has a method for doing the same.

Arrays class contains various methods for manipulating arrays (such as sorting and searching). This class also contains a static factory that allows arrays to be viewed as lists. The method to convert Array to ArrayList is asList() whose general form is

public static <T> List<T> asList(T... a)

Using Arrays.asList() to convert array to ArrayList

In the following Java code I have an array of cities which I am converting into an ArrayList.

public class CovertToArrayList {
    public static void main(String[] args) {
         String cityArray[] = {"Delhi", "Mumbai", "Bangalore", "Hyderabad", "Chennai"};
         //Converting array to List
         List<String> cityList = Arrays.asList(cityArray);
         for(String name : cityList){
            System.out.println("City : " + name);
         } 
    }
}

There are few points to note about Arrays.asList() method

  • This method returns a List that is a view onto the array. You can say it is more of a wrapper around an array. That makes it more efficient than any other option as array elements are not actually copied to the List.
  • The list returned by this method is a fixed-size list.
  • Since list returned is just a view onto the array, if you change any element in the list that change is reflected in the array too.
  • The ArrayList class used to create the list while using this method Arrays.asList is actually a static class within the Arrays class and many of the methods of the original ArrayList are not supported by this ArrayList. As example add() method is not there in this ArrayList so any attempt to add new element to the returned list will throw "UnsupportedOperationException"

Example code

public class CovertToArrayList {

    public static void main(String[] args) {
         String cityArray[] = {"Delhi", "Mumbai", "Bangalore", "Hyderabad", "Chennai"};
         //Converting array to List
         List<String> cityList = Arrays.asList(cityArray);
         // Attempt to add new element in the list
         // This will throw exception
         cityList.add("Pune");
         for(String name : cityList){
            System.out.println("City : " + name);
         }
        
    }

}

Output

Exception in thread "main" java.lang.UnsupportedOperationException
 at java.util.AbstractList.add(Unknown Source)
 at java.util.AbstractList.add(Unknown Source)
 at org.netjs.prog.CovertToArrayList.main(CovertToArrayList.java:16)
  • You can also initialize a List using Arrays.asList() method like this
    List<String> cityList = Arrays.asList("Delhi", "Mumbai", "Bangalore", 
    "Hyderabad", "Chennai");
    
  • As stated above no new element can be added to the List returned by Arrays.asList() method. If you have to add new elements to the List then there are other options.

    • Wrapping the list returned by Arrays.asList to a new ArrayList.
      public class CovertToArrayList {
          public static void main(String[] args) {
              String cityArray[] = {"Delhi", "Mumbai", "Bangalore", 
      "Hyderabad", "Chennai"};
              //Converting array to List
              ArrayList<String> cityList = new ArrayList<String>(Arrays.asList(cityArray));
              
              cityList.add("Pune");
              for(String name : cityList){
                 System.out.println("City : " + name);
              }     
          }
      }
      

      Output

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

      It can be seen that now new elements can be added to the list.

    • Using Collections.addAll method. Here again a new List is created using the array, by passing both as parameters.
      public class CovertToArrayList {
          public static void main(String[] args) {
               String cityArray[] = {"Delhi", "Mumbai", "Bangalore", "Hyderabad", "Chennai"};
               List<String> cityList= new ArrayList<String>();
               Collections.addAll(cityList, cityArray);
               cityList.add("Pune");
               for(String name : cityList){
                  System.out.println("City : " + name);
               }        
          }
      }
      
    • Using Java 8 Stream - If you are using Stream API in Java 8 then you have another option by using collect() method.

      public class CovertToArrayList {
          public static void main(String[] args) {
               String cityArray[] = {"Delhi", "Mumbai", "Bangalore", "Hyderabad", "Chennai"};
               // Using stream
               List<String> cityList = Stream.of(cityArray).collect(Collectors.toList());
               cityList.add("Pune");
               for(String name : cityList){
                  System.out.println("City : " + name);
               }        
          }
      }
      

      Output

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

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


    Related Topics

    1. How to convert ArrayList to Array in Java
    2. How ArrayList works internally in Java
    3. How to remove duplicate elements from an ArrayList in Java
    4. Difference between ArrayList and LinkedList in Java
    5. How to join lists in Java
    6. Java Collections interview questions

    You may also like -

    Thursday, 10 December 2015

    Difference between Array and ArrayList in Java

    Difference between Array and ArrayList is one question you may come across in a Java technical interview. Though performance wise both Array and ArrayList may give almost similar performance but functionality wise they both are used in quite different scenarios.

    This question may be asked while asking some Java Collections interview questions in order to test the knowledge of the candidate about the ArrayList being dynamic and the performance difference if any.

    Array Vs ArrayList

    • First and the most important difference is Array is static and can't be resized once declared.
      Whereas ArrayList is dynamic and that is why also known as dynamic array. ArrayList also uses array of Object internally, but it has the logic to keep growing the size of the array as and when previous size is not able to fit in the number of elements stored in the ArrayList.
    • Refer How ArrayList works internally in Java to know more about the internal implementation of ArrayList.
    • Array can store both primitive types as well as Objects whereas ArrayList can store only objects. Though Autoboxing and Unboxing has blurred that difference, but the important point to note here is that in case of ArrayList any primitive data type is still wrapped and stored as an Object.

      For example, if you want an array of primitive type int -

      int[] intArray = new int[3];
      

      Or, if you have a class Employee and you want an array of size 5 to hold 5 Employee objects then -

      Employee[] employees = new Employee[5];
      

      In case of ArrayList if you want to store integers then you have to do this, note the use of wrapper class Integer -

      List<Integer> myList = new ArrayList<Integer>();
      
    • Difference number 2 also indicates one more difference, which is about "type safety". Since Array knows the type of the data which it can hold so it will give compiler error "Type Mismatch" or "ArrayStoreException" if it is not able to resolve it at run time.
      As Exp.
      Object[] names = new String[3];
      names[0] = 12;
      
      This will throw ArrayStoreException.
      Where as this
      String[] names = new String[3];
      names[0] = 12;
      
      Will throw compile time error "Type Mismatch".

      In case of ArrayList, generics brought the much needed type safety which, as shown above, is not required for Array.

      If a list, which should store only Integers, is needed it should be defined as -

      List<Integer> myList = new ArrayList<Integer>();
      

    • Performance wise both Array and ArrayList are almost similar as ArrayList also uses array of Objects internally. But there is some overhead in case of ArrayList in case of resizing the array.
    • Array has length variable which gives the length of the array. Note that length attribute denotes the length of the array at the time of declaration.
      As exp. If an array is declared like this -
      String[] names = new String[3];
      names[0] = "Java";
      
      Then length var will always be 3 even if array names has only one value.

      In case of ArrayList, size() method is used and it will give the size as the current number of elements in the ArrayList.

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


    Related Topics

    1. Difference between ArrayList and Vector in Java
    2. Difference between ArrayList and LinkedList in Java
    3. Difference between HashMap and HashTable in Java
    4. Difference between Comparable and Comparator
    5. HashSet Vs LinkedHashSet Vs TreeSet in Java
    6. Java Collections interview questions

    You may also like -

    Tuesday, 8 December 2015

    Difference between ArrayList and Vector in Java

    Vector, just like ArrayList, is also a growable dynamic array. As of Java v1.2, this class was retrofitted to implement the List interface, making it a member of the Java Collections Framework.

    With JDK 5 it was also retrofitted for generics and implements Iterable interface too which means it can also use enhanced for loop.

    So, in many ways Vector is just like ArrayList apart from some differences and this post is about those differences between the ArrayList and Vector.

    ArrayList Vs Vector in Java

    • ArrayList is not synchronized whereas Vector is Synchronized. Which means that the methods in the Vector class are Synchronized methods making Vector thread-safe and ready to use as-is in a multi-threaded environment.
      ArrayList, if needed in a multi-threaded environment, has to be synchronized externally using Collections.synchronizedList method which returns a synchronized (thread-safe) list backed by the specified list.
    • Refer How and why to synchronize ArrayList in Java to know how to synchronize an ArrayList.

    • A Vector, by default, doubles the size of its array when it needs to expand the array, while the ArrayList increases its array size by 50 percent.
    • As mentioned though Vector is retrofitted to implement the List interface it still has legacy methods which are not there in ArrayList. As Exp. methods like addElement(), removeElement(), capacity() which are there in Vector class but not in ArrayList.
    • Performance wise Vector is comparatively slower than the ArrayList because it is synchronized. That means only one thread can access method of Vector at the time and there is an overhead of acquiring lock on the object too.
    • For traversing an ArrayList as well as Vector, Iterator or ListIterator can be used. That Iterator/ListIterator is fail-fast and throws ConcurrentModificationException if any other Thread modifies the map structurally by adding or removing any element except Iterator's own remove() method.
      For Vector enumeration can also be used for traversing which is not fail-fast.

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


    Related Topics

    1. Difference between ArrayList and LinkedList in Java
    2. How to join lists in Java
    3. How to sort arraylist of custom objects in Java
    4. How to remove elements from an ArrayList in Java
    5. Difference between HashMap and HashTable in Java
    6. Java Collections interview questions

    You may also like -

    Sunday, 29 November 2015

    Java Collections interview questions

    1. What is Java Collections Framework? What are the benefits of using Collections framework?

      Java Collections Framework provides a standard way to handle a group of objects. Benefits of the Collections Framework are -

      • High performance, implementation of the Collection classes (ArrayList, LinkedList, HashSet etc.) are very efficient and used as-is in most of the cases.
      • Reduced effort as framework already provides several implementations for most of the scenarios that can be used as-is.
      • Provides interoperability, as exp. if you are using List interface any implementation that implements List interface can be swapped with the existing one.
      • If you want to extend any collection that can be easily done using the standard interfaces provided with in the Collections frameworks.

    2. Describe the Collection framework hierarchy.

      At the root of the Collections framework is Collection interface, it must be implemented by any class that defines a collection. This interface declares the core methods that every collection will have, if any class doesn't implement any of the method then it can throw UnsupportedOperationException.
      Then there are List and Set interfaces that extend Collection interface and provided some of its own behaviour that will be further implemented by the classes that implement List and Set interfaces respectively.
      There is also a Queue interface that extends collection to provide behaviour of a queue. On the other hand there is Map interface which provides core methods for the Map implementations.

      Collections Framework Hierarchy


    3. Name the core Collection classes.

      • AbstractCollection - Implements most of the Collection interface.
      • AbstractList - Extends AbstractCollection and implements List interface.
      • AbstractSequentialList - Extends AbstractList to provide sequential access.
      • ArrayList - Extends AbstractList to provide dynamic array implementation.
      • LinkedList - Extends AbstractSequentialList to implement a linked list.
      • AbstractQueue - Extends AbstractCollection and implements Queue interface.
      • ArrayDeque - Resizable-array implementation of the Deque interface.
      • PriorityQueue - Extends AbstractQueue to provide a priority-based queue.
      • AbstractSet - Extends AbstractCollection and implements Set interface.
      • HashSet - Extends AbstractSet backed by a HashTable (actually a HashMap instance).
      • LinkedHashSet - Extends HashSet to provide insertion order interation.
      • TreeSet - Extends AbstractSet (and implements NavigableSet interface) to provide sorted set.
      • EnumSet - Extends AbstractSet for use with Enum elements.

    4. How generics changed the collection framework?

      With JDK5 the Collection framework was reengineered to add generics. That was done to add "Type Safety" to the collections. Prior to JDK5 (and generics) elements were stored in collections as Object references, which brought the danger of accidentally storing incompatible types in Collection because for Collections everything was Object reference. Which would have resulted in run time error when trying to retrieve elements and casting them to the desired type.
      With the introduction of generics now we can explicitly tell which data type is to be stored in the collections, which helps in avoiding the run time error. As Collection will throw error at compile time itself for incompatible data type. As exp.

      Map<String, String> cityTemperatureMap = new LinkedHashMap<String, String>();
      
      Here we are explicitly stating that this LinkedHashMap can only store string as both key and value.


    5. What change does autoboxing bring to Collection?

      Since we know that collection cannot store primitive types, only references. Before the introduction of autoboxing/unboxing in JDK5, if you wanted to strore primitive value like int in a collection, it had to be wrapped in an Integer class manually. While retrieving the value it had to be cast manually into its primitive type.
      Collection still store only references but autoboxing/unboxing facilitate it to happen automatically, with no need to wrap it manually.

      List<Integer> tempList = new ArrayList<Integer>();
      // Storing in collection using autoboxing
      tempList.add(1);
      // wrapping primitive int 2 to Integer manually, with out autoboxing
      tempList.add(new Integer(2));
      


    6. What is for-each style loop

      Another feature which was added to Collection with JDK 5 is for-each style loop. Any collection which wants to be the target of the "for-each loop" statement has to implement iterable interface.
      Using for-each loop is easier than constructing the iterator to iterate over the collection and can be used in most of the cases rather than using the iterator loop.
      If you have a list of Strings, that can be iterated using for-each loop like this.

      for(String city : cityList){
          System.out.println("Name " + city);
      }
      


    7. What is a diamond operator?

      Diamond operator let the compiler infer the type arguments for the generic classes. It is added in Java 7.
      As Example - Before JDK7 if we had to define a Map using String as both Key and Value we had to write it like this -

      Map<String, String> cityMap = new HashMap<String, String>();
      
      In Java SE 7, you can substitute the parameterized type of the constructor with an empty set of type parameters (<>) known as diamond operator.
      Map<String, String> cityMap = new HashMap<>();
      


    8. What are the changes in Collections framework in Java 8?

      There are several changes in Collections Framework in Java 8 mostly influenced by the inclusion of Lambda expression in Java 8 -

      • Stream API - Stream can be obtained for Collection via the stream() and parallelStream() methods;
        As exp if you have a list of cities in a List and you want to remove the duplicate cities from that list it can be done as
        cityList = cityList.stream().distinct().collect(Collectors.toList());
        
      • ForEach loop which can be used with Collection. Spliterators which are helpful in parallel processing where several threads can itearate/process part of the collection.
      • New methods are added to Collections like replaceAll, getOrDefault, putIfAbsent in Map.
      • HashMap, LinkedHashMap and ConcurrentHashMap.implementation is changed to reduce hash collisions. Instead of linked list a balanced tree is used to store the entries after a certain threshold is reached.
        Refer How HashMap internally works in Java to know more about the changes done in Java 8 to HashMap internal implementation.


    9. What is ForEach statement added in Java 8?

      Java 8 has added a functional style lopping to the Collections. Real advantage of this loop is when it is used on a stream with the chain of functional methods. If you have a Map<String, String> then it can be looped using ForEach statement like this -

      Set<Map.Entry<String, String>> valueSet = cityMap.entrySet();
      valueSet.forEach((a)->System.out.println("Key is " + a.getKey() + " Value is " + a.getValue()));
      


    10. What is RandomAccess interface?

      RandomAccess interface is a marker interface used by List implementations to indicate that they support fast (generally constant time) random access.
      Note that using it with a sequential access list like LinkedList will result in taking more time to access a particular element.


    11. Which collection classes implement random access interface?

      In Java.util package the classes that implement random access interface are - ArrayList, CopyOnWriteArrayList, Stack, Vector.


    12. What is the difference between Collection and Collections?

      Collection is an interface which is the root of the Collections framework, as you can see in question#2, List, Set and Queue are the interfaces that extend the Collection interface.
      Collections is a utility class with static methods that operate on or return Collections. It provides several methods like sort, reverse, synchronizedCollection, binarySearch etc.


    13. What all Collection classes are inherently thread-safe?

      In the initial Collection classes like Vector, HashTable and Stack all the methods were synchronized to make these classes thread safe.
      Later implementations starting from Java 1.2 were not synchronized.
      Classes in java.util.concurrent package like ConcurrentHashMap, CopyOnWriteArrayList also provides thread safety but with a different implementation that doesn't require making all the methods synchronized.


    14. How can we synchronize a collection OR how to make a collection thread-safe?

      Collections class has several static methods that return synchronized collections. Each of the six core collection interfaces -Collection, Set, List, Map, SortedSet, and SortedMap - has one static factory method.

      public static <T> Collection<T> synchronizedCollection(Collection<T> c);
      public static <T> Set<T> synchronizedSet(Set<T> s);
      public static <T> List<T> synchronizedList(List<T> list);
      public static <K,V> Map<K,V> synchronizedMap(Map<K,V> m);
      public static <T> SortedSet<T> synchronizedSortedSet(SortedSet<T> s);
      public static <K,V> SortedMap<K,V> synchronizedSortedMap(SortedMap<K,V> m); 
      
      Each of these methods returns a synchronized (thread-safe) Collection backed up by the specified collection.

    15. Refer How and why to synchronize ArrayList in Java to know how to synhronoze ArrayList.
    16. How to make a Collection Class immutable?

      Collections class provides static method to make a Collection unmodifiable. Each of the six core collection interfaces -Collection, Set, List, Map, SortedSet, and SortedMap - has one static factory method.

      public static <T> Collection<T> unmodifiableCollection(Collection<? extends T> c);
      public static <T> Set<T> unmodifiableSet(Set<? extends T> s);
      public static <T> List<T> unmodifiableList(List<? extends T> list);
      public static <K,V> Map<K, V> unmodifiableMap(Map<? extends K, ? extends V> m);
      public static <T> SortedSet<T> unmodifiableSortedSet(SortedSet<? extends T> s);
      public static <K,V> SortedMap<K, V> unmodifiableSortedMap(SortedMap<K, ? extends V> m);
      


    17. What is List interface?

      List interface extends the root interface Collection and adds behaviour for the collection that stores a sequence of elements. These elements can be inserted or accessed by their position in the list using a zero-based index.


    18. Which Collection classes implement List interface?

      Some of the Collection classes that implement List interface are
      ArrayList, CopyOnWriteArrayList, LinkedList, Stack, Vector


    19. Why ArrayList is called dynamically growing array? How that dynamic behaviour is achieved?

      In the case of ArrayList you don't have to anticipate in advance, like in the case of array, how many elements you are going to store in the arraylist. As and when elements are added list keeps growing. That is why ArrayList is called dynamically growing array.
      For ArrayList, data structure used for storing elements is array itself. When ArrayList is created it initializes an array with an initial capacity (default is array of length 10). When that limit is crossed another array is created which is 1.5 times the original array and the elements from the old array are copied to the new array.

      Refer ArrayList in Java to know more about ArrayList in Java.
      Refer How ArrayList works internally in Java to know how ArrayList works internally in Java.

    20. How ArrayList works internally in Java?

      Basic data structure used by ArrayList to store objects is an array of Object class, which is defined like -
      transient Object[] elementData;
      When we add an element to an ArrayList it first verifies whether it has that much capacity in the array to store new element or not, in case there is not then the new capacity is calculated which is 50% more than the old capacity and the array is increased by that much capacity (Actually uses Arrays.copyOf which returns the original array increased to the new length)

      Refer How ArrayList works internally in Java to know how ArrayList works internally in Java.

    21. How to add elements to an ArrayList?

      • List provides a method add(E e) which appends specified element to the end of the list. Using add(E e) method will mean keep adding elements sequentially to the list.
      • Another add method - add(int index, E element) inserts the specified element at the specified position in this list.
      • Third method addAll(int index, Collection<? extends E> c) inserts all of the elements in the specified collection into this list, starting at the specified position.


    22. Does ArrayList allow duplicate elements?

      Yes. List allows duplicate elements to be added.


    23. Does ArrayList allow null?

      In ArrayList any number of nulls can be added.


    24. How to join two or more ArrayLists?

      List provides a method addAll to join two or more lists in Java.
      If you have one list cityList and another List secondCityList then you can join them using addAll like this -
      cityList.addAll(secondCityList);

      Refer How to join lists in Java to know more ways to join Lists in Java.s

    25. How to remove elements from an ArrayList?

      ArrayList provides several methods to remove elements from the List. Since ArrayList internally uses array to store elements, one point to note is that when an element is removed from the List the remaining elements have to be shifted to fill the gap created in the underlying array.

      • clear() - Removes all of the elements from this list.
      • remove(int index) - Removes the element at the specified position in this list.
      • remove(Object o) - Removes the first occurrence of the specified element from this list, if it is present.
      • removeAll(Collection<?> c) - Removes from this list all of its elements that are contained in the specified collection.
      • removeIf(Predicate<? super E> filter) - Removes all of the elements of this collection that satisfy the given predicate.
      Note that removeIf is added in Java 8

      Refer How to remove elements from an ArrayList in Java to know more ways to remove elements from an ArrayList in Java.

    26. How to remove duplicate elements from an ArrayList?

      We can use a HashSet to do the job of removing the duplicate elements. HashSet only stores unique elements and we'll use that feature of HashSet to remove duplicates.
      If you have a List called cityList you can create a HashSet using this list -
      Set<String> citySet = new HashSet<String>(cityList);
      then add this set back to the cityList
      cityList.clear();
      cityList.addAll(citySet);
      That will remove all the duplicate elements from the given list. Note that insertion order won't be retained if a HashSet is used. In case insertion order is to be retained use LinkedHashSet.

      Refer How to remove duplicate elements from an ArrayList in Java to know more ways to remove duplicate selements from an ArrayList in Java.

    27. How to loop/iterate an ArrayList in Java?

      There are many ways to loop/iterate an arrayList in Java. Options are -

      • for loop
      • for-each loop
      • iterator
      • list iterator
      • Java 8 forEach loop
      for-each loop is the best way to iterate a list if you just need to traverse sequentially through a list.

      Refer How to loop/iterate an arraylist in Java to know more ways to loop ArrayList in Java.

    28. What is ListIterator in Java?

      ListIterator provides the functionality to iterate a list in both directions. The interesting point about list iterator 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().

      Refer List iterator in Java to know more about ListIterators in Java.

    29. How to sort ArrayList in Java?

      Collections class has a static method sort which can be used for sorting an arraylist.
      There are two overloaded versions of sort method -

      • public static <T extends Comparable<? super T>> void sort(List<T> list) - Sorts the specified list into ascending order, according to the natural ordering of its elements.
      • public static <T> void sort(List<T> list, Comparator<? super T> c) - Sorts the specified list according to the order induced by the specified comparator.
      If you have a List called cityList it can be sorted like this -
      Collections.sort(cityList);

      Refer How to sort arraylist in Java to know more about How to sort ArrayList in Java.

    30. How to sort ArrayList of Strings in descending order?

      Collections.sort() method will sort the ArrayList of String in ascending order.
      To have a descending order either comparator has to be provided or reverseOrder method of the Collections class can be used.
      Collections.sort(cityList, Collections.reverseOrder());

      Refer How to sort arraylist in Java to know more about How to sort ArrayList in Java.

    31. How to sort ArrayList of custom objects in Java?

      Refer How to sort arraylist of custom objects in Java to know more about How to sort ArrayList of custom objcts in Java.


    32. How and why to synchronize ArrayList in Java?

      In order to have better performance most of the Collections are not synchronized. Which 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.
      To synchronize a List Collections.synchronizedList() method can be used.

      Refer How and why to synchronize ArrayList in Java to know more about How to synchronize ArrayList in Java.

    33. How to convert ArrayList to Array in Java?

      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.
      If you have a List called cityList, it can be converted to an array like this -
      String cityArray[] = new String[cityList.size()];   
      cityArray = cityList.toArray(cityArray);
      

      Refer How to convert ArrayList to Array in Java to know more about How to convert ArrayList to Array in Java.

    34. How to convert Array to ArrayList in Java?

      Arrays class contains a static factory method asList() that allows arrays to be viewed as lists.
      public static <T> List<T> asList(T... a)
      As Exp.

      String cityArray[] = {"Delhi", "Mumbai", "Bangalore", "Hyderabad", "Chennai"};
      //Converting array to List
      List<String> cityList = Arrays.asList(cityArray);
      

      Refer How to convert Array to ArrayList in Java to know more about How to convert Array to ArrayList in Java.

    35. How is the performance of an ArrayList?

      • Adding an element - If you are adding at the end using add(E e) method it is O(1). In the worst case it may go to O(n). That will happen if you add more elements than the capacity of the underlying array.
      • Retrieving an element - Since ArrayList internally uses an array to store elements so get(int index) means going to that index directly in the array. So, for ArrayList get(int index) is O(1).
      • Removing an element - If you are removing using the remove(int index) method then, in case of ArrayList getting to that index is fast but removing will mean shuffling the remaining elements to fill the gap created by the removed element with in the underlying array. Thus it can be said remove(int index) operation is O(n - index) for the arraylist.
      String cityArray[] = {"Delhi", "Mumbai", "Bangalore", "Hyderabad", "Chennai"};
      //Converting array to List
      List<String> cityList = Arrays.asList(cityArray);
      


    36. What is LinkedList class in Java? How is it implemented?

      LinkedList class in Java implements List and Deque interfaces and LinkedList implements it using doubly linkedlist.
      Within the LinkedList implementation there is a private class Node which provides the structure for a node in a doubly linked list. It has item variable for holding the value and two reference to Node class itself for connecting to next and previous nodes.

      Refer How Linked List class works internally in Java to know more about LinkedList in Java.

    37. What is Deque interface in Java?

      Java.util.Deque is an interface in Java which extends Queue interface and provides support for element insertion and removal at both ends. The name deque is short for "double ended queue" and is usually pronounced "deck".
      Some of the implementing classes of the Deque interface are LinkedList, ConcurrentLinkedDeque, LinkedBlockingDeque. Note that addFirst() and addLast() methods provided in the LinkedList implementation are specified by the Deque interface.


    38. Difference between ArrayList and LinkedList in Java?

      In Java collections framework ArrayList and LinkedList are two different implementations of List interface

      • LinkedList is implemented using a doubly linked list concept where as ArrayList internally uses an array of Objects which can be resized dynamically
      • For LinkedList add(e Element) is always O(1) where as for ArrayList add(e Element) operation runs in amortized constant time, that is, adding n elements requires O(n) time.
      • For LinkedList get(int index) is O(n) where as for ArrayList get(int index) is O(1).
      • If you are removing using the remove(int index) method then for LinkedList class it will be O(n). In case of ArrayList getting to that index is fast but removing will mean shuffling the remaining elements to fill the gap created by the removed element with in the underlying array.

      Refer Difference between ArrayList and LinkedList in Java to see differences in detail.

    39. Difference between ArrayList and Vector in Java?

      • ArrayList is not synchronized whereas Vector is synchronized.
      • Performace wise ArrayList is fast in comparison to Vector as ArrayList is not synchronized.
      • ArrayList, by default, grows by 50% in case the initial capacity is exhausted. In case of Vector the backing array's size is doubled by default.
      • For traversing an ArrayList iterator is used. For traversing Vecor Iterator/Enumerator can be used. Note that Iterator is fail-fast for both Vector and ArrayList. Enumerator which can be used with Vector is not fail-fast.

      Refer Difference between ArrayList and Vector in Java to see differences in detail.

    40. Difference between Array and ArrayList in Java?

      • Array is fixed in size which is provided at the time of creating an Array. ArrayList grows dynamically and also known as dynamically growing array.
      • Array can store primitive types as well as objects. In ArrayList only Objects can be stored.
      • Arrays can be multi-dimensional whereas ArrayList is always unidimensional.
        As Exp. a two dimensional array can be created as -
        Integer myArray[][] = new Integer[4][3];
      • Performance wise both Array and ArrayList are almost same as internally ArrayList also uses an Array. But there is overhead of resizing the array and copying the elements to the new Array in case of ArrayList.

      Refer Difference between Array and ArrayList in Java to see differences in detail.

    41. What is an Iterator?

      Iterator is an interface which is part of the Java Collections framework. An Iterator enables you to iterate a collection. Iterators also allow the caller to remove elements from the underlying collection during the iteration.
      Collection classes provide iterator method which returns an iterator. This iterator can be used to traverse a collection.
      As exp. if there is a set called citySet, an iterator on this set can be obtained as -

      Iterator<String> itr = citySet.iterator();
      while (itr.hasNext()) {
          String city = (String) itr.next();
          System.out.println("city " + city);        
      }
      


    42. Difference between iterator and ListIterator?

      • Iterator can be obtained on any Collection class like List or Set. But ListIterator can only be used to traverse a List.
      • Iterator only moves in one direction using next() method. ListIterator can iterate in both directions using next() and previous() methods.
      • Iterator always start at the beginning of the collection.
        ListIterator can be obtained at any point.
        As Exp. If you have a List of integers numberList, you can obtain a ListIterator from the third index of this List.
        ListIterator<Integer> ltr = numberList.listIterator(3);
        
      • ListIterator provides an add(E e) method which is not there in Iterator. add(E e) inserts the specified element into the list.
      • ListItearator also provides set method. void set(E e) replaces the last element returned by next() or previous() with the specified element

      Refer List iterator in Java to know more about ListIterator in Java.

    43. Why Iterator doesn't have add method whereas ListIterator has add method?

      Iterator can be obtained on any Collection class like List or Set so contract for Iterator makes no guarantees about the order of iteration.
      But ListIterator can only be used to traverse a List so it does guarantee the order of the iteration. That is why ListIterator provides an add operation.


    44. What is fail fast iterator?

      An iterator is considered fail-fast if it throws a ConcurrentModificationException under either of the following two conditions:

      • In multi-threaded environment, if one thread is trying to modify a Collection while another thread is iterating over it.
      • Even with single thread, if a thread modifies a collection directly while it is iterating over the collection with a fail-fast iterator, the iterator will throw this exception.
      fail-fast iterator will throw a ConcurrentModificationException if the underlying collection is structurally modified in any way except through the iterator's own remove or add (if applicable as in list-iterator) methods.
      Note that structural modification is any operation that adds or deletes one or more elements; merely setting the value of an element (in case of list) or changing the value associated with an existing key (in case of map) is not a structural modification.


    45. What is a fail-safe iterator?

      An iterator is considered fail-safe if it does not throw ConcurrentModificationException. ConcurrentModificationException is not thrown as the fail-safe iterator makes a copy of the underlying structure and iteration is done over that snapshot.
      Since iteration is done over a copy of the collection so interference is impossible and the iterator is guaranteed not to throw ConcurrentModificationException.


    46. Difference between fail-fast iterator and fail-safe iterator.

      • fail-fast iterator throws a ConcurrentModificationException if the underlying collection is structurally modified whereas fail-safe iterator doesn't throw ConcurrentModificationException.
      • fail-fast iterator doesn't create a copy of the collection whereas fail-safe iterator makes a copy of the underlying structure and iteration is done over that snapshot.
      • fail-fast iterator provides operations like remove, add and set (in case of ListIterator) whereas in case of fail-safe iterators element-changing operations on iterators themselves (remove, set and add) are not supported. These methods throw UnsupportedOperationException.

      Refer fail-fast Vs fail-safe iterator in Java to know more about the differences between fail-fast and fail-safe iterator.

    47. Can we iterate through a Map?

      Though we can't iterate a Map as such but Map interface has methods which provide a set view of the Map. That set can be iterated. Those two methods are -

      • Set<Map.Entry<K, V>>entrySet() - This method returns a set that contains the entries in the map. The entries in the set are actually object of type Map.Entry.
      • Set<K>keySet() - This method returns a set that contains the keys of the map.
      There is also a values() method in the Map that returns a Collection view of the values contained in this map.

      Refer How to loop through a map in Java to see code examples of iterating a Map.

    48. Are Maps actually collections OR Why doesn't Map extend Collection?

      Maps themselves are not collections because they don't implement Collection interface. One of the reason as mentioned here https://docs.oracle.com/javase/8/docs/technotes/guides/collections/designfaq.html#a14 is because elements are stored in a Map as a Key-Value pair which provides a very limited abstraction.
      Maps can be viewed as Collections (of keys, values, or pairs), and this fact is reflected in the three "Collection view operations" on Maps (keySet, entrySet, and values).


    49. What is Map.Entry in Map?

      Map.Entry is an interface in java.util, in fact Entry is a nested interface in Map interface. Nested interface must be qualified by the name of the class or interface of which it is a member, that's why it is qualified as Map.Entry.
      Map.Entry represents a key/value pair that forms one element of a Map.
      The Map.entrySet method returns a collection-view of the map, whose elements are of this class.
      As exp. If you have a Map called cityMap then using entrySet method you can get the set view of the map whose elements are of type Map.Entry, and then using getKey and getValue methods of the Map.Entry you can get the key and value pair of the Map.

      for(Map.Entry<String, String> entry:  cityMap.entrySet()){
         System.out.println("Key is " + entry.getKey() + " Value is " + entry.getValue());
      }
      


    50. How Does HashMap internally works in Java?

      Please Refer How HashMap internally works in Java to know about the internal implementation of the HashMap.


    51. Does HashMap allow null keys and null values?

      HashMap allows one null key and any number of null values. If another null key is added it won't cause any error. But the value with the new null key will override the value with old null key.
      As exp. If you have a Map, cityMap and you add two values with null keys in the cityMap, Kolkata will override the New Delhi as only one null key is allowed.

      cityMap.put(null, "New Delhi");
      cityMap.put(null, "Kolkata");
      


    52. What happens if HashMap has duplicate keys?

      If an attempt is made to add the same key twice, it won't cause any error but the value which is added later will override the previous value.
      As Exp. If you have a Map, cityMap and you add two values with same key in the cityMap, Kolkata will override the New Delhi.

      cityMap.put("5", "New Delhi");
      cityMap.put("5", "Kolkata");
      


    53. What is hash-collision in hash based collections?

      In HashMap, using the key, a Hash is calculated and that hash value decides in which bucket the particular Map.Entry object will reside.
      Hash collision means more than one key having the same calculated hash value thus stored in the same bucket. In HashMap, in that case Entry objects are stored as a linked-list with in the same bucket.

      Refer How HashMap internally works in Java to know about the internal implementation of the HashMap.

    54. What is the hashCode() method?

      hashCode() method is present in the java.lang.Object class. This method is used to get a unique integer value for a given object. We can see it's use with hash based collections like HashTable or HashMap where hashCode() is used to find the correct bucket location where the particular (key, value) pair is stored.

      Refer Overriding hashCode() and equals() method in Java to know more about the hashCode() method.

    55. What is equals() method?

      equals() method is present in the java.lang.Object class. It is used to determine the equality of two objects.

      Refer Overriding hashCode() and equals() method in Java to know more about the equals() method.

    56. When do we need to override hashCode() and equals() methods?

      The default implementation of equals() method in the Object class is a simple reference equality check.

      public boolean equals(Object obj){
           return (this == obj);
      }
      
      The default implementation of hashCode() in the Object class just returns integer value of the memory address of the object.
      It becomes very important to override these two methods in case we are using a custom object as key in a hash based collection.
      In that case we can't rely on the default implementation provided by the Object class and need to provide custom implementation of hashCode() and equals() method.
      If two objects Obj1 and Obj2 are equal according to their equals() method then they must have the same hash code too. Though the vice-versa is not true that is if two objects have the same hash code then they do not have to be equal too.

      Refer Overriding hashCode() and equals() method in Java to know more about Overriding hashCode() and equals() method

    57. Which Map implementation should be used if you want to retain the insertion order?

      LinkedHashMap should be used in this case.

      Refer LinkedHashMap in Java to know more about LinkedHashMap in Java.

    58. What is LinkedHashMap?

      LinkedHashMap is also one of the implementation of the Map interface, apart from implementing Map interface LinkedHashMap also extends the HashMap class. So just like HashMap, LinkedHashMap also allows one null key and multiple null values.
      How it differs from other implementations of the Map interface like HashMap and TreeMap is that LinkedHashMap maintains the insertion order of the elements which means if we iterate a LinkedHashMap we'll get the keys in the order in which they were inserted in the Map.
      LinkedHashMap maintains a doubly-linked list running through all of its entries and that's how it maintains the iteration order.

      Refer LinkedHashMap in Java to know more about LinkedHashMap in Java.

    59. Which Map implementation should be used if you want Map values to be sorted by keys?

      TreeMap should be used in this case.

      Refer Treemap in Java to know more about TreeMap in Java.

    60. What is TreeMap in Java?

      TreeMap is also one of the implementation of the Map interface like HashMap and LinkedHashMap. TreeMap class implements the NavigableMap interface and extends the AbstractMap class.
      How it differs from other implementations of the Map interface is that objects in TreeMap are stored in sorted order. The elements are ordered using their natural ordering or a comparator can be provided at map creation time to provide custom ordering.
      One important point about TreeMap is, though HashMap and LinkedHashMap allow one null as key, TreeMap doesn't allow null as key. Any attempt to add null in a TreeMap will result in a NullPointerException.

      Refer Treemap in Java to know more about TreeMap in Java.

    61. What is a WeakHashMap?

      WeakHashMap is a Hash table based implementation of the Map interface, with weak keys. An entry in a WeakHashMap will automatically be removed when its key is no longer in ordinary use. Which means storing only weak references allows garbage collector to remove the entry (key-value pair) from the map when its key is not referenced outside of the WeakHashMap.
      In WeakHashMap both null values and the null key are supported. A WeakHashMap is created as-
      Map weakHashMap = new WeakHashMap();


    62. What is a IdentityHashMap?

      IdentityHashMap class implements the Map interface with a hash table, using reference-equality in place of object-equality when comparing keys (and values). In other words, in an IdentityHashMap, two keys k1 and k2 are considered equal if and only if (k1==k2). Where as In normal Map implementations (like HashMap) two keys k1 and k2 are considered equal if and only if (k1==null ? k2==null : k1.equals(k2)).
      Note that This class is not a general-purpose Map implementation. While this class implements the Map interface, it intentionally violates Map's general contract, which mandates the use of the equals method when comparing objects. This class is designed for use only in the rare cases wherein reference-equality semantics are required.


    63. Difference between HashMap and HashTable in Java.

      Though both HashTable and HashMap store elements as a (key, value) pair and use hashing technique to store elements, moreover from Java v1.2, HashTable class was retrofitted to implement the Map interface, making it a member of the Java Collections Framework. But there are certain difference between the two -

      • HashMap is not synchronized where as HashTable is synchronized.
      • HashMap allows one null value as a key and any number of null values where as HashTable does not allow null values either as key or as value.
      • For traversing a HashMap an iterator can be used. For traversing a HashTable either an iterator or Enumerator can be used. The iterator used for both HashMap and HashTable is fail-fast but the enumerator used with HashTable is fail-safe.
      • Performance wise HashMap is faster than the HashTable reason being HashMap is not synchronized.

      Refer Difference between HashMap and HashTable in Java to see in detail.

    64. HashMap Vs LinkedHashMap Vs TreeMap in Java.

      • HashMap makes no guarantees as to the order of the map.
        LinkedHashMap maintains the insertion order of the elements which means if we iterate a LinkedHashMap we'll get the keys in the order in which they were inserted in the Map.
        TreeMap stores objects in sorted order.
      • HashMap as well as LinkedHashMap allows one null as key, multiple values may be null though.
        TreeMap does not allow null as key.
      • HashMap stores elements in a bucket which actually is an index of the array.
        LinkedHashMap also uses the same internal implementation, it also maintains a doubly-linked list running through all of its entries.
        TreeMap is a Red-Black tree based NavigableMap implementation.
      • Performance wise HashMap provides constant time performance O(1) for get() and put() method.
        LinkedHashMap also provides constant time performance O(1) for get() and put() method but in general a little slower than the HashMap as it has to maintain a doubly linked list.
        TreeMap provides guaranteed log(n) time cost for the containsKey, get, put and remove operations.

      Refer HashMap Vs LinkedHashMap Vs TreeMap in Java to see in detail.

    65. Difference between Comparable and Comparator.

      Comparable Comparator
      Comparable interface is in java.lang package. Comparator interface is in java.util package.
      Comparable interface provides public int compareTo(T o); method which needs to be implemented for sorting the elements.
      This method compares this object with object o and returns an integer, if that integer is -
      • Positive - this object is greater than o.
      • Zero - this object is equal to o.
      • Negative - this object is less than o.
      Comparator interface provides int compare(T o1, T o2); method which needs to be implemented for sorting the elements. Here o1 and o2 objects are compared and an integer value is returned, if that integer is -
      • Positive - o1 is greater than o2.
      • Zero - o1 is equal to o2.
      • Negative - o1 is less than o2.
      The class which has to be sorted should implement the comparable interface (sorting logic is in the class which has to be sorted), and that implementation becomes the natural ordering of the class. Some other class can implement the Comparator interface not the actual class whose objects are to be sorted. That way there may be many comparators and depending on the ordering needed specific comparator can be used. As example for Employee class if different orderings are needed based on first name, last name, age etc. then we can have different comparators with the implementations for those orderings.
      To sort the list when Comparable is used we can use Collections.sort(List). To sort the list when Comparator is used, Comparator class has to be explicitly specified as a param in the sort method. Collections.sort(List, Comparator)

      Refer Difference between Comparable and Comparator to see in detail.

    66. How Does HashSet internally works in Java?

      HashSet internally uses HashMap to store it's elements. But it differs from HashMap on two points.

      • HashSet only stores unique values i.e. no duplicates are allowed.
      • In HashSet we have add(E e) method which takes just the element to be added as parameter not the (key, value) pair.

      Refer How HashSet works internally in Java to know more about the internal implementation of the HashSet.

    67. Which Set implementation should be used if you want the insertion order to be maintained?

      LinkedHashSet should be used in this case.

      Refer LinkedHashSet in Java to know more about LinkedHashSet in Java.

    68. What is LinkedHashSet?

      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.
      LinkedHashSet also stores unique elements just like other implemetations of the Set interface. How LinkedHashSet differs 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.

      Refer LinkedHashSet in Java to know more about LinkedHashSet in Java.

    69. Which Set implementation should be used if you want the elements to be stored in sorted order?

      TreeSet should be used in this case.

      Refer TreeSet in Java to know more about TreeSet in Java.

    70. What is TreeSet?

      TreeSet is also one of the implementation of the Set interface like HashSet and LinkedHashSet. TreeSet class implements the NavigableSet interface and extends the AbstractSet class.
      Just like other implementations of the Set interface HashSet and LinkedHashSet, TreeSet also stores unique elements. How TreeSet differs from other implementations is that elements in TreeSet are stored in sorted order. The elements are ordered using their natural ordering or a comparator can be provided at set creation time to provide custom ordering.
      One more point about TreeSet is, though HashSet and LinkedHashSet allow one null, TreeSet doesn't allow null as element.

      Refer TreeSet in Java to know more about TreeSet in Java.

    71. How to sort elements in different order (other than natural ordering) in TreeSet?

      By default elements are stored in TreeSet using natural ordering. If you want to sort using different order then you need to provide your own comparator at set creation time. If you have a TreeSet that stores Strings, then to sort the Strings in descending order rather than the natural ordering (which is ascending in case of String) you can write a comparator like this -

      class CityComparator implements Comparator<String>{
          @Override
          public int compare(String str1, String str2) {
              return str2.compareTo(str1);
          }    
      }
      
      This custom comparator has to be provided at the set creation time.
      Set<String> citySet = new TreeSet<String>(new CityComparator());
      

      Refer How to Sort elements in different order in TreeSet to see the detailed explanation of how to sort elements in different order in TreeSet.

    72. How can we sort HashSet in Java?

      Best way to sort a HashSet is to create a TreeSet using the given HashSet. That will automatically sort the elements as TreeSet is sorted.
      As Exp. - If there is a HashSet, citySet a TreeSet can be created using it like this -

      Set<String> sortedSet = new TreeSet<String>(citySet);
      

      Refer How to sort HashSet in Java to see the detailed explanation of how to sort HashSet in Java.

    73. What is EnumSet?

      EnumSet in Java is a specialized set implementation for use with enum types. All of the elements stored in an enum set must, explicitly or implicitly, come from a single enum type that is specified while creating the set. EnumSet was introduced in Java 5 along with the Enum.
      One of the things to note about EnumSet is that it is an abstract class and uses factory methods to create objects. There are two concrete implementations of EnumSet -

      • RegularEnumSet
      • JumboEnumSet

      Refer EnumSet in Java to read more about EnumSet in Java.

    74. HashSet Vs LinkedHashSet Vs TreeSet in Java

      • HashSet is unordered, it will store elements on the basis of the calculated hash that's it.
        LinkedHashSet maintains the insertion order of the elements.
        TreeSet keeps the element in sorted order. The sorting order,s TreeSet follows by default is known as the natural ordering of the elements.
      • HashSet as well as LinkedHashSet allow null value to be stored. Mind you only one null value is allowed in both HashSet and LinkedHashSet.
        TreeSet does not allow null value, trying to add null to a TreeSet will result in a null pointer exception.
      • For HashSet and LinkedHashSet comparison of the elements is done using equals() method. Note that set allows only unique elements, and that uniqueness is maintained by using the equals() method to compare elements.
        TreeSet does the comparison of the element using the compareTo (or compare) method, depending on whether sorting is done using Comparable or Comparator.
      • Performance wise HashSet is at the top as it has no added baggage of insertion ordering or sorting. If hashing is done correctly HashSet offers constant time performance O(1) for the basic operations (add, remove, contains and size).
        For LinkedHashSet performance is likely to be just slightly below that of HashSet, due to the added expense of maintaining the linked list.
        TreeSet has to sort elements with every insertion so that way performance is slow, but TreeSet provides guaranteed log(n) time cost for the basic operations (add, remove and contains) irrespective of the number of elements stored.

      Refer HashSet Vs LinkedHashSet Vs TreeSet in Java to read about differences in detail.

    Related Topics

    1. Java OOP interview questions
    2. Core Java basics interview questions
    3. Java String interview questions
    4. Java Exception Handling interview questions
    5. Java Multi-threading interview questions
    6. Java Concurrency interview questions