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.util.List and java.util.ArrayList object. Let see the code snippet below.

package org.kodejava.example.util;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ArrayInsert {
    public static void main(String[] args) {
        // Creates an array of integer value and prints the 
        // original values.
        Integer[] numbers = new Integer[]{1, 2, 3, 8, 13, 21};
        System.out.println("Original numbers: " + 
                Arrays.toString(numbers));

        // Creates an ArrayList object and add the entire content
        // of numbers array into the list. We use the 
        // add(index, element) method to add element=5 at index=3.
        List<Integer> list = new ArrayList<>();
        list.addAll(Arrays.asList(numbers));
        list.add(3, 5);

        // Converts back the list into array object and prints 
        // the new values.
        numbers = list.toArray(new Integer[list.size()]);
        System.out.println("After insert    : " + Arrays.toString(numbers));
    }
}

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:

Original numbers: [1, 2, 3, 8, 13, 21]
After insert    : [1, 2, 3, 5, 8, 13, 21]

How do I create a List in iText?

You can create a list in iText using the com.itextpdf.text.List. This class represent a list. The list item is created using the com.itextpdf.text.ListItem. You can create an ordered list or unordered list. To create ordered list pass the List.ORDERED as the parameter to class List. To create an unordered list pass the List.UNORDERED.

Let’s see an example below:

package org.kodejava.example.itextpdf;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.List;
import com.itextpdf.text.ListItem;
import com.itextpdf.text.pdf.PdfWriter;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;

public class PDFListDemo {
    public static void main(String[] args) {
        Document document = new Document();
        try {
            PdfWriter.getInstance(document,
                    new FileOutputStream("PDFListDemo.pdf"));
            document.open();

            List ordered = new List(List.ORDERED);
            ordered.add(new ListItem("Item 1"));
            ordered.add(new ListItem("Item 2"));
            ordered.add(new ListItem("Item 3"));
            document.add(ordered);

            List unordered = new List(List.UNORDERED);
            unordered.add(new ListItem("Item 1"));
            unordered.add(new ListItem("Item 2"));
            unordered.add(new ListItem("Item 3"));
            document.add(unordered);
        } catch (DocumentException | FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            document.close();
        }
    }
}

Maven Dependencies

<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.9</version>
</dependency>

How do I Convert Array to Collection?

package org.kodejava.example.util;

import java.util.Arrays;
import java.util.List;

public class ArrayToListExample {
    public static void main(String[] args) {
        // Creates an array of object, in this case we create an
        // Integer array.
        Integer[] numbers = {1, 1, 2, 3, 5, 8, 13, 21, 34, 55};

        // Convert the created array above to collection, in this
        // example we convert it to a List.
        List list = Arrays.asList(numbers);

        // We've got a list of our array here and iterate it.
        for (int i = 0; i < list.size(); i++) {
            System.out.print(list.get(i) + ", ");
        }
    }
}

How do I convert a collection object into an array?

To convert collection-based data into array we can use toArray() or toArray(T[] a) method provided by the implementation of Collection interface such as java.util.ArrayList.

package org.kodejava.example.util;

import java.util.List;
import java.util.ArrayList;

public class CollectionToArrayExample {
    public static void main(String[] args) {
        List<String> words = new ArrayList<>();
        words.add("Kode");
        words.add("Java");
        words.add("Sample");
        words.add("Code");

        String[] array = words.toArray(new String[words.size()]);
        for (String word : array) {
            System.out.println(word);
        }
    }
}

Our sample code result is shown below:

Kode
Java
Sample
Code

How do I convert an array into a collection object?

To convert array based data into List / Collection based we can use java.util.Arrays class. This class provide a static method asList(T... a) that converts array into List / Collection.

package org.kodejava.example.util;

import java.util.Arrays;
import java.util.List;

public class ArraysExample {
    public static void main(String[] args) {
        String[] words = {"Happy", "New", "Year", "2006"};
        List<String> list = Arrays.asList(words);

        for (String word : list) {
            System.out.println(word);
        }
    }
}

The results of our code are:

Happy
New
Year
2006

How do I know if an ArrayList contains a specified item?

In this example you are going to learn how to find out if a List or ArrayList object has a specified element. To check if an ArrayList object contains a specified element we can use the contains() method. This method returns a boolean true when the specified element is found in the ArrayList, if not it will returns false.

package org.kodejava.example.util;

import java.util.ArrayList;
import java.util.List;

public class ArrayListContainsExample {
    private List<String> list = new ArrayList<>();

    public ArrayListContainsExample() {
        list.add("Item 1");
        list.add("Item 2");
        list.add("Item 3");
        list.add("Item 4");
    }

    public static void main(String[] args) {
        ArrayListContainsExample demo = new ArrayListContainsExample();

        // Check to see if the list contains "Item 1".
        String itemToFind = "Item 1";
        demo.findItemInTheList(itemToFind);

        // Check to see if the list contains "Item 20".
        itemToFind = "Item 20";
        demo.findItemInTheList(itemToFind);
    }

    private void findItemInTheList(String itemToFind) {
        if (list.contains(itemToFind)) {
            System.out.println(itemToFind + " was found in the list");
        } else {
            System.out.println(itemToFind + " was not found in the list");
        }
    }
}

The output of the code snippet above are:

Item 1 was found in the list
Item 20 was not found in the list

How do I know the size of ArrayList?

In this example we are going to learn how to obtain the size of an ArrayList object. As you might already know, an java.util.ArrayList is a class that can be use to create a dynamic size array. We can add and remove elements from the ArrayList dynamically.

Because its elements can be add or remove at anytime, we might want to know the number of elements currently stored in this list. To obtain the size we can use the size() method. This method returns an int value that tells us the number of elements stored in the ArrayList object.

When the list contains more than Integer.MAX_VALUE elements this method returns Integer.MAX_VALUE.

package org.kodejava.example.util;

import java.util.ArrayList;
import java.util.List;

public class ArrayListSize {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("Item 1");
        list.add("Item 2");
        list.add("Item 3");

        int size = list.size();
        System.out.println("List size = " + size);
    }
}

In the code snippet above we start creating an instance of ArrayList that can holds String values. As a good practice we should always use the interface as the type of the declared object, in this case we use the List interface. The <> is a diamond operator, started from JDK 7 you can use this operator so that you don’t need to repeat the generic type twice between the declaration and instantiation.

After we create the ArrayList object and add string elements to the list object, we get the size of the list by calling the size() method. We store the result in the size variable and print out its value. If you compile an run the code above you will get the following output:

List size = 3

How do I use ArrayList class?

In this example we will learn how to use the java.util.ArrayList class. An ArrayList is part of the Java Collection Framework. By using this class we can create a dynamic size array of data, which means we can add or remove elements from the array dynamically.

In the code below we will see the demonstration on how to create an instance of ArrayList, add some elements, remove elements and iterate through the entire ArrayList elements either using a for-loop or using the for-each syntax.

We can also see how to convert the ArrayList into an array object using the toArray() method. And we use the Arrays.toString() utility method when we want to print the content of an array.

When creating a class instance it is a good practice to use the interface as the type of variable instead of the concrete type directly. This can make us easily update our code if we don’t want to use ArrayList anymore sometime in the future.

And here is the code snippet:

package org.kodejava.example.util;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ArrayListExample {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();

        // Add items into ArrayList
        list.add("Item 1");
        list.add("Item 2");
        list.add("Item 3");

        // Remove the third item from ArrayList, first index = 0
        list.remove(2);

        // Iterate ArrayList item using for loop statement
        for (int i = 0; i < list.size(); i++) {
            String item = list.get(i);
            System.out.println("Item = " + item);
        }

        // Iterate ArrayList item using for-each statement
        for (String item : list) {
            System.out.println("Item = " + item);
        }

        // Convert ArrayList into array of object
        String[] array = list.toArray(new String[list.size()]);
        System.out.println("Items = " + Arrays.toString(array));
    }
}

Executing the program will give us the following output printed in our console.

Item = Item 1
Item = Item 2
Item = Item 1
Item = Item 2
Items = [Item 1, Item 2]