r/javaexamples • • May 19 '15

Using Arrays and ArrayLists

Using Arrays and ArrayLists

Learning how to use Arrays, and the more dynamic Array Lists is an important part of learning how to program Java.

The simplest way to think of an array is like a set of shelves, drawers or boxes. Each drawer has a number, starting at zero and going to -> number of drawers - 1.

See Here

An array can hold any data type, even other arrays.

	// create an array of ints, size 10
	int[] grades = new int[10];

	// create an array of strings, size 20
	String[] arrayOfStrings = new String[20];

	// create an array of Integer objects, size 5
	Integer[] arrayOfIntegerObjects = new Integer[5];

	// create an array of used defined object
	MyObject[] foo = new MyObject[100];

	// create an array of linked lists - note: will throw unchecked operation warning
	LinkedList<Integer>[] arrayOfLinkedLists = new LinkedList[3];

You can also declare an array with initial values, like this:

    int[] numbers = { 1, 2, 3, 43, 57 };

This will automatically size the array properly.

Accessing Elements of the Array

Just reference the index number using square brackets. Don't forget the index starts at zero!

System.out.println(numbers[0]);

Would output 1 in the above example.

System.out.println(numbers[4]);

Would output 57, and saying numbers[5] will cause an ArrayOutOfBounds exception.

Looping through Arrays

There are two main ways to loop through an array, a for loop and a for-each loop. Use the first if you need the index value, use the second if you just need to loop through them all. See also

The For Loop

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

The For-Each Loop

for (type current : arrayName) {}

so in our example above:

for (int current : numbers) {
	System.out.println(current);
}

So, lets make an array and fill it with random values:

	// create an array of ints, size 10
	int[] grades = new int[10];

	//loop through array and fill with random data
	// actually counts from 0 to 9
	for(int i = 0; i < grades.length; i++)
	{
		// random integer from 50 - 100
		// assumes you have declared & imported Random rand
		grades[i] = rand.nextInt(50) + 51;
		System.out.println("Array location " + i + " = " + grades[i]);
	}
	System.out.println();

Output from above:

Array location 0 = 57
Array location 1 = 95
Array location 2 = 72
Array location 3 = 86
Array location 4 = 56
Array location 5 = 76
Array location 6 = 61
Array location 7 = 98
Array location 8 = 73
Array location 9 = 77

Now you can sort the array like this:

Arrays.sort(grades);

See the full code below for more examples of operations upon arrays, like arraycopy, and getting the sum and average of array elements.

Arrays are fast and powerful, but have one main problem: You need to know the size of the data you have upon creation! Many times you will not know the size of the data you are working with, so we need to use a more complex object. here is where the ArrayList comes in.

ArrayList is generic, so it is instantiated with the diamond brackets, and cannot use primitive types (int, double etc. - although, use the Object types of each, and you can still add primitive elements to the list, the compiler will automatically convert them, this is called autoboxing).

So for ints, you would say:

ArrayList<Integer> myList = new ArrayList<>();

and then, to add an element, say:

myList.add(123);

To get the value at a certain index, use:

myList.get(index);

To find a specific value use:

int index = myList.indexOf(123);

returns the index found, or -1 if not found.

See the example program for more:

// Arrays example
// by /u/Philboyd_Studge for /r/javaexamples
// 
// Example of Arrays and ArrayLists
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
import java.util.Scanner;


public class ArraysExample
{
	public static Random rand = new Random();
	public static Scanner scan = new Scanner(System.in);
	
	public static void main(String[] args)
	{

		// create an array of ints, size 10
		int[] grades = new int[10];

		//loop through array and fill with random data
		// actually counts from 0 to 9
		for(int i = 0; i < grades.length; i++)
		{
			grades[i] = rand.nextInt(50) + 51;
			System.out.println("Array location " + i + " = " + grades[i]);
		}
		System.out.println();

		// or directly access by index number
		grades[4] = 100;

		System.out.println("Changed index 4");

		// display them again
		for(int i = 0; i < 10; i++)
		{
			System.out.println("Array index " + i + " = " + grades[i]);
		}
		System.out.println();

		//sort the array
		Arrays.sort(grades);

		System.out.println("Sorted:");

		// Here's another way to loop through them
		for(int each : grades)
		{
			System.out.println("Grade = " + each);
		}

		//search a sorted array
		System.out.println("100 found at index " + Arrays.binarySearch(grades, 100));

		// let's get a sum
		int sum = 0;
		for(int each : grades) 
		{
			sum += each;
		}
		System.out.println("Sum of array = " + sum);

		// get average
		double avg = sum/10.0;
		System.out.println("Average = " + avg);

		// let's fill the array with user entries
		String input = "";
		for (int i = 0; i < 10; i++)
		{
			System.out.print("Enter an integer:");
			input = scan.nextLine();
			try
			{
				grades[i] = Integer.parseInt(input);
			}
			catch (NumberFormatException nfe)
			{
				grades[i] = 0;
			}
		}

		// sort
		Arrays.sort(grades);

		// display
		for (int each : grades) System.out.println(each);

		// array copy
		int[] array2 = new int[5];

		System.arraycopy(grades, 5, array2, 0, 5);

		System.out.println("Copied last 5 elements:");
		for (int each : array2) System.out.println(each);

		// now, let's use an ArrayList
		ArrayList<Integer> gradeList = new ArrayList<>();

		// let's fill the array with user entries
		while (!input.equalsIgnoreCase("done"))
		{
			System.out.print("Enter an integer (or 'done'):");
			input = scan.nextLine();
			if (input.equalsIgnoreCase("done")) break;
			try
			{
				gradeList.add(Integer.parseInt(input));
			}
			catch (NumberFormatException nfe)
			{
				System.out.println("Incorrect entry.");
			}
		}

		// add arbitrary value in case user entered no values
		if (gradeList.isEmpty()) gradeList.add(25);

		// sort, slightly different from array sort
		Collections.sort(gradeList);


		//add specific index
		gradeList.add(gradeList.size() - 1, 100 );
		// for-each display
		for (Integer each : gradeList) System.out.println(each);

		//find in array
		System.out.println("Found '100' at index = " + gradeList.indexOf(100));

		// get
		System.out.println("Get list index 0 = " + gradeList.get(0));

		// display list with index
		for (int i = 0; i < gradeList.size(); i++)
		{
			System.out.println("Index " + i + " = " + gradeList.get(i));
		}

		// min/max

		System.out.println("Min: " + Collections.min(gradeList));
		System.out.println("Max: " + Collections.max(gradeList));




	}	
}

Example output:

Array location 0 = 85
Array location 1 = 57
Array location 2 = 56
Array location 3 = 92
Array location 4 = 88
Array location 5 = 78
Array location 6 = 61
Array location 7 = 60
Array location 8 = 94
Array location 9 = 67

Changed index 4
Array index 0 = 85
Array index 1 = 57
Array index 2 = 56
Array index 3 = 92
Array index 4 = 100
Array index 5 = 78
Array index 6 = 61
Array index 7 = 60
Array index 8 = 94
Array index 9 = 67

Sorted:
Grade = 56
Grade = 57
Grade = 60
Grade = 61
Grade = 67
Grade = 78
Grade = 85
Grade = 92
Grade = 94
Grade = 100
100 found at index 9
Sum of array = 750
Average = 75.0
Enter an integer:33
Enter an integer:44
Enter an integer:12345
Enter an integer:2
Enter an integer:3
Enter an integer:1
Enter an integer:9909
Enter an integer:poop
Enter an integer:4567
Enter an integer:-3
-3
0
1
2
3
33
44
4567
9909
12345
Copied last 5 elements:
33
44
4567
9909
12345
Enter an integer (or 'done'):44
Enter an integer (or 'done'):poop
Incorrect entry.
Enter an integer (or 'done'):1.2
Incorrect entry.
Enter an integer (or 'done'):345
Enter an integer (or 'done'):929394
Enter an integer (or 'done'):23
Enter an integer (or 'done'):1
Enter an integer (or 'done'):22
Enter an integer (or 'done'):done
1
22
23
44
345
100
929394
Found '100' at index = 5
Get list index 0 = 1
Index 0 = 1
Index 1 = 22
Index 2 = 23
Index 3 = 44
Index 4 = 345
Index 5 = 100
Index 6 = 929394
Min: 1
Max: 929394
3 Upvotes

0 comments sorted by