Java - Array

> Procedural Languages > Java

1 - 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.

Advertising

3 - Management

3.1 - Initialization

  • Declaration
// declares an array of 
//     - integers
int[] anArray;
//     - string
String[] anArray
// ...
  • 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
  • Array Initialization
int[] anArray= {1,2,3,4,5,6,7,8,9,10};
anArray= newInteger[]{1,2,3,4};

3.1.1 - List

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);
}
Advertising

3.2 - Conversion

3.2.1 - ToList

Arrays.asList

3.3 - Loop

3.3.1 - For

for

for (int i = 0; i < anArray.length; i++) {
 
	System.out.println(i+" : "+anArray[i]);
 
}

3.4 - Size

int size = array.length;

3.5 - 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);

3.6 - 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);

3.7 - Equality

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

3.8 - Class

Class literal

type[].class

Example for a byte:

byte[].class
Advertising

3.9 - Functional Programm

3.9.1 - Transformation

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

3.9.2 - 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());

3.10 - Slice

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

3.11 - Join

String.join(" ",args)

4 - Documentation / Reference

lang/java/array.txt · Last modified: 2019/10/05 14:34 by gerardnico