Collections Java Interview Questions – Set 01

Can you write code to sort the following string values naturally (i.e. in alphabetical order)? (JEE, Java, Servlets, JMS, JNDI, JDBC, JSP, and EJB)

Here is the sample code that makes use of the default compareTo( ) provided in the String class as it implements the Comparable interface and the Collections utility class that provides a sorting method, which internally uses the efficient “merge sort” algorithm.

import java.util.Arrays;

import java.util.Collections;

import java.util.List;

public class Sort1 {

public static void main(String[] args) {

List<string> values = Arrays.asList(“JEE”, “Java”, “Servlets”, “JMS”, “JNDI”, “JDBC”, “JSP”, “EJB”);

Collections.sort(values); // uses the default compareTo(String anotherString)  in the String class

System.out.println(values);

}

}

Output:

[EJB, JDBC, JEE, JMS, JNDI, JSP, Java, Servlets]

How can a collection object be sorted?

// Sort

Collections.sort(list);

// Sort case-insensitive

Collections.sort(list, String.CASE_INSENSITIVE_ORDER);

// SortReverse-order

Collections.sort(list, Collections.reverseOrder ());

// Reverse-order sort case-insensitive

Define local, member and a class variable.

Within a method variables declared are called “local” variables.

Variables declared in the class i.e not in any methods are “member” variables (global variables).

Variables declared in the class i.e not in any methods and are called as “static” are class variables.

Name the different identifier states of a Thread.

Different types of identifiers of a Thread are:

R – Running or runnable thread

S – Suspended thread

CW – Thread waiting on a condition variable

MW – Thread waiting on a monitor lock

MS – Thread suspended waiting on a monitor lock

Define Vector class? Differentiate the Vector and ArrayList.

Vector canbe said a legacy class which has been introduced to implement the List interface since Java 2 platform v1.2

Vector is always synchronized but ArrayList is not.

When Vector class is synchronized, if we will run in multithreading environment we’ve to use ArrayList with Collections.

Vector has a default size i.e 10 while arrayList has no default size.

ArraayList is not having any method returning Enumerations where as vector list is having.

Differentiate between Enumeration and Iterator interface

In java.util package the Enumeration and Iterator are available.

The Enumeration interface is replicated by the Iterator interface.

In preference to Enumeration new implementations should consider using Iterator .

The difference of Iterators from enumerations are:

  • Enumeration has 2 methods namely hasMoreElements() & nextElement() where the Iterator contained three methods namely hasNext(), next(),remove().
  • An optional remove operation is added in Iterator,and has shorter method names. We Use remove() to delete the objects but the Enumeration interface does not support this feature.
  • The legacy classes use Enumeration interface .Vector.elements() & Hashtable.elements() method results Enumeration.
  • All Java Collections Framework classes returns iterator. java.util.Collection.iterator() method returning an instance of Iterator.

Collections.sort(list, String.CASE_INSENSITIVE_ORDER);

Collections.reverse(list);

Is there anything wrong with the above code?

Yes, 2 things — firstly, the above sort is case sensitive, that is the uppercase takes priority over lowercase pushing ‘Java’ after ‘JSP’. Secondly, if the collection had any null values, it will throw a NullpointerException.

These two issues can be rectified by providing a custom sorting implementation that ignores case and handles null values by pushing them to the end. The Collections class’s sort method takes a Comparator implementation as a second argument. In the code below, the Comparator has been implemented as an anonymous inner class. The compare(…) method will be called a number of times by the Collections.sort(list, comparator).

import java.util.Arrays;

import java.util.Collections;

import java.util.Comparator;

import java.util.List;

public class Sort2 {

public static void main(String[] args) {

List<String> values = Arrays.asList(“JEE”, “Java”, null,  “Servlets”, null, “JMS”, “JNDI”, “JDBC”, “JSP”, null,”EJB”);

//The comparator is defined as an anonymous inner class, but it can be

//defined in its own class. Handles nulls and ignores case

Collections.sort(values, new Comparator<String>() {

@Override

public int compare(String o1, String o2) {

//push the null values to the end

if(o1 == null){

if(o2 == null) {

return 0;

}

return 1;

}

else if(o2 == null){

return -1;

}

return o1.compareToIgnoreCase(o2);

}

}); // anonymous inner class end

System.out.println(values);

}

}

What is Hashmap & Hashtable with example?

Hashtabel is original collection classes in java which was introduced as version 1.2 that HashMap permits null values in it, while Hashtable doesn’t.

Now, what if you have your own custom class like a Dog, Cat, etc instead of a library class like String, Integer, etc?

Here is an example of a JavaTechnology custom object that implements a default sorting logic based on the rank (i.e popularity).public class JavaTechnology implements Comparable<JavaTechnology>{

private String name;

private int rank;   // popularity lower value means more popular

public JavaTechnology(String name, int rank){

this.name = name;

this.rank = rank;

}

//default implementation by rank alone

@Override

public int compareTo(JavaTechnology technology) {

int rank1 = this.rank;

int rank2 = technology.rank;

if (rank1 > rank2){

return +1;

}else if (rank1 < rank2){

return -1;

}else{

return 0;

}

}

//required for printing, displaying, etc.

@Override

public String toString() {

return “(” + name + ” , ” + rank + “)”;

}

}

Now, a simple test class

import java.util.Arrays;

import java.util.Collections;

import java.util.List;

public class Sort3Test {

public static void main(String[] args) {

JavaTechnology jt1 = new JavaTechnology(“JEE”, 1);

JavaTechnology jt2 = new JavaTechnology(“Java”, 1);

JavaTechnology jt3 = new JavaTechnology(“Servlets”, 2);

JavaTechnology jt4 = new JavaTechnology(“JSP”, 2);

JavaTechnology jt5 = new JavaTechnology(“JNDI”, 3);

JavaTechnology jt6 = new JavaTechnology(“EJB”, 4);

JavaTechnology jt7 = new JavaTechnology(“JMS”, 5);

List<javatechnology> values = Arrays.asList(jt1, jt2, jt3, jt4, jt5, jt6, jt7);

Collections.sort(values); // invokes the compareTo(…) method in JavaTechnology a number of times

System.out.println(values);

}

}

Output:

[(JEE , 1), (Java , 1), (Servlets , 2), (JSP , 2), (JNDI , 3), (EJB , 4), (JMS , 5)]

What if you have a specific scenario where you want to first sort by rank and then alphabetically if the ranks are same?

Any number of Comparator classes can be created to sort them differently as shown below.

import java.util.Comparator;

public class JavaTechnologyComparator implements Comparator<JavaTechnology> {

@Override

public int compare(JavaTechnology t1, JavaTechnology t2) {

//handle null values here

Integer rank1 = t1.getRank();

Integer rank2 = t2.getRank();

int rankVal = rank1.compareTo(rank2);

int nameVal = t1.getName().toLowerCase().compareTo(t2.getName().toLowerCase());

//if same rank, then sort by name

if(rankVal == 0){

return nameVal;

}

//else sort by rank

return rankVal ;

}

}

Now, the Sort3Test class has been slightly modified to use a Comparator.

import java.util.Collections;

import java.util.List;

public class Sort3Test {

public static void main(String[] args) {

JavaTechnology jt1 = new JavaTechnology(“JEE”, 1);

JavaTechnology jt2 = new JavaTechnology(“Java”, 1);

JavaTechnology jt3 = new JavaTechnology(“Servlets”, 2);

JavaTechnology jt4 = new JavaTechnology(“JSP”, 2);

JavaTechnology jt5 = new JavaTechnology(“JNDI”, 3);

JavaTechnology jt6 = new JavaTechnology(“EJB”, 4);

JavaTechnology jt7 = new JavaTechnology(“JMS”, 5);

List<JavaTechnology> values = Arrays.asList(jt1, jt2, jt3, jt4, jt5, jt6, jt7);

Collections.sort(values, new JavaTechnologyComparator());

// invokes the compare(…) in JavaTechnologyComparator

// a number of times

System.out.println(values);

}

}

The output will be:

[(Java , 1), (JEE , 1), (JSP , 2), (Servlets , 2), (JNDI , 3), (EJB , 4), (JMS , 5)]

This should now enable you to sort any Java objects.

What is RMI and how it is useful?

Remote method invocation is called RMI.

One can work with remote object using RMI.

It gives a impression that you are working with a object that resides within your own JVM though it is somewhere.

The protocol used by RMI is RMI-IIOP

Define a Collection API.

The set of classes and interfaces supporting the operation on collections of objects is the Collection API.

Than the vectors, arrays, and hashtables if effectively replaces,these classes and interfaces are more flexible, more powerful, and more regular

class examples: HashSet, TreeMap, ArrayList, LinkedList,HashMap and TreeMap.

interface examples: Set,List ,Collection and Map.

How many forms of Polymorphism are there?

polymorphism exists in three different forms in Java:

  • Method overloading
  • Method overriding through inheritance
  • Method overriding through the Java interface

Define the wrapper classes in Java and name a few.

Wrapper class is wraps around the primitive data type. List of the primitive types and the corresponding wrapper classes:

Primitive Wrapper

boolean java.lang.Boolean

byte java.lang.Byte

char java.lang.Character

double java.lang.Double

float java.lang.Float

int java.lang.Integer

long java.lang.Long

short java.lang.Short

void java.lang.Void

Differentiate between JDK ,JRE & JVM

JDK stands for Java Development Kit. It is the most widely used Java Software Development Kit.

JRE stands for Java Runtime Environment. It is an implementation of the Java Virtual Machine which executes Java programs

JVM stands for Java Virtual Machine. It is an interpreter.

What is the Collection interface

The Collection interface provides support for the implementation of a mathematical bag – an unordered collection of objects that may contain duplicates.

What is immutable object in Java? Can you change values of a immutable object?

A Java object is considered immutable when its state cannot change after it is created. Use of immutable objects is widely accepted as a sound strategy for creating simple, reliable code. Immutable objects are particularly useful in concurrent applications. Since they cannot change state, they cannot be corrupted by thread interference or observed in an inconsistent state. java.lang.String and java.lang.Integer classes are the Examples of immutable objects from the Java Development Kit. Immutable objects simplify your program due to following characteristics :

  • Immutable objects are simple to use test and construct.
  • Immutable objects are automatically thread-safe.
  • Immutable objects do not require a copy constructor.
  • Immutable objects do not require an implementation of clone.
  • Immutable objects allow hashCode to use lazy initialization, and to cache its return value.
  • Immutable objects do not need to be copied defensively when used as a field.
  • Immutable objects are good Map keys and Set elements (Since state of these objects must not change while stored in a collection).
  • Immutable objects have their class invariant established once upon construction, and it never needs to be checked again.

Immutable objects always have “failure atomicity” (a term used by Joshua Bloch) if an immutable object throws an exception, it’s never left in an undesirable or indeterminate state

Can you explain the core collection interfaces?

There are six interfaces and come under two different inheritance group one which comes under the collection interface root and the other in the map interface root.

Collection

It’s the base of all collection classes. It provides a unified way to manipulate collection objects. Collection has group of object called as elements. These elements can be accessed and manipulated using Iterator. List

In List interface the elements are arranged sequentially. Elements can be inserted in to any location and you can also insert duplicate elements. In order to access the elements you need to use the “ListIterator”. Using “ListIterator” you can move back and forth which makes it unique as compared to other iterators.

Set

It represents a collection but no duplicates are allowed in this case.

SortedSet

It extends the Set interface and sorts the set in ascending order.

Map

Map stores association between keys and value pairs. So given a key you can easily find the value. One thing important to note is they do not implement iterable interface. But yes you can obtain a collection view of the map which allows you loop using for loop.

SortedMap

It extends Map so that the keys are maintained in ascending order.