How can I insert an element in array at a given position?

As we know an array in Java is a fixed-size object, once it created its size cannot be changed. So if you want to have a resizable array-like object where you can insert an element at a given position you can use a java.util.List object type instead.

This example will show you how you can achieve array insert using the java.uti.List and java.util.ArrayList object. Let see the code snippet below.

In the code snippet above the original array of Integer numbers will be converted into a List, in this case we use an ArrayList, by adding all elements of the array into the list using the List.addAll() method. The Arrays.asList() can be use to convert an array into a collection type object.

Next we insert a new element into the List using the add(int index, E element) method. Where index is the insert / add position and element is the element to be inserted. After the new element inserted we convert the List back to the original array.

Below is the result of the code snippet above:

How to use Preferences API to store program configurations?

The Preferences API provided in the java.util.prefs package can be use to store and retrieve application configurations. The main class is the Preferences class. Using this class you can manage the preference data such as storing, retrieving, removing and clearing the preference data.

Preferences are key-value pairs of data. You can stored a string, int, boolean and other primitive data type. You can use the get() method to retrieve value associated with a key from preference node and the put() method to store a value associated with a key in the preference node. To remove a value associated with a key from preference node you can use the remove() method. And if you want to clear the keys from the preference node you can use the clear() method.

The actual storage of these preference data is dependent on the platform. For example in Windows OSes it stored in the Windows Registry. What you have to know that this Preferences API is not intended to use for storing application data, you will only use it to store configurations of your applications.

Let’s see an example of using the Preferences API.

Here are the output you’ll get when running the example above:

How to get random key-value pair from Hashtable?