Arrays - Lists: Java Programming

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 26

Arrays – lists

Java programming

Tobias Andersson Gidlund

tobias.andersson.gidlund@lnu.se

Department of Computer Science


Arrays – lists 1(26)
About arrays

▶ An array is the built in and primitive way in Java to create lists.


▶ In Java, arrays are fixed sized lists of a specific data type.
▶ This means that the array is initialised for a specific size and the size cannot be
changed after this.
▶ It can also just contain elements of one, and only one, data type such as integer or
float.
▶ More dynamic lists are available in the Java library, but need to imported.
▶ This includes ArrayList and LinkedList covered in another lecture.
▶ A list can be of different dimensions, that is for example two or three dimensional.
▶ Useful for constructing tables or representing 3D objects.

Department of Computer Science


Arrays – lists 2(26)
The data type list

▶ Model:
A list can be seen as a binder.
▶ You can browse it, look in, remove or add sheets.
▶ The binder can be empty, but the binder is still there.
▶ A model can be seen as a sequence of elements:

(♣, , ♠, ♯, ♣, ♭)
▶ The parenthesis is not part of the list, but rather represents the list itself.
▶ It shows the start and end of the list.

Department of Computer Science


Arrays – lists 3(26)
Organisation of the list

▶ A list is an ending number of linearly arranged elements.


(a1 , a2 , a3 , . . . , an )
▶ It would be possible to think of an unending list, but this is not possible for a
computer.
▶ This should not, however, be confused with known number of elements, some of the
list data types can handle unknown number of elements.
▶ The order of elements is defined in a before-after relation:
▶ The list has a first and a last element.
▶ All elements, except the last, has a unique subsequent element.
▶ All elements, except the first has a unique predecessor.

Department of Computer Science


Arrays – lists 4(26)
Organisation, cont.

▶ A list is a list of type, for example integers or persons.


▶ This means that the list is an ordered sequence of elements of a certain type.
▶ The list is, with other words, homogeneous.
▶ Examples of lists are:
▶ Lists of integers.
▶ Strings (lists of characters).
▶ Person register (list of persons)
▶ Pig register (list of pigs).
▶ …

Department of Computer Science


Arrays – lists 5(26)
The list type array

▶ As stated, the most primitive of list types in Java is the array


▶ It is only available in memory and does not have a graphical representation.
▶ A “ordinary” variable has a name, a type and a content.

30 int age;

▶ We use the variable as a “container” for a certain data type.


▶ The variable can then be used as the data type.
▶ Integers can be added, subtracted and so on.

Department of Computer Science


Arrays – lists 6(26)
“Larger” variables

▶ The array type can be seen as a “larger” variable.


▶ That is, it can contain more than one value.
▶ Every part of the array must be of the same data type.
▶ An example could be that every part is of integer type.
▶ The parts are called elements (or components).
▶ An array can be seen as a list of the same kind of elements.
▶ It can be visualised as follows:

45 53 64 12 33 12 Integer array
0 1 2 3 Length - 2 Length - 1 Element index

Department of Computer Science


Arrays – lists 7(26)
Concepts

▶ An array is a numbered collection of elements of the same kind


▶ Each element is of the same data type as the others.
▶ An integer array consists only of integers.
▶ Each element in the array has an index number – it is numbered.
▶ In Java the numbering starts with zero.
▶ The first element is therefore number zero, the second one is number one and so on.
▶ When working with an array, it is still just one variable to work with.
▶ Differentiate therefore between the content and the index number.

Department of Computer Science


Arrays – lists 8(26)
Creating an array
▶ An array is an object and needs to be created as such using new.
double[] rain = new double[7];

▶ Here an array of length seven is created that can contain only decimal numbers.
▶ The different elements in the array can be accessed using the index:
rain[0] = 22.5;

▶ The values can also be read using the same approach:


System.out.println(rain[3]);

▶ Notice that it is up to you as a programmer to make sure you are within the index
range when you read or set the values.

Department of Computer Science


Arrays – lists 9(26)
Complete example
package lecture8;

public class Rain {


public static void main(String[] args) {
double[] rain = new double[7];

rain[0] = 22.5;
rain[1] = 3.4;
rain[2] = 10.5;
rain[3] = 0.3;
rain[4] = 3.14; Output:
rain[5] = 2.3;
rain[6] = 22.6;
0.3
System.out.println(rain[3]); The avarage rain fall is 9.248571428571427

double sum = 0.0;

for(int i = 0; i < 7; i++)


sum += rain[i];

System.out.println("The avarage rain fall is " +


,→ (sum/7.0));
}
}

Department of Computer Science


Arrays – lists 10(26)
Faster initiation

▶ An array can be created for any data type, including classes (as we will look more
into later).
▶ If, at the time of creation, the elements are know, the array can be initiated directly.
▶ Put the initiated values in curly brackets at the initiation.
▶ Notice that the size is not needed when initiating with values, as it can be deduced
by the number of values.
int[] siffror = { 1, 2, 3, 4, 5, 6};

▶ Also notice the semi colon at the end, it is needed.

Department of Computer Science


Arrays – lists 11(26)
Example
package lecture8;
import java.util.Random;

public class FastSentence {


public static void main(String[] args) {
Random rnd = new Random();
String[] p = {"I", "You", "He", "She", "It", "We", "They"};
String[] v = {"eat(s)", "squash(es)", "pull(s)", "push(es)", "hug(s)", They lift(s) a pen
,→ "kill(s)", "lift(s)", "blow(s)"};
String[] n = {"a pen", "a whale", "a friend", "a pig", "a robot", "a She eat(s) a pig
,→ book", "a film", "a candle"}; I pull(s) a pen
It push(es) a whale
int valp = 0; int valv = 0; int valn = 0;
We kill(s) a book
for(int i = 0; i < 5; i++) {
valp = rnd.nextInt(p.length);
valv = rnd.nextInt(v.length);
valn = rnd.nextInt(n.length);
System.out.println(p[valp] + " " + v[valv] + " " + n[valn]);
}
}
}

Department of Computer Science


Arrays – lists 12(26)
Length and iteration

▶ The length of an array is given by the property length (as seen in the previous
example).
▶ One of the most common errors for arrays is ArrayIndexOutOfBoundsException
▶ One key insight is that the last index is always one less than the size:
max_index = array_name.length - 1;

▶ To fully understand how arrays work, we recommend that you try to do exercises
like calculating the sum, finding the largest, shift position and many more.

Department of Computer Science


Arrays – lists 13(26)
Example – finding smallest value
package lecture8;

public class FindingLowest {


public static void main(String[] args) {
int[] numbers = {2, 5, 3, 6, 1, 5, 9};

int min = numbers[0];

for(int i = 0; i < numbers.length; i++) {


if(numbers[i] < min) Here are the numbers:
min = numbers[i];
} 2 5 3 6 1 5 9
System.out.println("Here are the numbers: "); Smallest number was 1
for(int j = 0; j < numbers.length; j++)
System.out.print(numbers[j] + " ");

System.out.println();

System.out.println("Smallest number was " +


,→ min);
}
}

Department of Computer Science


Arrays – lists 14(26)
A more comfortable for

▶ There is another, simpler, form of iteration for arrays (and other lists).
▶ It is called foreach iteration even if the keyword is for…
▶ Example:
for(double s: snow) {
sum += s;
}

▶ Can be read as “for each double s in snow”.


▶ Positive with this is that you do not need to keep track of the index number.
▶ Negative is that you cannot do anything else but step through the array.

Department of Computer Science


Arrays – lists 15(26)
Example
package lecture8;

public class ConvenientFor {


public static void main(String[] args) {
double[] snow = {3.14, 5.2, 5.5, 3.2, 2.54, 4.24, 3.14};

double sum = 0.0;

for(double s: snow) {
sum += s;
}

double averageSnow = sum / 7.0;

System.out.println("Average snow: " + averageSnow);


}
}

Average snow: 3.8514285714285714


Department of Computer Science
Arrays – lists 16(26)
Copying arrays

▶ It is not entire natural how to copy an array to another.


▶ The first is to know that it is a difference between the array and the content of the
array.
▶ A simple assignmnet just sets the array to point to the other array.
▶ This means that if the content is changed in one of them, it is also changed in the
other.
▶ If the array to the left had a value before the assignmnet, then this is now gone.
▶ The garbage collector in Java will remove it from memory.

Department of Computer Science


Arrays – lists 17(26)
package lecture8;
public class CopyParty {
public static void main(String[] args) {
String[] sentence1 = {"I", "am", "Anakin"};
String[] sentence2 = {"We", "drive", "a starship"};

for(String s: sentence1)
System.out.print(s + " ");
System.out.println();

for(String s: sentence2) I am Anakin


System.out.print(s + " ");
System.out.println(); We drive a starship
sentence2 = sentence1; I am Anakin
for(String s: sentence2) I am Darth Vader
System.out.print(s + " ");
System.out.println(); I am Darth Vader
sentence2[2] = "Darth Vader";

for(String s: sentence1)
System.out.print(s + " ");
System.out.println();

for(String s: sentence2)
System.out.print(s + " ");
}
}
Department of Computer Science
Arrays – lists 18(26)
Ways to copy an array

▶ If you really want to do a value copy of an array, there are three ways to do that:
▶ Copy each element.
▶ Use copyOf in Arrays.
▶ the method clone.
▶ Next example will show how to copy each element manually.
▶ You should also have a closer look at copyOf.
▶ Another, not as recommended way, is to use arraycopy in System.

Department of Computer Science


Arrays – lists 19(26)
package lecture8;

public class CopyArray {


public static void main(String[] args) {
char[] greek = new char[] {'Z', 'e', 'u', 's'};
char[] nordic = new char[4];

for(char c: greek){
System.out.print(c);
}
System.out.println();
for(int i = 0; i < greek.length; i++) {
Zeus
nordic[i] = greek[i];
}
Zeus
for(char c: nordic) {
System.out.print(c);
Oden
}
System.out.println();
Zeus
nordic[0] = 'O'; nordic[1] = 'd'; nordic[2] = 'e'; nordic[3] = 'n';

for(char c: nordic) {
System.out.print(c);
}
System.out.println();
for(char c: greek){
System.out.print(c);
}
}
}

Department of Computer Science


Arrays – lists 20(26)
Multidimensional arrays

▶ The arrays shown so far have only had one dimension.


▶ Which basically means it is a list.
▶ An array can, however, have as many dimensions as you like.
▶ Two dimensions is common.
▶ Three is not uncommon, not the least as we see the world in three dimensions.
▶ Larger dimentions than that are uncommon, but difficult to “see”.
▶ Though not impossible and can be seen as different “layers”.
▶ The concept is the same in the programming language.

Department of Computer Science


Arrays – lists 21(26)
Two dimensional arrays

▶ The most common form after one-dimensional arrays.


▶ Much of what we see is two dimensional:
▶ Chess boards
▶ Spreadsheets
▶ Two dimensional arrays are sometimes called tables.
▶ There is also a close connection between two dimensional arrays and nested loops.
▶ Java does not have “true” multidimensional arrays but use arrays-in-arrays.

Department of Computer Science


Arrays – lists 22(26)
Declaration

▶ Declaration specifies the number of rows and columns.


▶ In that order.
▶ Each dimension is shown with a new set of brackets.
▶ Example:
int[][] array2D = new int[3][2];

▶ In this case, a new array is created with three rows with two columns – in each
“cell” there is an int.
▶ Notice that in Java it is allowed, but not recommended, to put the brackets with the
variable instead of with the data type.

Department of Computer Science


Arrays – lists 23(26)
package lecture8;
public class Simple2D {
public static void main(String[] args) {
int[][] array2D = new int[3][2];

array2D[0][0] = 8;
array2D[0][1] = 16;
array2D[1][0] = 32;
array2D[1][1] = 64; 8 16
array2D[2][0] = 128; 32 64
array2D[2][1] = 512;
128 512
for(int i = 0; i < array2D.length; i++) {
for (int j = 0; j < array2D[i].length; j++) {
System.out.print(array2D[i][j] + " ");
}
System.out.println();
}
}
}

Department of Computer Science


Arrays – lists 24(26)
Another example
package lecture8;
public class Init2D {
public static void main(String[] args) {
double[][] temperature = {
{11.2, 12.0, 12.9, 17.0, 13.4, 17.0, 20.5},
{19.0, 20.5, 21.5, 16.0, 16.0, 13.5, 10.9},
{15.0, 15.5, 17.0, 19.0, 20.1, 24.0, 22.5},
{17.0, 17.5, 20.5, 21.0, 21.5, 23.0, 20.5}
};

System.out.println("Monday\tTuesday\tW-day\tT-day\tFriday\tS-day\tSunday");

for(int i = 0; i < temperature.length; i++) {


for(int j = 0; j < temperature[i].length; j++) {
System.out.print(temperature[i][j] + "\t");
}
System.out.println();
}
}
}

Monday Tuesday W-day T-day Friday S-day Sunday


11.2 12.0 12.9 17.0 13.4 17.0 20.5
19.0 20.5 21.5 16.0 16.0 13.5 10.9
15.0 15.5 17.0 19.0 20.1 24.0 22.5
17.0 17.5 20.5 21.0 21.5 23.0 20.5

Department of Computer Science


Arrays – lists 25(26)
Summary

▶ Arrays is the primitive, built-in, way to create lists in Java.


▶ In Java, arrays must be created with a fixed size and for one single data type.
▶ Each element in an array can be accessed using index numbers.
▶ Starting from zero.
▶ Arrays can have more dimensions than one, for example two or three.

Department of Computer Science


Arrays – lists 26(26)

You might also like