Last Updated:

Popular methods for working with Java arrays

Printing Array Elements

int[] simpleIntArray = { 2, 5, 3, 1, 4 };
String arrayString = Arrays.toString(intArray);
// if you explicitly specify simpleIntArray, then we will get a printed link
System.out.println(simpleIntArray );
// [I@3250ac3b


// specify the array converted to a string and get the desired result
System.out.println(arrayString);
// [2, 5, 3, 1, 4]

Array sorting

We use the Arrays.sort() method and our own implementation of bubble array sorting.

Creating an ArrayList from an Array

An easy way to create a collection from an array can contain pitfalls. Read more about possible problems here.ArrayList

For another example of use, see the link.

Creating an Array from an ArrayList

Below is a simple example "on the knee", and there is an explanation at the link.

Does the array contain the specified element?

We use the technique of representing the array as a collection and calling the usual method:contains()

String[] simpleStringArray = { "a", "c", "e" };
boolean contains = Arrays.asList(simpleStringArray).contains("e");
// print true
System.out.println(contains);

Copying an Array in Java

We use methods to copy the array ,, and even . Here's another example.Arrays.copyOf() Arrays.copyOfRange()System.arraycopy()Object.clone()

Converting an Array to a Set

 

You can learn more about the Set collection here, and find out the difference between Set and Set<?> here.

Convert int to byte array

// create a new buffer of bytes of the specified size
byte[] mByteArray = ByteBuffer.allocate(4).putInt(8).array();
for (byte t : mByteArray ) {
System.out.format("0x%x ", t);
}

Using the Apache Commons Lang library

The Apache Commons Lang library is a set of utility classes to make it easier to work with the classes in the . In our case, we will use the available methods to work with arrays.java.lang.*

You can connect this library to your application using the dependencies for maven projects:

Or in another suitable way for you (see the link in the code above).

Combining (concatenation) of an array

 

Retrieving the Reverse Array

int[] simpleIntArray = { 2, 4, 6, 8, 10 };
ArrayUtils.reverse(simpleIntArray);
// Get to the console [10, 8, 6, 4, 2]
System.out.println(Arrays.toString(simpleIntArray));

Delete an array element

 

This is how my selection of methods for working with arrays in Java ends. If this article was useful to you and learned something new, then subscribe to new articles on Java and Android!

And what methods do you use most often when working with arrays?