Java - Array

Java Conceptuel Diagram

About

Collection - Array in Java.

Arrays implement most of the List operations, but not remove and add. They are “fixed-size” Lists.

An array is a container object that holds :

  • a fixed number of values
  • of a single type.

The length of an array is established when the array is created. After creation, its length is fixed.

In Java, arrays cannot be resized dynamically. Another approach is to use a list.

Management

Initialization

  • Declaration
// declares an array of 
//     - integers
int[] anArray;
//     - string
String[] anArray
// A generic
T[] anGenericArray = (T[]) Array.newInstance(clazz, values.size())
// ...
  • Array Initialization
int[] anArray= {1,2,3,4,5,6,7,8,9,10};
anArray= new Integer[]{1,2,3,4};
string[] stringArray = new String[]{"foo","bar"}
  • Memory Allocation
// allocates memory for 3 integers with the index (0,1,2)
anArray = new int[3];
// allocates memory for 3 strings
anArray = new String[3];
  • Unit Initialization
// initialize first element
anArray[0] = "Nic";
// initialize second element
anArray[1] = "o";

anArray[2] = "Nic";
anArray[3] = "Nicooooo";
// and so forth

fromList

Foo[] array = new Foo[list.size()];
list.toArray(array); // fill the array
int[] array = new int[list.size()];
for(int i = 0; i < list.size(); i++) {
         array[i] = list.get(i);
}

IsArray

obj.getClass().isArray()

Array vs List - Pro / Cons

  • Pro: You can cast an array but not a list. Example: casting an array at the end of a stream
String[] names = (String[]) personss.stream().map(Person::getName).toArray();

Conversion

ToList

Arrays.asList

ToStream

Java - Stream Processing

Arrays.asList(array).stream()
// or shortcut
Arrays.stream(array)

Loop

For

for

for (int i = 0; i < anArray.length; i++) {

	System.out.println(i+" : "+anArray[i]);
	
}

Size

int size = array.length;

Resize

  • Integer array:
public static double [] resize(int[] array, int newSize){
    if (newSize == 0) {
      return [];
    }
    return array.length == newSize ? array : Arrays.copyOf(array, newSize);
}
  • Generic where array factory is a functional interface that creates the array in the good type
public static <T> T [] resize(T[] array, int newSize, ArrayFactory<? extends T> factory) {
    int oldSize = array.length;
    if (oldSize == newSize) {
      return array;
    }

    T[] result = factory.create(newSize);
    if (newSize == 0) {
      return result;
    }

    System.arraycopy(array, 0, result, 0, Math.min(oldSize, newSize));
    return result;
}
@FunctionalInterface
public interface ArrayFactory<T> {
  T[] create(int count);
}

Copy

char[] copyTo = java.util.Arrays.copyOfRange(copyFrom, 2, 9);
char[] copyTo = java.util.Arrays.copyOf(copyFrom, copyFrom.length)
System.arraycopy(copyFrom, 2, copyTo, 0, 7);

Concat

public static <T> T[] concatAll(T[] first, T[]... rest) {
    int totalLength = first.length;
    for (T[] array : rest) {
      totalLength += array.length;
    }
    T[] result = Arrays.copyOf(first, totalLength);
    int offset = first.length;
    for (T[] array : rest) {
      System.arraycopy(array, 0, result, offset, array.length);
      offset += array.length;
    }
    return result;
  }

Add an element in the first position

public static <T> T[] addElementFirst(T[] elements, T first) {
    int totalLength = elements.length + 1;
    T[] result = Arrays.copyOf(elements, totalLength);
    result[0]=first;
    System.arraycopy(elements, 0, result, 1, totalLength-1);
    return result;
}

Remove the last one

String[] arr = {"1","2","3"};
String[] arrMinOne = new String[arr.length-1];
System.arraycopy(arr,0,arrMinOne,0,arr.length-1);

Equality

import java.util.Arrays;
Arrays.equals(firstArray, secondArray));

Class

Class literal

type[].class

Example for a byte:

byte[].class

Functional Programming

Transformation

String[] arr = {"1","2",""};
arr = Arrays
	.stream(arr)
	.map(s -> {
		if (s.equals("")) {
			return null;
		} else {
			return s;
		}
	})
	.toArray(String[]::new);

Select by index

Example: select the even elements

List<String> evenElement = IntStream
      .range(0, elements.length)
      .filter(i -> i % 2 == 0)
      .mapToObj(i -> elements[i])
      .collect(Collectors.toList());

Slice

String[] args = Arrays.copyOfRange(args, 1, args.length);

Join

String.join(" ",args)

Documentation / Reference





Discover More
Java Conceptuel Diagram
Java - (Data Type|Type)

data type in the java world. The Java programming language is statically-typed, which means that all variables must first be declared before they can be used. The language supports four kinds...
Java Conceptuel Diagram
Java - (Enumerable|Iterator) Data Type (Iterable interface)

The (Enumeration|Iterator) interface defines the methods by which you can: iterate enumerate obtain one at a time the elements of a collection. The Enumerator Interface: has been deprecated...
Simple Class
Java - Class (Definition)

A java/lang/Classclass provides the blueprint for objects; you create an object from a class. All classes are derived from the Object class. A class declaration names the class and encloses the class...
Java Conceptuel Diagram
Java - For Statement

The for statement is a part of the control flow possibility of Java. The java/lang/IterableIterable interface must be implemented in order to use it. See for example: During a for loop, this is...
Java Conceptuel Diagram
Java - List (sequence)

A list (also known as a sequence): is ordered allow duplicates (multiple null elements if they allow them) is zero based. The first element is at the position 0. can contain themselves as elements...
Java Conceptuel Diagram
Java - Parameter

Parameters refers to the list of variables in a method declaration. Arguments are the actual values that are passed in when the method is invoked. When you invoke a method, the arguments used must match...
Java Conceptuel Diagram
Java - Random access file

A java/io/RandomAccessFilerandom access file behaves like a large array of bytes stored in the file system. There is a kind of cursor, or index into the implied array, called the file pointer. A Random...
Java Conceptuel Diagram
Java - Reference Data Type

Reference types in Java. Reference types all inherit from Object (the java.lang.Object class) Classes, enums, arrays, and interfaces Examples of reference types include: java.lang.String,...
Java Conceptuel Diagram
What is the Java Main Method and how to create one ?

This page is the main method in Java (ie the startup point of every app). This is a quick example that shows how to write a main method. psvmtab In the Java programming language, every application...



Share this page:
Follow us:
Task Runner