Date post: | 16-Jan-2016 |
Category: |
Documents |
Upload: | leona-dalton |
View: | 231 times |
Download: | 0 times |
1
Arrays and Array Lists
CSE 1310 – Introduction to Computers and ProgrammingVassilis Athitsos
University of Texas at Arlington
2
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:
3
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.
4
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:
5
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).
6
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:
7
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.
8
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).
9
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
10
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.
11
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++).
12
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.
13
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";…
14
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;…
15
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);…
16
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};
17
A First Example• Printing out months and lengths is easy, using a loop.
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]); } }}
18
Why Is the Array Solution Better?
19
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]);
20
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.
21
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.
22
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.
23
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 ???
24
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.
25
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 ???.
26
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.
27
Accessing Single Elements
int[] numbers = {10, 2, 5, 40, 30, 100, 200}; int a = numbers[7];
• The above code will do what?
28
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.
29
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.
30
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.
31
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?
Output:
32
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?
Output:
3254015100200
33
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?
Output:
34
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.
Output:
nullnullChicagoNew Yorknull
35
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.
Example Output:
Enter N: 5Enter value 0: 40Enter value 1: 10Enter value 2: 80Enter value 3: 100Enter value 4: 20
numbers[0] = 40numbers[1] = 10numbers[2] = 80numbers[3] = 100numbers[4] = 20
36
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]); } }}
A program that:• Reads N integers from the user.• Stores those integers in an array.• Prints the contents of the array.
37
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
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.
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; }
39
Reading an Array from a User
• Using our user_integers function, the main function looks more simple:
40
Reading an Array from a User
• Using our user_integers function, the main function looks more simple:
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]); }}
41
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
Finding the Smallest Value
• Write a function find_min that:– Takes as input
an array of integers.
– Returns the smallest value among those integers.
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;}
43
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
Finding the Largest Value
• Write a function find_max that:– Takes as input
an array of integers.
– Returns the largest value among those integers.
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;}
45
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.
Example Output:
Enter N: 5Enter value 0: 40Enter value 1: 10Enter value 2: 80Enter value 3: 90Enter value 4: 20
numbers[0] = 40numbers[1] = 10 *** smallest value ***numbers[2] = 80numbers[3] = 90 *** largest value ***numbers[4] = 20
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"); } }}
47
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.
48
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;
49
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.
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); }}
50
Example: An Array List of Integers• Adding a new number to the array: see red line.
– Use the add method.
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); }}
51
Example: An Array List of Integers• Getting the size of an array list: see red line.
– Use the size method.
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)); }}
52
Example: An Array List of Integers• Accessing elements of the array list: see red line.
– Use the get method.
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)); }}
53
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.
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;}
54
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.
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;}
55
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.
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;}
56
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.
Example Output:
Enter a number, or q to quit: 40Enter a number, or q to quit: 10Enter a number, or q to quit: 80Enter a number, or q to quit: 90Enter a number, or q to quit: 20Enter a number, or q to quit: q
position 0: 40position 1: 10 *** smallest value ***position 2: 80position 3: 90 *** largest value ***position 4: 20
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"); } }}
58
Printing Array Lists with println• println can be used to print out an entire array list.
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); }}
59
Changing a Value in an Array List• set(position, value) can be used to change a value.
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); }}
60
Changing a Value in an Array List• set(position, value) can be used to change a value.
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); }}
61
Removing a Value in an Array List• remove(pos) removes the value at position pos.
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); }}
62
Removing a Value in an Array List• remove(pos) removes the value at position pos.
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); }}
63
Removing a Value in an Array List• IMPORTANT: remove(pos) shifts the positions of all elements
after position pos.
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)); }}
64
Removing a Value in an Array List• IMPORTANT: remove(pos) shifts the positions of all elements
after position pos.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: DallasAfter remove, Dallas moved from position2 to position 1.
65
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.
66
Sharing of Modifications: Example• What will this program print?
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:
67
Sharing of Modifications: Example• What will this program print?
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] = 10a[1] = 20a[2] = 7a[3] = 40
68
Sharing of Modifications: Example• Is the red line an assignment or a modification of an array variable?
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] = 10a[1] = 20a[2] = 7a[3] = 40
69
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.
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] = 10a[1] = 20a[2] = 7a[3] = 40
70
Sharing of Modifications: Example• Is the red line an assignment or a modification of an array variable?
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] = 10a[1] = 20a[2] = 7a[3] = 40
71
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.
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] = 10a[1] = 20a[2] = 7a[3] = 40
72
Another Example
• What will this program print?
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:
73
Another Example
• What will this program print?
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] = 10a[1] = 20a[2] = 7a[3] = 40c[0] = 4c[1] = 15c[2] = 2
74
Another Example
• Line-by-line execution
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
75
Another Example
• Line-by-line execution– Assignment of
array variable.
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}
76
Another Example
• Line-by-line execution– Assignment of
array variable.
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
77
Another Example
• Line-by-line execution– Assignment of
array variable.
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}bc {4, 3, 2}
78
Another Example
• Line-by-line execution– Modification of
array.
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}bc {4, 3, 2}
Since a and b point to the same array, it is clear that changing b changes a at the same time.
79
Another Example
• Line-by-line execution– Assignment of
array variable.
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}bc {4, 3, 2}
Again, we should NOT represent this as:
b = {4, 3, 2} c = {4, 3, 2}
80
Another Example
• Line-by-line execution– Modification of
array.
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}bc {4, 15, 2}
Since b and c point to the same array, it is clear that changing b changes c at the same time.
81
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.
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}bc {4, 15, 2}
82
Another Example
• What does this print?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:
83
Another Example
• What does this print?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] = 10a[1] = 20a[2] = 0a[3] = 40
84
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.
85
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: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]); } }