Ben Chuanlong Du's Blog

It is never too late to learn.

Arrays in Java

Comments

  1. An array in Java is not an Iterable (due to design reasons). There is no super class of array and Iterable either in Java. If you want a method to support both array and Iterable as the parameter, you need to overload it (for both array and Iterable.) It is the same situation in Kotlin as Kotlin is mostly Java.

Compare Arrays in Java

Instantiate Array Using Curly Braces

In [13]:
import java.util.Arrays;

long[] arr = new long[] {1, 2, 3};
Arrays.stream(arr).forEach(i -> System.out.println(i));
1
2
3
Out[13]:
null

Cast Arrays

System.arraycopy

In [ ]:
String[] stringArray = Arrays.copyOf(objectArray, objectArray.length, String[].class);
In [ ]:
Arrays.copyOf

ArrayList to Array

In [ ]:
ArrayList.toArray(new Type[0])

Stream

In [ ]:
String[] strings = Arrays.stream(objects).toArray(String[]::new);
In [ ]:
String[] strings = Arrays.stream(obj).map(Object::toString).toArray(String[]::new);

Comments