Immutable Objects in Java

An object is considered immutable if its state cannot change after it is constructed. Maximum reliance on immutable objects is widely accepted as a sound strategy for creating simple, reliable code Creating an immutable version of a type using defensive copying Some basic types and classes in Java are fundamentally mutable. For example, all array types are mutable, and so are … Read more

Immutable Class in Java

Immutable objects are instances whose state doesn’t change after it has been initialized. For example, String is an immutable class, and once instantiated its value never changes. Example without mutable refs public final class Color { final private int red; final private int green; final private int blue; private void check(int red, int green, int … Read more

Compile time processing using annotation processor

This article is an intro to Java source-level annotation processor and provides examples of using this technique for generating additional source files during compilation. This example demonstrates how to do compile time checking of an annotated element. The annotation The @Setter annotation is a marker can be applied to methods. The annotation will be discarded during compilation … Read more

Annotations in Java

In Java, an annotation is a form of syntactic metadata that can be added to Java source code. It provides data about a program that is not part of the program itself. Annotations have no direct effect on the operation of the code they annotate. Classes, methods, variables, parameters and packages are allowed to be … Read more

Constructors in Java

While not required, constructors in Java are methods recognized by the compiler to instantiate specific values for the class which may be essential to the role of the object. This topic demonstrates proper usage of Java class constructors. Default Constructor The “default” for constructors is that they do not have any arguments. In case you … Read more

Operators in Java

Operators in Java programming language are special symbols that perform specific operations on one, two, or three operands, and then return a result. The Increment/Decrement Operators (++/–) Variables can be incremented or decremented by 1 using the ++ and — operators, respectively. When the ++ and — operators follow variables, they are called post-increment and … Read more

Iterating through the contents of a Map

Maps provide methods which let you access the keys, values, or key-value pairs of the map as collections. Iterating through the contents of a Map. You can iterate through these collections. Given the following map for example: Map repMap = new HashMap<>();repMap.put(“Jon Skeet”, 927_654);repMap.put(“BalusC”, 708_826);repMap.put(“Darin Dimitrov”, 715_567); Iterating through map keys: for (String key : … Read more

Maps in Java

The java.util.Map interface represents a mapping between keys and their values. A maps cannot contain duplicate keys; and each key can maps to at most one value. Since Maps is an interface, then you need to instantiate a concrete implementation of that interface in order to use it; there are several Maps implementations, and mostly … Read more

Making a list unmodifiable

The list unmodifiable method is used to returns an unmodifiable view of the specified list. The Collections class provides a way to make a list unmodifiable: List ls = new ArrayList();List unmodifiableList = Collections.unmodifiableList(ls); If you want an unmodifiable list with one item you can use: List unmodifiableList = Collections.singletonList(“Only string in the list”); Moving objects around … Read more

Lists in Java with Examples

A list is an ordered collection of values. In Java, lists are part of the Java Collections Framework. Lists implement the java.util.List interface, which extends java.util.Collection. Sorting a generic list The Collections class offers two standard static methods to sort a list: sort(List list) applicable to lists where T extends Comparable, and sort(List list, Comparator … Read more

Immutable Empty Collections and iterators in Java with Examples

Sometimes it is appropriate to use an immutable empty collection. There are several ways to create immutable empty List in Java. The Immutable Empty Collections class provides methods to get such collections in an efficient way: List anEmptyList = Collections.emptyList(); Map anEmptyMap = Collections.emptyMap(); Set anEmptySet = Collections.emptySet(); These methods are generic and will automatically … Read more

Collections in Java

The collections framework in java.util provides a number of generic classes for sets of data with functionality that can’t be provided by regular arrays. Collections framework contains interfaces for Collection, with main sub-interfaces List and Set, and mapping collection Map. Collections are the root interface and are being implemented by many other collection frameworks. Removing … Read more

Array Covariance

Object arrays are covariant, which means that just as Integer is a subclass of Number, Integer[] is a subclass of Number[]. This may seem intuitive, but can result in surprising behavior: Integer[] integerArray = {1, 2, 3}; Number[] numberArray = integerArray; // valid Number firstElement = numberArray[0]; // valid numberArray[0] = 4L; // throws ArrayStoreException … Read more

Java Arrays

Creating a List from an Array The Arrays.asList() method can be used to return a fixed-size list containing the elements of the given array.. The resulting List will be of the same parameter type as the base type of the array. String[] stringArray = {“foo”, “bar”, “baz”};List stringList = Arrays.asList(stringArray); Note: This list is backed … Read more

Enums with constructors

Enums with Constructors

An enum cannot have a public constructor; however, private constructors are acceptable (constructors for enums are package-private by default): public enum Coin { PENNY(1), NICKEL(5), DIME(10), QUARTER(25); // usual names for US coins // note that the above parentheses and the constructor arguments match private int value; Coin(int value) { this.value = value; } public … Read more