Table of Contents
One of the most common collections in Java are arrays. Arrays can be thought of as simply a list of data, and that data can take the form of numbers, strings, objects, even arrays themselves.
Creation
Creating an array in Java is pretty straightforward. Let's create one that contains strings:
JAVAString[] colors = { "red", "green", "blue" };
That right there is an array of 3 string
elements assigned to the variable colors
.
Arrays in Java have a set size. You can either initialize it like previously shown, or like this:
JAVAString[] colors = new String[3];
In both cases, an array of size 3
is created.
Retrieval
Now that we can create arrays, let's learn how to get an element back when we want to use it. Arrays in Java start counting from 0
. This means that the 3rd element in the array has an index of 2
.
With this in mind, let's get the second element from our original array:
JAVAString[] colors = { "red", "green", "blue" };
System.out.println(colors[1]);
BASHgreen
You can take this further and print the entire array, like this:
JAVAString[] colors = { "red", "green", "blue" };
for (int i = 0; i < colors.length; i++) {
System.out.println(colors[i]);
}
BASHred
green
blue
We simply iterate through all the values between 0
and the length of the array to get every element in that array.
Reassignment
Once you have initialized an array with values, you can modify each individual element pretty easily. Simply reassign the element's value like you would any variable:
JAVAString[] colors = { "red", "green", "blue" };
colors[1] = "yellow"; // reassignment
for (int i = 0; i < colors.length; i++) {
System.out.println(colors[i]);
}
BASHred
yellow
blue
Sort
You can easily sort a Java array by calling the sort()
method:
JAVAString[] colors = { "red", "green", "blue" };
Arrays.sort(colors);
for (int i = 0; i < colors.length; i++) {
System.out.println(colors[i]);
}
BASHblue
green
red
- Getting Started with TypeScript
- Getting Started with Solid
- Getting Started with Express
- Create an RSS Reader in Node
- Getting Started with Electron
- How to build a Discord bot using TypeScript
- How to deploy a PHP app using Docker
- How to deploy a Deno app using Docker
- Getting Started with Sass
- Using Puppeteer and Jest for End-to-End Testing
- Getting Started with React
- Setting Up a Local Web Server using Node.js