Skip to content

Monthly Archives: March 2016

Java task. Fibonacci sequence.

Fibonacci numbers are a number sequence, where first two numbers are 1 and 1 or 0 and 1. Each subsequent number is the sum of previous two numbers. This task is often asked by interviewers (not only in Java). Let’s solve it in two ways: using a loop and recursion.

public int getFibonacci(int number) {
    if (number == 1 || number == 2) {
        return 1;
    int fibo1 = 1;
    int fibo2 = 1;
    int fibonacci = 1;
    for (int i = 3; i <= number; i++) {
        fibonacci = fibo1 + fibo2;
        fibo1 = fibo2;
        fibo2 = fibonacci;

    return fibonacci;

To see a recursive solution of this task, click “read more”.

Read More →

What is a diamond operator?

Diamond operator Java
Diamond operator Java

This is an improvement appeared in Java 7.
Consider you have a class with a long name and you need to create a HashMap of Strings and Lists of your class instances. You code will look like this:

Map<String, List<MyClassWithLongLongName>> myMap = new HashMap<String, List<MyClassWithLongLongName>>();

In Java 7 you can write less code using the diamond operator(<>):

Map<String, List<MyClassWithLongLongName>> myMap = new HashMap<>();

Describing the Java Map collection. Difference between other collections.

Map is a collection that stores key-value pairs. A map cannot contain duplicate keys.

What is the main difference between Map and other collections?

The main difference between Map and other collections is that it contains key and value. It doesn’t inherit from Collection interface.

The Map interface includes methods for basic operations (put, get, remove, containsKey, containsValue, size, empty), bulk operations (putAll, clear) and collection views (such as keySet, entrySet and values).

The general-purpose implementations are: HashMap, TreeMap and LinkedHashMap.

HashMap which is the best-performing implementation, stores its elements in a hash table. HashMap doesn’t care about ordering elements. If you need to order your elements in some order (for example, ascending, descending, etc), use TreeMap, which stores its elements in a red-black tree and uses comparators. However, if you want to store your key-value pairs in order they were inserted, consider using LinkedHashMap.

Describing the Java Deque collection interface

A Deque is a double-ended-queue. It is a collection of elements that supports the insertion and removal of elements at both end points. It implements both Stack and Queue at the same time. This interface defines following methods:

  • void addFirst(E e)
  • void addLast(E e)
  • boolean offerFirst(E e)
  • boolean offerLast(E e)
  • E removeFirst()
  • E removeLast()
  • E pollFirst()
  • E pollLast()
  • E getFirst()
  • E getLast()
  • E peekFirst()
  • E peekLast()
  • boolean removeFirstOccurence(Object o)
  • boolean removeLastOccurence(Object o)
  • + methods from Queue interface

Read More →

Describing the Java Queue collection interface

A Queue is a collection for holding elements prior to processing. It provides additional insertion, removal and inspection operations:

  • E element()
  • boolean offer(E e)
  • E peek()
  • E poll()
  • E remove()

The general-purpose implementation of Queue is LinkedList.

Each Queue method exists in two forms: one throws an exception when fails, and the other returns a special value when fails (null or false, depending on return type).
Methods that will throw an exception: add, element, remove.
Methods that will return a special value: offer, peek, poll.

Queues typically (but not necessarily) order elements in a FIFO manner, which stands for First In – First Out. In this case all new elements are inserted at the tail of the queue. Other kinds of queues may use different insertion rules.
If we need to control elements ordering we can use PriorityQueue that stores the elements in natural order or uses Comparator or Comparable to define the right order.

Describing the Java Set collection interface

A Set is a Collection that cannot contain duplicates. The Set interface extends Collection interface but has no specific methods. It adds the restriction that duplicates are prohibited. This interface also adds a stronger contract on the behavior of the equals and the hashcode methods, allowing Set instances to be compared meaningfully even if their implementation types differ. The two Set instances are equal if they contain the same elements.

JCF contains three general-purpose Set implementations: HashSet, LinkedHashSet and TreeSet. They are all based on HashMap, LinkedHashMap and TreeMap correspondly. When you add an element, it stores as a “key” of inner Map, and the value is always a dummy object.

HashSet which is the best-performing implementation, stores its elements in a hash table. HashSet doesn’t care about ordering elements. If you need to order your elements, consider using use TreeSet, which stores its elements in a red-black tree and uses comparators. However, if you want to store your elements in order they were inserted, consider using LinkedHashSet.

Describing the Java List collection interface

List is an ordered collection that can contain duplicates. In addition to the Collection interface methods, the List interface includes the following:

  • Positional access: manipulating the elements by their index in the list. This includes methods such as: get, set, add, addAll, remove.
  • Search: methods indexOf and lastIndexOf search for a specified object in the list and return its index.
  • Iteration: extends Iterator semantics to take advantage of the list’s sequential nature. With ListIterator you can traverse the list in either direction, modify list during iteration and obtain the current position of the iterator. The listIterator methods provide this behavior.
  • Range-view: the sublist method returns a sublist with a specified range of elements.

There are two general-purpose List implementations: ArrayList, which is based on an array, and which is usually the better-performing, and LinkedList, which offers better performance under certain circumstances.

What data can be stored in a collection?

You can store anything but primitives. To store primitives consider using wrappers (Integer for int, Double for double, etc…).
For example, you can store your own classes:

List<MyClass> myClassObjects = new LinkedList<MyClass>();

To store primitives:

Set<Integer> ints = new TreeSet<Integer>();

Notice, that you can add primitives, since it will be wrapped automatically:

ints.add(1); // Correct