Skip to content

Arrays

A way to arrange data in Java

  • Lesson
  • 3 min read
  • 13 of 15 in this chapter

What are arrays?

An array is a way to store multiple sets of data into a single variable. This type of data structure localizes a set of data. For example...

Java
//we are going to use an int for this array
int arrayName[]; //this is how we declare an array

This is how we make an array with elements

Java
int arrayName[] = {0,1,2,3,4,5,6};

Functions that go along with arrays

There are many ways to obtain and edit data in an array. The way you access a specific value from a position on an array is to use...

Java
arrayname[x];
//x is the position in the array

remember array positions are from a 0 based counting system (for example position 0 would be the first entry in an array, position 1 would be the second entry in an array, etc. )

To change the value of a datatype in an array use...

Java
arrayname[x] = 5;
/*In this we are setting the value of the array 'arrayname' at x position to 5*/

Another function for arrays includes finding array length. This function is called array.length. The way you find the length of an array, is to use “arrayname.length”

You can loop through every position in an array using for loops. For example...

Java
for(int i = 0;i < arrayname.length; i++){
 System.out.println(arrayname[i]); 
}

You can also loop through every position on an array like this...

Java
int arrayName[] = {2,3,4,5,1,3};
for(int i: arrayName){
 /*this iterates through all indexes 
 and returns a value*/
 System.out.println(i);
 //this will print out every point on an array
 //2 3 4 5 1 3
}

ArrayList

What if we wanted to add entries to an array, so that we can make it as long as we desire? Well we can with ArrayList. ArrayList is a way to make an array that is resizable.

To start we need to add this to the top of our code…

Java
import java.util.ArrayList;

This is how we initialize the ArrayList…

Java
public static void main(String[] args){
 ArrayList listName = new ArrayList();
 //The syntax is:
 //ArrayList name = new ArrayList();
}

This is how we add an entry to our ArrayList…

Java
listName.add("what we want to put in the list");

This is how we remove an item to our array list…

Java
listName.remove(0);
//syntax listName.remove(the index position from the list); 

Here are some other functions for ArrayList...

Java
ArrayList listName = new ArrayList();
listName.get(0);
/*this will give us the value at 
index 0(first entry on the list)
NOTE: This is not standalone code*/
//a good use of this function is to print >
System.out.println(listName.get(0));
listName.set(0,"list item");
/*this sets the value of the first position to:
list item*/
listName.size();
/*this will return the size of the array
NOTE:this is not standalone code*/
listName.clear();
//this will clear the list