89
Arrays and Array Lists CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1

Arrays and Array Lists - University of Texas at Arlington

  • Upload
    others

  • View
    5

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Arrays and Array Lists - University of Texas at Arlington

Arrays and Array Lists

CSE 1310 – Introduction to Computers and Programming

Vassilis Athitsos

University of Texas at Arlington

1

Page 2: Arrays and Array Lists - University of Texas at Arlington

Motivating Exercise

• Let's write a program that:

– Asks the user to enter three numbers.

– Prints how many of those numbers are less than the last number entered.

• Example:

– user enters: 10 35 15

– program prints:

2

Page 3: Arrays and Array Lists - University of Texas at Arlington

Motivating Exercise

• Let's write a program that:

– Asks the user to enter three numbers.

– Prints how many of those numbers are less than the last number entered.

• Example:

– user enters: 10 35 15

– program prints: 1 of those numbers are less than 15

– explanation: 10 is less than the last number entered, which was 15.

3

Page 4: Arrays and Array Lists - University of Texas at Arlington

Motivating Exercise

• Let's write a program that:

– Asks the user to enter three numbers.

– Prints how many of those numbers are less than the last number entered.

• Another example:

– user enters: 100 35 10

– program prints:

4

Page 5: Arrays and Array Lists - University of Texas at Arlington

Motivating Exercise

• Let's write a program that:

– Asks the user to enter three numbers.

– Prints how many of those numbers are less than the last number entered.

• Another example:

– user enters: 100 35 10

– program prints: 0 of those numbers are less than 10

– explanation: none of the numbers entered is less than the last number entered (which is 10).

5

Page 6: Arrays and Array Lists - University of Texas at Arlington

Motivating Exercise

• Let's modify the previous program so that it:

– Asks the user to enter four numbers.

– Prints how many of those numbers are less than the last number entered.

• Example:

– user enters: 10 5 20 15

– program prints:

6

Page 7: Arrays and Array Lists - University of Texas at Arlington

Motivating Exercise

• Let's modify the previous program so that it:

– Asks the user to enter four numbers.

– Prints how many of those numbers are less than the last number entered.

• Example:

– user enters: 10 5 20 15

– program prints: 2 of those numbers are less than 15

– explanation: 10 and 5 are less than the last number entered, which was 15.

7

Page 8: Arrays and Array Lists - University of Texas at Arlington

Limits of This Approach

• Let's modify the previous program so that it:

– Asks the user to enter 20 numbers.

– Prints how many of those numbers are less than the last number entered.

• Or, how about we modify the previous program so that the user can enter as many numbers as they want (they can enter "q" when they are done).

8

Page 9: Arrays and Array Lists - University of Texas at Arlington

Limits of This Approach

• Let's modify the previous program so that it:

– Asks the user to enter 20 numbers.

– Prints how many of those numbers are less than the last number entered.

– Can be done, but is very tedious.

• Or, how about we modify the previous program so that the user can enter as many numbers as they want (they can enter "q" when they are done).

– CANNOT BE DONE WITH WHAT WE KNOW

9

Page 10: Arrays and Array Lists - University of Texas at Arlington

Another Program We Would Like to Write but Cannot

• Write a program that:

– Asks the user to specify an integer N.

– Asks the user to enter N names and phone numbers.

– Then, whenever the user types a name, the computer outputs the corresponding phone number.

• Again, this cannot be done with what we know so far.

10

Page 11: Arrays and Array Lists - University of Texas at Arlington

Containers

• A container is a data type that allows you to store not just one value, but a set of values.

• Container is a computer science term, not a Java term.

• Different programming languages have different (and usually multiple) names for containers.

– A common name is arrays (Java, C++).

11

Page 12: Arrays and Array Lists - University of Texas at Arlington

Containers in Java: Arrays, Array Lists

• There are multiple types of containers in Java as well.

• In this course we will talk about two types of containers:

– Arrays.

– Array lists.

12

Page 13: Arrays and Array Lists - University of Texas at Arlington

A First Example

• Printing months and their lengths.

• Without arrays:

– 12 variables for month names.

String month1_name = "January";

String month2_name = "February";

String month3_name = "March";

String month4_name = "April";

String month5_name = "May";

String month6_name = "June";

13

Page 14: Arrays and Array Lists - University of Texas at Arlington

A First Example

• Printing months and their lengths.

• Without arrays:

– 12 variables for month lengths.

int month1_length = 31;

int month2_length = 28;

int month3_length = 31;

int month4_length = 30;

int month5_length = 31;

int month6_length = 30;

14

Page 15: Arrays and Array Lists - University of Texas at Arlington

A First Example

• Printing months and their lengths.

• Printing out this info requires explicitly mentioning each variable.

System.out.printf("%s has %d days.\n", month1_name, month1_length);

System.out.printf("%s has %d days.\n", month2_name, month2_length);

System.out.printf("%s has %d days.\n", month3_name, month3_length);

System.out.printf("%s has %d days.\n", month4_name, month4_length);

System.out.printf("%s has %d days.\n", month5_name, month5_length);

System.out.printf("%s has %d days.\n", month6_name, month6_length);

15

Page 16: Arrays and Array Lists - University of Texas at Arlington

A First Example

• Printing months and their lengths.

• With arrays:

– One variable for month names.

String[] month_names = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};

– One variable for month lengths.

int[] month_lengths = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

16

Page 17: Arrays and Array Lists - University of Texas at Arlington

A First Example

• Printing out months and lengths is easy, using a loop.

17

public class months_arrays {

public static void main(String[] args) {

String[] month_names = {"January", "February", "March",

"April", "May", "June",

"July", "August", "September",

"October", "November", "December"};

int[] month_lengths = {31, 28, 31, 30, 31, 30,

31, 31, 30, 31, 30, 31};

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

{

System.out.printf("%s has %d days.\n",

month_names[i], month_lengths[i]);

}

}

}

Page 18: Arrays and Array Lists - University of Texas at Arlington

Why Is the Array Solution Better?

18

Page 19: Arrays and Array Lists - University of Texas at Arlington

Why Is the Array Solution Better?

• Without arrays, printing all names and lengths of months requires many lines of code.

– Using arrays, we need two lines of code.

• Without arrays, changing output from "xxx has yy days." to "There are yy days in xxx." requires 12 changes.

– One change using arrays: just change the printf in the loop. System.out.printf("There are %d days in %s.\n",

month_lengths[i], month_names[i]);

19

Page 20: Arrays and Array Lists - University of Texas at Arlington

Arrays Simplify Code

• Entering data remains painful.

– Either way we must enter 12 names and 12 lengths.

– The solution to that will be files (our next topic).

• Data will be read automatically from files.

• Manipulating data becomes much easier.

– We can go through data using loops.

– We can process millions of data (strings, numbers) with few lines of code.

20

Page 21: Arrays and Array Lists - University of Texas at Arlington

Creating an Array of Numbers

• There are two ways to create an array.

• First: providing an initial list of values.

int[] numbers = {10, 2, 5, 40, 30, 100, 200};

• Second: providing just the length.

int[] numbers = new int[4];

• The second approach initializes all values to 0.

21

Page 22: Arrays and Array Lists - University of Texas at Arlington

Creating an Array of Strings

• There are two ways to create an array.

• First: providing an initial list of values.

String[] names = {"Mary", "Ann", "Joe"};

• Second: providing just the length.

String[] names = new String[10];

• The second approach initializes all values to null.

– null means that these values are not valid strings.

22

Page 23: Arrays and Array Lists - University of Texas at Arlington

Accessing Single Elements

int[] numbers = {10, 2, 5, 40, 30, 100, 200};

int a = numbers[0];

System.out.printf("%d", numbers[5]);

• The above code:

– creates an array of 7 integers.

– numbers[0] refers to element 0 of the array, which is ???

23

Page 24: Arrays and Array Lists - University of Texas at Arlington

Accessing Single Elements

int[] numbers = {10, 2, 5, 40, 30, 100, 200};

int a = numbers[0];

System.out.printf("%d", numbers[5]);

• The above code:

– creates an array of 7 integers.

– numbers[0] refers to element 0 of the array, which is 10.

IMPORTANT: ELEMENT POSITIONS START WITH 0, NOT WITH 1.

24

Page 25: Arrays and Array Lists - University of Texas at Arlington

Accessing Single Elements

int[] numbers = {10, 2, 5, 40, 30, 100, 200};

int a = numbers[0];

System.out.printf("%d", numbers[5]);

• The above code:

– creates an array of 7 integers.

– numbers[5] refers to element 5 of the array, which is ???.

25

Page 26: Arrays and Array Lists - University of Texas at Arlington

Accessing Single Elements

int[] numbers = {10, 2, 5, 40, 30, 100, 200};

int a = numbers[0];

System.out.printf("%d", numbers[5]);

• The above code:

– creates an array of 7 integers.

– numbers[5] refers to element 5 of the array, which is 100.

26

Page 27: Arrays and Array Lists - University of Texas at Arlington

Accessing Single Elements

int[] numbers = {10, 2, 5, 40, 30, 100, 200};

int a = numbers[7];

• The above code will do what?

27

Page 28: Arrays and Array Lists - University of Texas at Arlington

Accessing Single Elements

int[] numbers = {10, 2, 5, 40, 30, 100, 200};

int a = numbers[7];

• The above code will crash.

– numbers[7] does not exist, valid positions are only from 0 to 6.

28

Page 29: Arrays and Array Lists - University of Texas at Arlington

Length of an Array

int[] numbers = {10, 2, 5, 40, 30, 100, 200};

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

{

System.out.printf("%d\n", numbers[i]);

}

• The above code prints all 7 elements of the array.

• numbers.length gives the number of elements in the array.

29

Page 30: Arrays and Array Lists - University of Texas at Arlington

Changing Single Elements

int[] numbers = {10, 2, 5, 40, 30, 100, 200};

numbers[0] = 3;

numbers[4] = 15;

• The above code:

– creates an array of 7 integers.

– sets the value of numbers[0] to 3.

– sets the value of numbers[4] to 15.

30

Page 31: Arrays and Array Lists - University of Texas at Arlington

Changing Single Elements

int[] numbers = {10, 2, 5, 40, 30, 100, 200};

numbers[0] = 3;

numbers[4] = 15;

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

{

System.out.printf("%d\n", numbers[i]);

}

• What will this code print?

31

Output:

Page 32: Arrays and Array Lists - University of Texas at Arlington

Changing Single Elements

int[] numbers = {10, 2, 5, 40, 30, 100, 200};

numbers[0] = 3;

numbers[4] = 15;

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

{

System.out.printf("%d\n", numbers[i]);

}

• What will this code print?

32

Output:

3

2

5

40

15

100

200

Page 33: Arrays and Array Lists - University of Texas at Arlington

Changing Single Elements

String[] str = new String[5];

str[2] = "Chicago";

str[3] = "New York";

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

{

System.out.printf("%s\n", str[i]);

}

• What will this code print?

33

Output:

Page 34: Arrays and Array Lists - University of Texas at Arlington

Changing Single Elements

String[] str = new String[5];

str[2] = "Chicago";

str[3] = "New York";

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

{

System.out.printf("%s\n", str[i]);

}

• What will this code print?

– str[0], str[1], str[4] have still not received valid values, so they print as null.

34

Output:

null

null

Chicago

New York

null

Page 35: Arrays and Array Lists - University of Texas at Arlington

Reading an Array from a User

• Write a program that:

– Asks the user to enter an integer N.

– Asks the user to enter N values, and stores them in an array.

– Prints out the values.

35

Example Output:

Enter N: 5

Enter value 0: 40

Enter value 1: 10

Enter value 2: 80

Enter value 3: 100

Enter value 4: 20

numbers[0] = 40

numbers[1] = 10

numbers[2] = 80

numbers[3] = 100

numbers[4] = 20

Page 36: Arrays and Array Lists - University of Texas at Arlington

import java.util.Scanner;

public class read_n_numbers {

public static void main(String[] args)

{

Scanner in = new Scanner(System.in);

System.out.printf("Enter N: ");

int N = in.nextInt();

int[] numbers = new int[N];

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

{

System.out.printf("Enter value %d: ", i);

numbers[i] = in.nextInt();

}

System.out.printf("\n");

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

{

System.out.printf("numbers[%d] = %d\n", i, numbers[i]);

}

}

} 36

A program that: • Reads N integers from the user. • Stores those integers in an array. • Prints the contents of the array.

Page 37: Arrays and Array Lists - University of Texas at Arlington

Reading an Array from a User

• Write a function that:

– Asks the user to enter an integer N.

– Asks the user to enter N values, and stores them in an array.

– Returns the array.

37

Page 38: Arrays and Array Lists - University of Texas at Arlington

Reading an Array from a User

• Write a function that:

– Asks the user to enter an integer N.

– Asks the user to enter N values, and stores them in an array.

– Returns the array.

38

public static int[] user_integers()

{

Scanner in = new Scanner(System.in);

System.out.printf("Enter N: ");

int N = in.nextInt();

int[] result = new int[N];

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

{

System.out.printf("Enter value %d: ", i);

result[i] = in.nextInt();

}

return result;

}

Page 39: Arrays and Array Lists - University of Texas at Arlington

Reading an Array from a User

• Using our user_integers function, the main function looks more simple:

39

Page 40: Arrays and Array Lists - University of Texas at Arlington

Reading an Array from a User

• Using our user_integers function, the main function looks more simple:

40

public static void main(String[] args)

{

int [] numbers = user_integers();

System.out.printf("\n");

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

{

System.out.printf("numbers[%d] = %d\n",

i, numbers[i]);

}

}

Page 41: Arrays and Array Lists - University of Texas at Arlington

Finding the Smallest Value

• Write a function find_min that:

– Takes as input an array of integers.

– Returns the smallest value among those integers.

41

Page 42: Arrays and Array Lists - University of Texas at Arlington

Finding the Smallest Value

• Write a function find_min that:

– Takes as input an array of integers.

– Returns the smallest value among those integers.

42

public static int find_min(int[] values)

{

int result = values[0];

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

{

if (values[i] < result)

{

result = values[i];

}

}

return result;

}

Page 43: Arrays and Array Lists - University of Texas at Arlington

Finding the Largest Value

• Write a function find_max that:

– Takes as input an array of integers.

– Returns the largest value among those integers.

43

Page 44: Arrays and Array Lists - University of Texas at Arlington

Finding the Largest Value

• Write a function find_max that:

– Takes as input an array of integers.

– Returns the largest value among those integers.

44

public static int find_max(int[] values)

{

int result = values[0];

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

{

if (values[i] > result)

{

result = values[i];

}

}

return result;

}

Page 45: Arrays and Array Lists - University of Texas at Arlington

An Example Program

• Write a program that:

– Asks the user to enter an integer N.

– Asks the user to enter N values, and stores them in an array.

– Prints out the values, indicating the maximum and the minimum.

45

Example Output:

Enter N: 5

Enter value 0: 40

Enter value 1: 10

Enter value 2: 80

Enter value 3: 90

Enter value 4: 20

numbers[0] = 40

numbers[1] = 10 *** smallest value ***

numbers[2] = 80

numbers[3] = 90 *** largest value ***

numbers[4] = 20

Page 46: Arrays and Array Lists - University of Texas at Arlington

46

public static void main(String[] args) {

int[] numbers = user_integers();

int smallest = find_min(numbers);

int largest = find_max(numbers);

System.out.printf("\n");

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

{

System.out.printf("numbers[%d] = %d", i, numbers[i]);

if (numbers[i] == smallest)

{

System.out.printf(" *** smallest value ***\n");

}

else if (numbers[i] == largest)

{

System.out.printf(" *** largest value ***\n");

}

else

{

System.out.printf("\n");

}

}

}

Page 47: Arrays and Array Lists - University of Texas at Arlington

Limitations of Arrays

• Consider a phone catalog program that:

– Allows the user to enter a new name and phone number.

– Stores names in a String array, and phones in another String array.

– Allows the user to search for a phone number, given a name.

• What should be the size of the arrays?

– We do not know in advance.

– This is a major limitation of arrays: we must know their size when we create them.

• How do we remove items from an array?

– Also not straightforward. 47

Page 48: Arrays and Array Lists - University of Texas at Arlington

Array Lists

• Array lists are an alternative to arrays in Java.

• They make it easy to:

– Initialize without specifying a size.

– Adding more elements and increasing the size.

– Removing elements.

– Inserting elements in the middle.

• Important: to use array lists, include this line at the top of your code:

import java.util.ArrayList;

48

Page 49: Arrays and Array Lists - University of Texas at Arlington

Example: An Array List of Integers

• Creating a new array list of integers: see red line.

– Note: no need to specify size, initial size is 0.

49

public static ArrayList<Integer> user_integers() {

Scanner in = new Scanner(System.in);

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

while(true)

{

System.out.printf("Enter a number, or q to quit: ");

String input = in.next();

if (input.equals("q"))

{

return result;

}

int number = Integer.parseInt(input);

result.add(number);

}

}

Page 50: Arrays and Array Lists - University of Texas at Arlington

Example: An Array List of Integers

• Adding a new number to the array: see red line.

– Use the add method.

50

public static ArrayList<Integer> user_integers() {

Scanner in = new Scanner(System.in);

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

while(true)

{

System.out.printf("Enter a number, or q to quit: ");

String input = in.next();

if (input.equals("q"))

{

return result;

}

int number = Integer.parseInt(input);

result.add(number);

}

}

Page 51: Arrays and Array Lists - University of Texas at Arlington

Example: An Array List of Integers

• Getting the size of an array list: see red line.

– Use the size method.

51

public static void main(String[] args)

{

ArrayList<Integer> numbers = user_integers();

System.out.printf("\n");

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

{

System.out.printf("position %d: = %d\n", i, numbers.get(i));

}

}

Page 52: Arrays and Array Lists - University of Texas at Arlington

Example: An Array List of Integers

• Accessing elements of the array list: see red line.

– Use the get method.

52

public static void main(String[] args)

{

ArrayList<Integer> numbers = user_integers();

System.out.printf("\n");

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

{

System.out.printf("position %d: = %d\n", i, numbers.get(i));

}

}

Page 53: Arrays and Array Lists - University of Texas at Arlington

Finding the Smallest Value

• Write a function find_min that:

– Takes as input an array list of integers.

– Returns the smallest value among those integers.

53

Solution for arrays:

public static int find_min(int[] values)

{

int result = values[0];

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

{

if (values[i] < result)

{

result = values[i];

}

}

return result;

}

Page 54: Arrays and Array Lists - University of Texas at Arlington

Finding the Smallest Value

• Write a function find_min that:

– Takes as input an array list of integers.

– Returns the smallest value among those integers.

54

Solution for array lists:

public static int

find_min(ArrayList<Integer> values)

{

int result = values.get(0);

for (int i = 0; i < values.size(); i++)

{

if (values.get(i) < result)

{

result = values.get(i);

}

}

return result;

}

Page 55: Arrays and Array Lists - University of Texas at Arlington

Finding the Largest Value

• Write a function find_max that:

– Takes as input an array list of integers.

– Returns the largest value among those integers.

55

Solution for array lists:

public static int

find_max(ArrayList<Integer> values)

{

int result = values.get(0);

for (int i = 0; i < values.size(); i++)

{

if (values.get(i) > result)

{

result = values.get(i);

}

}

return result;

}

Page 56: Arrays and Array Lists - University of Texas at Arlington

An Example Program

• Write a program that:

– Asks the user to enter some integers, and stores them in an array list.

– Prints out the values, indicating the maximum and the minimum.

56

Example Output:

Enter a number, or q to quit: 40

Enter a number, or q to quit: 10

Enter a number, or q to quit: 80

Enter a number, or q to quit: 90

Enter a number, or q to quit: 20

Enter a number, or q to quit: q

position 0: 40

position 1: 10 *** smallest value ***

position 2: 80

position 3: 90 *** largest value ***

position 4: 20

Page 57: Arrays and Array Lists - University of Texas at Arlington

57

public static void main(String[] args) {

ArrayList<Integer> numbers = user_integers();

int smallest = find_min(numbers);

int largest = find_max(numbers);

System.out.printf("\n");

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

{

System.out.printf("position %d: %d", i, numbers.get(i));

if (numbers.get(i) == smallest)

{

System.out.printf(" *** smallest value ***\n");

}

else if (numbers.get(i) == largest)

{

System.out.printf(" *** largest value ***\n");

}

else

{

System.out.printf("\n");

}

}

}

Page 58: Arrays and Array Lists - University of Texas at Arlington

Printing Array Lists with println

• println can be used to print out an entire array list.

58 Output: [Chicago, New York, Dallas, Denver]

import java.util.Scanner;

import java.util.ArrayList;

public class example1 {

public static void main(String[] args) {

ArrayList<String> list = new ArrayList<String>();

list.add("Chicago");

list.add("New York");

list.add("Dallas");

list.add("Denver");

System.out.println(list);

}

}

Page 59: Arrays and Array Lists - University of Texas at Arlington

Changing a Value in an Array List

• set(position, value) can be used to change a value.

59 Output: ???

import java.util.Scanner;

import java.util.ArrayList;

public class example1 {

public static void main(String[] args) {

ArrayList<String> list = new ArrayList<String>();

list.add("Chicago");

list.add("New York");

list.add("Dallas");

list.set(1, "Denver");

System.out.println(list);

}

}

Page 60: Arrays and Array Lists - University of Texas at Arlington

Changing a Value in an Array List

• set(position, value) can be used to change a value.

60 Output: [Chicago, Denver, Dallas]

import java.util.Scanner;

import java.util.ArrayList;

public class example1 {

public static void main(String[] args) {

ArrayList<String> list = new ArrayList<String>();

list.add("Chicago");

list.add("New York");

list.add("Dallas");

list.set(1, "Denver");

System.out.println(list);

}

}

Page 61: Arrays and Array Lists - University of Texas at Arlington

• remove(pos) removes the value at position pos.

61 Output: ???

import java.util.Scanner;

import java.util.ArrayList;

public class example1 {

public static void main(String[] args) {

ArrayList<String> list = new ArrayList<String>();

list.add("Chicago");

list.add("New York");

list.add("Dallas");

list.remove(1);

System.out.println(list);

}

}

Removing a Value from an Array List

Page 62: Arrays and Array Lists - University of Texas at Arlington

• remove(pos) removes the value at position pos.

62 Output: [Chicago, Dallas]

import java.util.Scanner;

import java.util.ArrayList;

public class example1 {

public static void main(String[] args) {

ArrayList<String> list = new ArrayList<String>();

list.add("Chicago");

list.add("New York");

list.add("Dallas");

list.remove(1);

System.out.println(list);

}

}

Removing a Value from an Array List

Page 63: Arrays and Array Lists - University of Texas at Arlington

• IMPORTANT: remove(pos) shifts the positions of all elements after position pos.

63 position 1: ???

import java.util.Scanner;

import java.util.ArrayList;

public class example1 {

public static void main(String[] args) {

ArrayList<String> list = new ArrayList<String>();

list.add("Chicago");

list.add("New York");

list.add("Dallas");

list.remove(1);

System.out.printf("position 1: %s\n", list.get(1));

}

}

Removing a Value from an Array List

Page 64: Arrays and Array Lists - University of Texas at Arlington

Removing a Value from an Array List

• IMPORTANT: remove(pos) shifts the positions of all elements after position pos.

64

import java.util.Scanner;

import java.util.ArrayList;

public class example1 {

public static void main(String[] args) {

ArrayList<String> list = new ArrayList<String>();

list.add("Chicago");

list.add("New York");

list.add("Dallas");

list.remove(1);

System.out.printf("position 1: %s\n", list.get(1));

}

}

position 1: Dallas

After remove, Dallas moved from position2 to position 1.

Page 65: Arrays and Array Lists - University of Texas at Arlington

Inserting a Value to an Array List

• We have seen add(value), which adds a value to the end of the list.

• There is a second version of add, with two arguments.

• add(pos, value) inserts the value at position pos.

65

Page 66: Arrays and Array Lists - University of Texas at Arlington

Inserting a Value to an Array List

• add(pos, value) inserts the value at position pos.

66

import java.util.Scanner;

import java.util.ArrayList;

public class example1 {

public static void main(String[] args) {

ArrayList<String> list = new ArrayList<String>();

list.add("Chicago");

list.add("New York");

list.add("Dallas");

list.add(1, "Miami");

System.out.println(list);

}

}

Output: ???

Page 67: Arrays and Array Lists - University of Texas at Arlington

Inserting a Value to an Array List

• add(pos, value) inserts the value at position pos.

67

import java.util.Scanner;

import java.util.ArrayList;

public class example1 {

public static void main(String[] args) {

ArrayList<String> list = new ArrayList<String>();

list.add("Chicago");

list.add("New York");

list.add("Dallas");

list.add(1, "Miami");

System.out.println(list);

}

}

Output: [Chicago, Miami, New York, Dallas]

Page 68: Arrays and Array Lists - University of Texas at Arlington

Inserting a Value to an Array List

• IMPORTANT: add(value, pos) shifts the positions of all elements after position pos.

68

import java.util.Scanner;

import java.util.ArrayList;

public class example1 {

public static void main(String[] args) {

ArrayList<String> list = new ArrayList<String>();

list.add("Chicago");

list.add("New York");

list.add("Dallas");

list.add(1, "Miami");

System.out.println(list);

}

}

After adding Miami, Dallas moved from position 2 to position 3.

Output: [Chicago, Miami, New York, Dallas]

Page 69: Arrays and Array Lists - University of Texas at Arlington

Variables Pointing to Same Set

• This topic is a VERY COMMON SOURCE OF MISUNDERSTANDINGS.

• When two array (or array list) variables are set equal to each other, they are fundamentally linked:

– They both refer to the same set of values. • In computer science, we say that they are both pointers, pointing

to the same set of values.

– Any modification to that set of values affects all the variables that point to it.

• The only way to break that link, is to assign an array (or array list) variable to some other value.

• It is important to identify (and treat separately) assignments of array variables vs. modifications. 69

Page 70: Arrays and Array Lists - University of Texas at Arlington

Sharing of Modifications: Example

• What will this program print?

70

public class assignments

{

public static void main(String[] args)

{

int[] a = {10, 20, 30, 40};

int[] b = a;

b[2] = 7;

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

{

System.out.printf("a[%d] = %d\n", i, a[i]);

}

}

}

Output:

Page 71: Arrays and Array Lists - University of Texas at Arlington

Sharing of Modifications: Example

• What will this program print?

71

public class assignments

{

public static void main(String[] args)

{

int[] a = {10, 20, 30, 40};

int[] b = a;

b[2] = 7;

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

{

System.out.printf("a[%d] = %d\n", i, a[i]);

}

}

}

Output:

a[0] = 10

a[1] = 20

a[2] = 7

a[3] = 40

Page 72: Arrays and Array Lists - University of Texas at Arlington

Sharing of Modifications: Example

• Is the red line an assignment or a modification of an array variable?

72

public class assignments

{

public static void main(String[] args)

{

int[] a = {10, 20, 30, 40};

int[] b = a;

b[2] = 7;

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

{

System.out.printf("a[%d] = %d\n", i, a[i]);

}

}

}

Output:

a[0] = 10

a[1] = 20

a[2] = 7

a[3] = 40

Page 73: Arrays and Array Lists - University of Texas at Arlington

Sharing of Modifications: Example

• Is the red line an assignment or a modification of an array variable? – Assignment: b is set equal to a. Variables a and b point to the same set.

73

public class assignments

{

public static void main(String[] args)

{

int[] a = {10, 20, 30, 40};

int[] b = a;

b[2] = 7;

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

{

System.out.printf("a[%d] = %d\n", i, a[i]);

}

}

}

Output:

a[0] = 10

a[1] = 20

a[2] = 7

a[3] = 40

Page 74: Arrays and Array Lists - University of Texas at Arlington

Sharing of Modifications: Example

• Is the red line an assignment or a modification of an array variable?

74

public class assignments

{

public static void main(String[] args)

{

int[] a = {10, 20, 30, 40};

int[] b = a;

b[2] = 7;

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

{

System.out.printf("a[%d] = %d\n", i, a[i]);

}

}

}

Output:

a[0] = 10

a[1] = 20

a[2] = 7

a[3] = 40

Page 75: Arrays and Array Lists - University of Texas at Arlington

Sharing of Modifications: Example

• Is the red line an assignment or a modification of an array variable? – Modification: array variable b is not assigned a value, just b[2] is modified.

– This means that a[2] is now also equal to the new value.

75

public class assignments

{

public static void main(String[] args)

{

int[] a = {10, 20, 30, 40};

int[] b = a;

b[2] = 7;

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

{

System.out.printf("a[%d] = %d\n", i, a[i]);

}

}

}

Output:

a[0] = 10

a[1] = 20

a[2] = 7

a[3] = 40

Page 76: Arrays and Array Lists - University of Texas at Arlington

Another Example

• What will this program print?

76

public class assignments {

public static void main(String[] args)

{

int[] a = {10, 20, 30, 40};

int[] b = a;

int[] c = {4, 3, 2};

b[2] = 7;

b = c;

b[1] = 15;

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

{

System.out.printf("a[%d] = %d\n", i, a[i]);

}

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

{

System.out.printf("c[%d] = %d\n", i, c[i]);

}

}

}

Output:

Page 77: Arrays and Array Lists - University of Texas at Arlington

Another Example

• What will this program print?

77

public class assignments {

public static void main(String[] args)

{

int[] a = {10, 20, 30, 40};

int[] b = a;

int[] c = {4, 3, 2};

b[2] = 7;

b = c;

b[1] = 15;

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

{

System.out.printf("a[%d] = %d\n", i, a[i]);

}

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

{

System.out.printf("c[%d] = %d\n", i, c[i]);

}

}

}

Output:

a[0] = 10

a[1] = 20

a[2] = 7

a[3] = 40

c[0] = 4

c[1] = 15

c[2] = 2

Page 78: Arrays and Array Lists - University of Texas at Arlington

Another Example

• Line-by-line execution

78

public class assignments {

public static void main(String[] args)

{

int[] a = {10, 20, 30, 40};

int[] b = a;

int[] c = {4, 3, 2};

b[2] = 7;

b = c;

b[1] = 15;

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

{

System.out.printf("a[%d] = %d\n", i, a[i]);

}

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

{

System.out.printf("c[%d] = %d\n", i, c[i]);

}

}

}

Variables:

a

Page 79: Arrays and Array Lists - University of Texas at Arlington

Another Example

• Line-by-line execution – Assignment of

array variable.

79

public class assignments {

public static void main(String[] args)

{

int[] a = {10, 20, 30, 40};

int[] b = a;

int[] c = {4, 3, 2};

b[2] = 7;

b = c;

b[1] = 15;

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

{

System.out.printf("a[%d] = %d\n", i, a[i]);

}

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

{

System.out.printf("c[%d] = %d\n", i, c[i]);

}

}

}

Variables:

a {10,20,30,40}

Page 80: Arrays and Array Lists - University of Texas at Arlington

Another Example

• Line-by-line execution – Assignment of

array variable.

80

public class assignments {

public static void main(String[] args)

{

int[] a = {10, 20, 30, 40};

int[] b = a;

int[] c = {4, 3, 2};

b[2] = 7;

b = c;

b[1] = 15;

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

{

System.out.printf("a[%d] = %d\n", i, a[i]);

}

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

{

System.out.printf("c[%d] = %d\n", i, c[i]);

}

}

}

Understanding this line is the key: We should NOT represent this as: a = {10, 20, 30, 40} b = {10, 20, 30, 40}

Variables:

a {10,20,30,40}

b

Page 81: Arrays and Array Lists - University of Texas at Arlington

Another Example

• Line-by-line execution – Assignment of

array variable.

81

public class assignments {

public static void main(String[] args)

{

int[] a = {10, 20, 30, 40};

int[] b = a;

int[] c = {4, 3, 2};

b[2] = 7;

b = c;

b[1] = 15;

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

{

System.out.printf("a[%d] = %d\n", i, a[i]);

}

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

{

System.out.printf("c[%d] = %d\n", i, c[i]);

}

}

}

Variables:

a {10,20,30,40}

b

c {4, 3, 2}

Page 82: Arrays and Array Lists - University of Texas at Arlington

Another Example

• Line-by-line execution – Modification of

array.

82

public class assignments {

public static void main(String[] args)

{

int[] a = {10, 20, 30, 40};

int[] b = a;

int[] c = {4, 3, 2};

b[2] = 7;

b = c;

b[1] = 15;

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

{

System.out.printf("a[%d] = %d\n", i, a[i]);

}

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

{

System.out.printf("c[%d] = %d\n", i, c[i]);

}

}

}

Variables:

a {10,20,7,40}

b

c {4, 3, 2}

Since a and b point to the same array, it is clear that changing b changes a at the same time.

Page 83: Arrays and Array Lists - University of Texas at Arlington

Another Example

• Line-by-line execution – Assignment of

array variable.

83

public class assignments {

public static void main(String[] args)

{

int[] a = {10, 20, 30, 40};

int[] b = a;

int[] c = {4, 3, 2};

b[2] = 7;

b = c;

b[1] = 15;

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

{

System.out.printf("a[%d] = %d\n", i, a[i]);

}

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

{

System.out.printf("c[%d] = %d\n", i, c[i]);

}

}

}

Variables:

a {10,20,7,40}

b

c {4, 3, 2}

Again, we should NOT represent this as:

b = {4, 3, 2} c = {4, 3, 2}

Page 84: Arrays and Array Lists - University of Texas at Arlington

Another Example

• Line-by-line execution – Modification of

array.

84

public class assignments {

public static void main(String[] args)

{

int[] a = {10, 20, 30, 40};

int[] b = a;

int[] c = {4, 3, 2};

b[2] = 7;

b = c;

b[1] = 15;

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

{

System.out.printf("a[%d] = %d\n", i, a[i]);

}

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

{

System.out.printf("c[%d] = %d\n", i, c[i]);

}

}

}

Variables:

a {10,20,7,40}

b

c {4, 15, 2}

Since b and c point to the same array, it is clear that changing b changes c at the same time.

Page 85: Arrays and Array Lists - University of Texas at Arlington

Important

• When you assign a value to an array (or array list) variable, you create new arrows, or change where the arrows point.

• When you modify an array (or array list), the arrows are not changed.

85

public class assignments {

public static void main(String[] args)

{

int[] a = {10, 20, 30, 40};

int[] b = a;

int[] c = {4, 3, 2};

b[2] = 7;

b = c;

b[1] = 15;

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

{

System.out.printf("a[%d] = %d\n", i, a[i]);

}

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

{

System.out.printf("c[%d] = %d\n", i, c[i]);

}

}

}

Variables:

a {10,20,7,40}

b

c {4, 15, 2}

Page 86: Arrays and Array Lists - University of Texas at Arlington

Another Example

• What does this print?

86

public class example1 {

public static void foo(int[] x)

{

x[2] = 0;

}

public static void main(String[] args)

{

int[] a = {10, 20, 30, 40};

foo(a);

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

{

System.out.printf("a[%d] = %d\n", i, a[i]);

}

}

}

Output:

Page 87: Arrays and Array Lists - University of Texas at Arlington

Another Example

• What does this print?

87

public class example1 {

public static void foo(int[] x)

{

x[2] = 0;

}

public static void main(String[] args)

{

int[] a = {10, 20, 30, 40};

foo(a);

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

{

System.out.printf("a[%d] = %d\n", i, a[i]);

}

}

}

Output:

a[0] = 10

a[1] = 20

a[2] = 0

a[3] = 40

Page 88: Arrays and Array Lists - University of Texas at Arlington

Variables Pointing to Same Set (Recap)

• When two array (or array list) variables are set equal to each other, they point to the same underlying array (or array list): – Any modification to values of that array (or array list) affects all the

variables that point to it.

• The only way to break the link between two array (or array list) variables, is to assign an array (or array list) variable to some other value.

• Given a line of code involving an array (or array list) variable, we should be able to identify: – Does this line assign a value to the array (or array list) variable?

– Does this line simply modify one or more positions of the array?

• These two cases are different, and follow different rules.

88

Page 89: Arrays and Array Lists - University of Texas at Arlington

2D Arrays

• You can have arrays of arrays.

– These are called 2-dimensional arrays, or matrices.

– You can have arrays of arrays of arrays of arrays …

• Example:

89

public class example1 {

public static void main(String[] args)

{

double[][] a = { {3.2, 2.1, 5.3},

{8.0, 4.9, 5.7} };

a[1][0] = 2;

System.out.printf("%.1f\n", a[0][0]);

System.out.printf("%.1f\n", a[1][0]);

System.out.printf("%.1f\n", a[1][1]);

}

}