Skip to content

java

Strategy pattern

With this post I’m starting series of articles dedicated to GoF design patterns. GoF stands for Gang of Four – four authors that wrote a famous book about design patterns.

So the first pattern I want to describe is Strategy. It allows to choose the behaviour of instances at runtime by defining appropriate strategy.

Let’s see an example. Supposing we have a class Order, which has getTotal() method, that returns total cost of Items in this order:

 

public int getTotal() {
	int total = 0;
		
	for (Item item : items) {
		total += item.getPrice();
	}
		
	return total;
}

 

Very simple, isn’t it? But what if we want to change the price depending on some circumstances? That’s where we can use the Strategy pattern. Click read more to see full example.

Read More →

Programming competition and a small Java task

Last week we had a programming competition at work which consisted of some small tasks. One of them was to check, if we can make a given string palindrome by adding one letter in any place. Shame on me, I didn’t manage with this task in time. However I got the third place in this competition. 🏆😁

So the task:
Your app should check, if it’s possible to make a palindrome by adding a lowercase English letter to a given string in any position. If it is, the application should return an index which points to where to put a character, otherwise the app should return -1.
The given string contains only lowercase Latin characters.

What is a palindrome? Palindrome is a word or a number, which reads the same backward and forward. For example:

  • Was it a car or a cat I saw?
  • 1234321
  • Step on no pets

See the solution.

Read More →

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 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 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

What benefits does JCF provide?

JCF provides the following benefits:

  • Reduces programming effort: you don’t need to invent the wheel anymore, JCF provides useful data structures and algorithms.
  • Increases program speed and quality: JCF provides high-performance, high-quality implementations of useful data structures and algorithms. Programs can be easily tuned by switching collection implementation. It is possible because interface implementations are interchangeable. When you use the Collections Framework you don’t need to waste time by writing your own data structures, so you’ll have more time to write and improve your business logic.
  • Allows interoperability among unrelated APIs: you can use collections in different applications and be sure that it will work fine. You can exchange your collections between applications seamlessly.
  • Reduces effort to learn and to use new APIs: many APIs take collections on input and return them as output. In the past, each API could implement its own collections and you needed to learn it. Now we have a universal solution – JCF.
  • Reduces effort to design new APIs: this is the reverse side of the previous benefit. A programmer don’t have to invent and to implement his own collections.
  • Fosters software reuse: if you implement your own collection with a JCF interface, you will get a reusable code. You can use collections utilities on your implementation as well.