How do I get the component type of array?

The Class.getComponentType() method call returns the Class representing the component type of array. If this class does not represent an array class this method returns null reference instead.

package org.kodejava.lang.reflect;

public class ComponentTypeDemo {
    public static void main(String[] args) {
        String[] words = {"and", "the"};
        int[][] matrix = {{1, 1}, {2, 1}};
        Double number = 10.0;

        Class<?> clazz = words.getClass();
        Class<?> cls = matrix.getClass();
        Class<?> clz = number.getClass();

        // Gets the type of array component.
        Class<?> type = clazz.getComponentType();
        System.out.println("Words type: " +
                type.getCanonicalName());

        // Gets the type of array component.
        Class<?> matrixType = cls.getComponentType();
        System.out.println("Matrix type: " +
                matrixType.getCanonicalName());

        // It will return null if the class doesn't represent
        // an array.
        Class<?> numberType = clz.getComponentType();
        if (numberType != null) {
            System.out.println("Number type: " +
                    numberType.getCanonicalName());
        } else {
            System.out.println(number.getClass().getName() +
                    " class is not an array");
        }
    }
}

This program print the following output:

Words type: java.lang.String
Matrix type: int[]
java.lang.Double class is not an array

How do I determine if a class object represents an array class?

For checking if a class object is representing an array class we can use the isArray() method call of the Class object. This method returns true if the checked object represents an array class and false otherwise.

package org.kodejava.lang.reflect;

public class IsArrayDemo {
    public static void main(String[] args) {
        int[][] matrix = {{1, 1}, {2, 1}};
        Class<?> clazz = matrix.getClass();

        // Check if the class object represents an array class
        if (clazz.isArray()) {
            System.out.println(clazz.getSimpleName() +
                    " is an array class.");
        } else {
            System.out.println(clazz.getSimpleName() +
                    " is not an array class.");
        }
    }
}

How do I convert a java.util.Vector into an array?

This example demonstrates how to convert a Vector object into an array. You can use the Vector.copyInto(Object[] array) method to create a copy of the Vector object in array form.

package org.kodejava.util;

import java.util.Vector;

public class VectorToArray {
    public static void main(String[] args) {
        Vector<Integer> vector = new Vector<>();
        vector.add(10);
        vector.add(20);
        vector.add(30);
        vector.add(40);
        vector.add(50);

        // Declares and initializes an Integer array.
        Integer[] numbers = new Integer[vector.size()];

        // Copies the components of this vector into the specified
        // array of Integer
        vector.copyInto(numbers);

        for (Integer number : numbers) {
            System.out.println("Number: " + number);
        }
    }
} 

The result of the code snippet above:

Number: 10
Number: 20
Number: 30
Number: 40
Number: 50

How do I convert array into JSON?

In the example below you can see how to convert an array into JSON string. We serialize the array to JSON using the Gson.toJson() method. To deserialize a string of JSON into array we use the Gson.fromJson() method.

package org.kodejava.gson;

import com.google.gson.Gson;

public class ArrayToJson {
    public static void main(String[] args) {
        int[] numbers = {1, 1, 2, 3, 5, 8, 13};
        String[] days = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};

        // Create a new instance of Gson
        Gson gson = new Gson();

        // Convert numbers array into JSON string.
        String numbersJson = gson.toJson(numbers);

        // Convert strings array into JSON string
        String daysJson = gson.toJson(days);

        System.out.println("numbersJson = " + numbersJson);
        System.out.println("daysJson = " + daysJson);

        // Convert from JSON string to a primitive array of int.
        int[] fibonacci = gson.fromJson(numbersJson, int[].class);
        for (int number : fibonacci) {
            System.out.print(number + " ");
        }
        System.out.println();

        // Convert from JSON string to a string array.
        String[] weekDays = gson.fromJson(daysJson, String[].class);
        for (String weekDay : weekDays) {
            System.out.print(weekDay + " ");
        }
        System.out.println();

        // Converting multidimensional array into JSON
        int[][] data = {{1, 2, 3}, {3, 4, 5}, {4, 5, 6}};
        String json = gson.toJson(data);
        System.out.println("Data = " + json);

        // Convert JSON string into multidimensional array of int.
        int[][] dataMap = gson.fromJson(json, int[][].class);
        for (int[] i : dataMap) {
            for (int j : i) {
                System.out.print(j + " ");
            }
            System.out.println();
        }
    }
}

Here is our code result:

numbersJson = [1,1,2,3,5,8,13]
daysJson = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"]
1 1 2 3 5 8 13 
Sun Mon Tue Wed Thu Fri Sat 
Data = [[1,2,3],[3,4,5],[4,5,6]]
1 2 3 
3 4 5 
4 5 6

Maven Dependencies

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.10.1</version>
</dependency>

Maven Central

How do I count the occurrences of a number in an array?

package org.kodejava.basic;

import java.util.HashMap;
import java.util.Map;

public class NumberOccurrenceInArray {
    public static void main(String[] args) {
        int[] numbers = new int[]{1, 8, 3, 4, 3, 2, 5, 7, 3, 1, 4, 5, 6, 4, 3};

        Map<Integer, Integer> map = new HashMap<>();
        for (int key : numbers) {
            if (map.containsKey(key)) {
                int occurrence = map.get(key);
                occurrence++;
                map.put(key, occurrence);
            } else {
                map.put(key, 1);
            }
        }

        for (Integer key : map.keySet()) {
            int occurrence = map.get(key);
            System.out.println(key + " occur " + occurrence + " time(s).");
        }
    }
}

The result are:

1 occur 2 time(s).
2 occur 1 time(s).
3 occur 4 time(s).
4 occur 3 time(s).
5 occur 2 time(s).
6 occur 1 time(s).
7 occur 1 time(s).
8 occur 1 time(s).