CS300 Fall 2024 - Array Basics PDF

Summary

This document introduces array basics, covering how to create arrays using initializer list and new methods, along with access, modification, iteration, output, etc. This document is a learning resource.

Full Transcript

Learning Objectives: Array Basics Create an array using both the initializer list and new methods Access and modify array elements Iterate through arrays using both a regular for loop and an enhanced for loop Determine array output Creating an Array What Is an Array? An array is a data s...

Learning Objectives: Array Basics Create an array using both the initializer list and new methods Access and modify array elements Iterate through arrays using both a regular for loop and an enhanced for loop Determine array output Creating an Array What Is an Array? An array is a data structure that stores a collection of data such as ints, doubles, Strings, etc. This data is often referred to as the array’s elements. Being able to store elements into an array helps reduce the amount of time needed to declare and initialize variables. For example, if you wanted to store the names of all family members in your household, you would typically have to declare and initialize String variables and values for each family member. Copy the code below into the text editor on the left and then click the TRY IT button to see the output. You can also click on the ++Code Visualizer++ link underneath to see how the program runs behind the scenes. String a = "Alan"; String b = "Bob"; String c = "Carol"; String d = "David"; String e = "Ellen"; System.out.println(a); challenge What happens if you: Change the a in System.out.println(a) to b, c, d, or e? Array Creation To avoid the repetitive task of declaring and initializing multiple variables, you can declare an array and directly assign values or elements into that array like below. This technique is referred to as the initializer list method. String[] names = {"Alan", "Bob", "Carol", "David", "Ellen"}; “Initializer List” Method Syntax: Specify the data type that the array will store (i.e. String) followed by empty brackets []. Declare the variable name for the array (i.e. names) followed by the assignment symbol =. Elements assigned to the array are separated by commas , and enclosed within curly braces {}. Additional information If you used the Code Visualizer, you’ll notice that the array variable names refers to all of the elements as a collection. An array is considered to be an object that bundles all of the data that it holds. Note that the first array slot, or index, is always 0 so Alan is located at index 0 instead of 1. Alternatively, you can create an array using the new method in which you will need to declare and specify the array variable and length before you can assign elements to the array. String[] names = new String; “New” Method Syntax Specify the data type that the array will store (i.e. String) followed by empty brackets []. Declare the variable name for the array (i.e. names) followed by the assignment symbol =. Declare the keyword new followed by the data type (i.e. String) and number of elements in brackets (i.e. ). Additional information If you used the Code Visualizer, you’ll notice that the array variable names refers to all of the elements as a collection. null appears in all of the array slots because no elements have been assigned to them yet. Note that the first array slot, or index, is always 0. Array Details Both the initializer list and new methods mentioned above will store five elements in the array called names. However, the new method automatically initializes each element to a default value of null while the initializer list method does not. Note that array slots are formally called indices and each index can carry just one type of data. For example, storing an int of 5 into a String array will result in a error. P.O. Boxes at the postal office is symbolically similar to arrays. Each row of P.O. Boxes is like an array, except each box can only store one item (element) and each item within that row must be of the same type (i.e. Strings). The position at which each box is located is its index..guides/img/ArrayElementsIndices Oversize and Perfect Size Arrays Perfect size arrays A perfect size array is an array where the number of elements is equal to the memory allocated. (These are almost certainly the variety of array that you’re already familiar with.) For example, the maximum daily temperature for a week could be stored in an array with 7 integer values. Perfect size arrays can be created using an initializer, which sets both the array’s length and initializes each element in the array to given values: int[] highTempsF = {93, 80, 62, 75, 74, 89, 97}; Perfect size arrays of objects may contain null values. When to use perfect size arrays Perfect size arrays are especially useful when the size of the array is fixed by the context of the program. Storing the names of the days of the week in a perfect size array makes sense because the number of days in a week will not change. Compare this to an array that contains the list of cities where a company has locations – companies may add or remove locations over time, so this is not a great candidate for a perfect size array. Methods with perfect size array parameters Perfect size arrays are passed to methods using only the array’s reference (its location in heap memory). The number of elements and data are accessed from that array reference. Consider this method to store the given value at each element of the array: public static void fill(int[] arrayReference, int value) { int index; for (int index = 0; index < arrayReference.length; ++index) { arrayReference[index] = value; } } When an array reference is passed to a method, the method can update the contents of the original array AND those updates will persist after the method has completed, without needing to return a value (note that the return type of fill() is void). Methods returning perfect size arrays Methods can also return perfect size array references. Since methods can only return one value, a method returning an array MUST return a perfect size array! Oversize arrays An oversize array is an array where the number of elements used at any given time in the program is less than or equal to the memory allocated for the array (that is, its length). Since the number of elements (the size) of an oversize array can be less than the array’s length, we use a separate integer variable to keep track of how many elements are currently used. This is an example of an empty oversize array: int[] programScores = new int; int programScoresSize = 0; Since you haven’t completed any programming assignments yet this semester, the array only contains its default values. As the semester progresses, you may add more data to this array, and increase the corresponding size variable accordingly. Oversize array protocols There is nothing inherent to Java that enforces the rules of oversize arrays; these are a set of protocols that programmers agree to follow to make oversize array usage predictable: 1. Oversize arrays consist of an initialized array reference and an integer size variable. 2. Oversize arrays must be compact; that is, initialized values in an oversize array are present from index 0 to index size-1 with no gaps. This means that any data outside of the index range [0 - (size-1)] is considered “junk data”. Oversize arrays vs perfect size arrays Let’s compare the usage of these two standards of array maintenance. In each of the following questions, select the variable type that best matches the stated application. Accessing an Array Array Access To access and print array elements, you need to know their position. The position at which an element is stored is called its index. For example, numbers refers to the first element in the array called numbers. Array indices always start at 0 and increment by 1 with each element that comes next. Due to this, numbers refers to the fifth element in the array, not the fourth. int[] numbers = {1, 2, 3, 4, 5}; System.out.println(numbers); challenge What happens if you: Change numbers in the code above to numbers? Change numbers in the code above to numbers? Change numbers in the code above to numbers? important IMPORTANT You may have noticed that printing the numbers array without specifying an index resulted in an output that starts with [I@… This occurs because printing an array actually prints its memory location, not its elements. You’ll learn how to print all elements in an array without having to specify all of their indices on a later page. Default “New” Elements When using the new method to create an array, there are default values that populate as elements inside of the array, depending on the array type. For example, String[] words = new String will result in five null elements and int[] numbers = new int will populate five elements of 0s within the array. Below is a table showing the default values of different array types when the “new” method is used. Data Type Default Value String null int 0 double 0.0 boolean false double[] decimals = new double; boolean[] bools = new boolean; System.out.println(decimals); System.out.println(bools); challenge What happens if you: Change decimals in the code above to decimals? Change bools in the code above to bools? Change decimals in the code above to decimals? Change bools in the code above to bools? IndexOutOfBounds Error A common error that occurs is called the ArrayIndexOutOfBoundsException error. This happens when you try to access or print an element at an index that does not exist within the array. In the example above, decimals and bools both resulted in an ArrayIndexOutOfBoundsException because neither array has an index of 2. Both arrays have only indices and to hold their elements..guides/img/ArrayException Modifying an Array Array Modification To modify an element within an array, simply find the index at which that element is stored and assign a new value to it. int[] grades = {85, 95, 48, 100, 92}; System.out.println(grades); grades = 88; //88 will replace 48 at index 2 System.out.println(grades); challenge What happens if you: Change int[] grades = {85, 95, 48, 100, 92}; in the code above to int[] grades = new int;? Change all System.out.println(grades); in the code above to System.out.println(grades);? Change grades = 88; in the code above to grades = 100;? Modifying Multiple Arrays You can create and modify as many arrays as you’d like. For example, you can create an array to store your family members and another array to store their age. String[] family = {"Dad", "Mom", "Brother", "Sister"}; int[] age = new int; System.out.println(family + " " + age); System.out.println(family + " " + age); System.out.println(family + " " + age); System.out.println(family + " " + age); challenge What happens if you: Add age = 50; directly below the line int[] age = new int;? Add age = 45; below the line int[] age = new int; but before the print statements? Add age = 25; below the line int[] age = new int; but before the print statements? Add age = 20; below the line int[] age = new int; but before the print statements? Change "Sister" within the String array to "Brother2"? important IMPORTANT Since the integer array above was created using the new method, 0 was populated as elements within the array at first. Then by setting the array indices to specific values, you were able to modify the array to include the appropriate age for each family member. Iterating an Array Array Iteration Though we can add many elements to our array, printing each of them can get quite tedious. For example, if we have 10 names of friends in our array, we would need to specify each of their array index to print them. String[] friends = {"Alan", "Bob", "Carol", "David", "Ellen", "Fred", "Grace", "Henry", "Ian", "Jen"}; System.out.println(friends); System.out.println(friends); System.out.println(friends); System.out.println(friends); System.out.println(friends); System.out.println(friends); System.out.println(friends); System.out.println(friends); System.out.println(friends); System.out.println(friends); Luckily, we can use loops which we had learned previously to help us with this process. To print out all of our friends’ names without repeating the print statement ten times, we can use a for loop to iterate 10 times. String[] friends = {"Alan", "Bob", "Carol", "David", "Ellen", "Fred", "Grace", "Henry", "Ian", "Jen"}; for (int i = 0; i < 10; i++) { System.out.println(friends[i]); } challenge What happens if you: Change System.out.println(friends[i]); in the code above to System.out.println(friends);? Change System.out.println(friends[i]); in the code above to System.out.println(friends);? important IMPORTANT Did you notice that the print statement above includes i as the index for friends? We do this because i will take on the values specified by the for loop. The loop starts at 0 and increments by 1 until it reaches 9 (not including 10). Thus, friends will print, then friends, so on and so forth until friends is printed. Then the loop ends. Array Length To make the iteration process easier, we can use an instance variable called length to determine how many elements are in our array. To use length, just call it by adding a period. after our array followed by length. For example, friends.length will tell us how many elements are in our friends array. The advantage of using length is that we can initialize additional elements in our array without having to keep track of how many elements are already inside. String[] friends = {"Alan", "Bob", "Carol", "David", "Ellen", "Fred", "Grace", "Henry", "Ian", "Jen"}; for (int i = 0; i < friends.length; i++) { System.out.println(friends[i]); } challenge What happens if you: add "Kate" as an element to the array right after "Jen"? remove "Alan" and "Bob" from the array? Notice how friends.length continues to keep track of how many elements are in our array even though we’ve made several changes. Enhanced For-Loop Using an Enhanced For-Loop There is a special type of for loop that can be used with arrays called an enhanced for loop. An enhanced for loop, also known as a for each loop, can be used to iterate through array elements without having to refer to any array indices. To use an enhanced for loop, you need the following: * The keyword for followed by parentheses (). * A typed iterating variable followed by colon : followed by the array name. * Note that the iterating variable must be of the same type as the array. * Any commands that repeat within curly braces {}. * Note that when using an enhanced for loop, you can print the iterating variable itself without using brackets []. String[] friends = {"Alan", "Bob", "Carol", "David", "Ellen", "Fred", "Grace", "Henry", "Ian", "Jen"}; for (String i : friends) { System.out.println(i); } challenge What happens if you: change System.out.println(i); in the code above to System.out.println(friends[i]);? change String i in the code above to int i? important IMPORTANT One of the main differences between a regular for loop and an enhanced for loop is that an enhanced for loop does not refer to any index or position of the elements in the array. Thus, if you need to access or modify array elements, you cannot use an enhanced for loop. In addition, you cannot use an enhanced for loop to iterate through a part of the array. Think of an enhanced for loop as an all-or- nothing loop that just prints all of the array elements or nothing at all. Also note that the iterating variable type must match the array type. For example, you cannot use for (int i : friends) since friends is a String array and i is an integer variable. Use for (String i : friends) instead. Helpful Array Algorithms Array Algorithms In addition to being used with loops, arrays can also be used with conditionals to help with tasks such as searching for a particular element, finding a minimum or maximum element, or printing elements in reverse order. Searching for a Particular Element String[] cars = {"Corolla", "Camry", "Prius", "RAV4", "Highlander"}; String Camry = "A Camry is not available."; //default String value for (String s : cars) { //enhanced for loop if (s.equals("Camry")) { //if "Camry" is in array Camry = "A Camry is available."; //variable changes if "Camry" exists } } System.out.println(Camry); //print whether Camry exists or not challenge What happens if you: delete "Camry" from the cars array? try to modify the code above so that the algorithm will look for Prius in the array and will print A Prius is available. if Prius is an element and A Prius is not available. if it is not an element. Sample Solution String[] cars = {"Corolla", "Camry", "Prius", "RAV4", "Highlander"}; String Prius = "A Prius is not available."; for (String s : cars) { if (s.equals("Prius")) { Prius = "A Prius is available."; } } System.out.println(Prius); Finding a Minimum or Maximum Value int[] grades = {72, 84, 63, 55, 98}; int min = grades; //set min to the first element in the array for (int i : grades) { //enhanced for loop if (i < min) { //if element is less than min min = i; //set min to element that is less } } //elements are not modified so enhanced for loop can be used System.out.println("The lowest grade is " + min); //print lowest element challenge What happens if you: replace 72 in the int array with 42? try to modify the code so that the algorithm will look for the maximum element instead? Sample Solution int[] grades = {72, 84, 63, 55, 98}; int max = grades; for (int i : grades) { if (i > max) { max = i; } } System.out.println("The highest grade is " + max); Printing Elements in Reverse Order String[] letters = {"A", "B", "C", "D", "E"}; //start at index 4, then decrement by 1 until i < 0, then stop for (int i = letters.length - 1; i >= 0; i--) { System.out.println(letters[i]); } //regular for loop needed to access each element index Formative Assessment 1 Formative Assessment 2 Learning Objectives: ArrayLists Create an empty ArrayList Add and remove ArrayList elements Get and set ArrayList elements Iterate through ArrayLists using both a regular for loop and an enhanced for loop Determine ArrayList output Determine key differences between ArrayLists and arrays Creating an ArrayList What Is an ArrayList? Although arrays are very useful for data collection, they are considered static, meaning once they are created, you cannot add or remove elements from them without changing the way they are initialized. ArrayLists, on the other hand, are dynamic, meaning you can make changes to them while the program is running. ArrayLists are particularly helpful when you don’t know how large your collection of elements will become. Since ArrayLists are dynamic, you can add and remove elements later on if needed. In order to use ArrayLists, you must import it using import java.util.ArrayList; in the header of your program. For convenience, the program file to your left already contains the import statement. ArrayList Creation To create an ArrayList, you need to include the following: * The keyword ArrayList followed by the data type in angle brackets. * Note that unlike arrays, ArrayList types are labeled slightly differently (e.g. Integer, Double, Boolean, and String). * A variable name that refers to the ArrayList. * The assignment operator = followed by the keyword new. * Another ArrayList keyword followed by the data type in angle brackets followed by empty parentheses (). ArrayList numbers = new ArrayList(); System.out.println(numbers); important IMPORTANT Unlike printing arrays, printing an ArrayList will output its elements instead of its memory address. When an ArrayList is initialized, it is empty by default. This is why printing a new ArrayList results in empty brackets []. Determining ArrayList Size ArrayLists use the method size() to determine the number of elements that exist instead of length which is used for arrays. When an ArrayList is initially created, its size is automatically 0 since all new ArrayLists are empty by default. ArrayList numbers = new ArrayList(); System.out.println(numbers.size()); Adding and Removing Elements Adding ArrayList Elements To add elements to the ArrayList, simply use the add() method. The add() method will add whatever element that is specified inside parentheses () to the end of the ArrayList by default. If an element is added to an empty ArrayList, that element will be the first and only element in the ArrayList. ArrayList numbers = new ArrayList(); numbers.add(50); //add 50 as an element to end of ArrayList System.out.println(numbers); challenge What happens if you: add numbers.add(100); directly below numbers.add(50);? add numbers.add(12.3); below numbers.add(50); but before the print statement? important IMPORTANT Much like arrays, ArrayLists can only store one type of data. For example, you cannot store 12.3 into an Integer ArrayList. To add an element to a specific index in the ArrayList, you can use the add() method with two parameters inside the parentheses (). The first parameter is the index where you want the element to be stored at and the second parameter is the element itself. For example, numbers.add(0, 12) will add the number 12 to index 0 causing 12 to become the first element in the ArrayList. This will cause all of the elements to the right of 12 to move up by 1 index number. ArrayList numbers = new ArrayList(); numbers.add(50); numbers.add(100); System.out.println(numbers); numbers.add(0, 12); //add 12 as an element to index 0 System.out.println(numbers); challenge What happens if you: add numbers.add(2, 75); directly below numbers.add(0, 12);? add numbers.add(4, 250); below numbers.add(0, 12); but before the second print statement? add numbers.add(8, 320); below numbers.add(0, 12); but before the second print statement? important IMPORTANT Adding numbers.add(8, 320); produces the familiar IndexOutOfBoundsException error. This occurs because the ArrayList does not contain index number 8. However, you can add an element to the ArrayList if you specify the last available array index plus 1. For example, if the last available index is 3, then you can use numbers.add(4, 250); to add 250 to index 4 which did not exist previously. Removing ArrayList Elements To remove an element from an ArrayList, use the remove() method and specify the ArrayList index of the element you want to be removed as a parameter inside the parentheses (). Deleting an element will cause all elements to the right of that element to move down by 1 index number. ArrayList numbers = new ArrayList(); numbers.add(12); numbers.add(50); numbers.add(75); numbers.add(100); System.out.println(numbers); numbers.remove(2); //remove element at index 2 System.out.println(numbers); challenge What happens if you: add another numbers.remove(2); directly below numbers.remove(2);? add a third numbers.remove(2); directly below the other two numbers.remove(2);s? Getting and Setting Elements Getting ArrayList Elements To get or access ArrayList elements, use the get() method and include the index as a parameter inside parentheses (). ArrayList contact = new ArrayList(); contact.add("First name"); contact.add("Last name"); contact.add("Phone number"); System.out.println(contact.get(0)); //gets element at index 0 and prints challenge What happens if you: change contact.get(0) in the code above to contact.get(1)? change contact.get(0) in the code above to contact.get(2)? change contact.get(0) in the code above to contact.get(3)? Setting ArrayList Elements To set or modify ArrayList elements, use the set() method which includes two parameters within parentheses (). The first parameter specifies the ArrayList index and the second parameter specifies the element that will replace the current value at the index. For example, contact.set(2, "Email") will modify the element at index 2 and change it to Email. ArrayList contact = new ArrayList(); contact.add("First name"); contact.add("Last name"); contact.add("Phone number"); System.out.println(contact); contact.set(2, "Email"); //change element at index 2 to "Email" System.out.println(contact); challenge What happens if you: add contact.set(0, "Full name"); to the line directly before contact.set(2, "Email");? change contact.set(2, "Email"); in the code above to contact.set(1, "Address");? change contact.set(2, "Email"); in the code above to contact.set(3, "Alternative name");? important IMPORTANT Both get() and set() methods require that the ArrayList already has an element that exists at the specified index. Otherwise, the IndexOutOfBoundsException error will occur. Iterating an ArrayList Iterating ArrayList Elements Iterating through an ArrayList is very similar to iterating through an array. The main difference is that in an ArrayList, we use get() to access the elements instead of brackets []. Both of the code blocks below use a regular for to produce the exact same results. The first code block contains an array and the second contains an ArrayList. //iterating through an array int[] grades = {85, 95, 48, 100, 92}; for (int i = 0; i < grades.length; i++) { System.out.println(grades[i]); } //iterating through an ArrayList ArrayList grades = new ArrayList(); grades.add(85); grades.add(95); grades.add(48); grades.add(100); grades.add(92); for (int i = 0; i < grades.size(); i++) { System.out.println(grades.get(i)); } Enhanced For Loop in ArrayList We can also use an enhanced for loop to iterate through an ArrayList. //iterating an ArrayList with Enhanced For Loop ArrayList grades = new ArrayList(); grades.add(85); grades.add(95); grades.add(48); grades.add(100); grades.add(92); for (Integer i : grades) { //Integer is required instead of int! System.out.println(i); } important IMPORTANT When using an enhanced for loop for an ArrayList, you must label the iterating variable accordingly. Remember that ArrayLists use Integer, Double, and Boolean instead of int, double, and boolean. Only String is consistently labeled between ArrayLists and arrays. Therefore, for (Integer i : grades) is required instead of for (int i : grades). ArrayList vs. Array ArrayList vs. Array Which one is better: ArrayList or array? The answer is, it really depends. If you know how many elements you need in your collection and you don’t intend on changing the order of those elements, then it is better to use an array. On the other hand, if you don’t know how many elements you need and want to modify the order of elements later on, then it is better to use an ArrayList. Although an array is shorter to write and arguably easier to use, it is static, meaning it is not possible to add additional elements to the array after it has already been initialized. In contrast, an ArrayList is more dynamic, meaning you can add, remove, and reorganize elements as needed later on. Here is a table showing the differences between ArrayLists and arrays. Note that uppercase Type stands for compatible ArrayList types while lowercase type stands for compatible array types. Also note that var stands for ArrayList or array name, num stands for an integer number, index stands for index or position number, and element stands for an ArrayList or array element. Method/Types ArrayList Array type[] var = new type[num] ArrayList var = new Create or type[] var = {element, ArrayList() element…} Find number var.size() var.length of elements Access an var.get(index) var[index] element Modify and var.set(index, element) var[index] = element element Add an var.add(element) or n/a element var.add(index, element) Remove an var.remove(index) n/a element for (int i = 0; i < var.length; for (int i = 0; i < var.size(); i++) i++) for loop {System.out.println(var.get(i));} {System.out.println(var[i]);} Enhanced for for (Type i : var) for (type i : var) Enhanced for for (Type i : var) for (type i : var) loop {System.out.println(i)} {System.out.println(i)} Common Integer, Double, Boolean, int, double, boolean, compatible Strings Strings types Using Both an ArrayList and Array ArrayLists and arrays can be used in tandem with each other. For example, the following code keeps track of the top five students in a class. String[] top = {"First: ", "Second: ", "Third: ", "Fourth: ", "Fifth: "}; ArrayList names = new ArrayList(); names.add("Alan"); names.add("Bob"); names.add("Carol"); names.add("David"); names.add("Ellen"); for (int i = 0; i < 5; i++) { System.out.println(top[i] + names.get(i)); } challenge Without deleting any existing code, try to: switch Alan and Carol’s places. replace David with Fred. make Grace get “Fifth” place and remove Ellen from the list. Sample Solution String[] top = {"First: ", "Second: ", "Third: ", "Fourth: ", "Fifth: "}; ArrayList names = new ArrayList(); names.add("Alan"); names.add("Bob"); names.add("Carol"); names.add("David"); names.add("Ellen"); names.set(0, "Carol"); //switch Alan with Carol names.set(2, "Alan"); //and vice versa names.set(3, "Fred"); //Fred replaces David names.add(4, "Grace"); //Grace takes Ellen's place names.remove(5); //Ellen's "Sixth" place gets removed for (int i = 0; i < 5; i++) { System.out.println(top[i] + names.get(i)); } Helpful ArrayList Algorithms ArrayList Algorithms Like arrays, ArrayLists can be used to search for a particular element and to find a minimum or maximum element. Additionally, ArrayLists can reverse the order of elements rather than just simply printing the elements in reverse order. Searching for a Particular Element ArrayList cars = new ArrayList(); String Camry = "A Camry is not available."; //default String value cars.add("Corolla"); cars.add("Camry"); cars.add("Prius"); cars.add("RAV4"); cars.add("Highlander"); for (String s : cars) { //enhanced for loop if (s.equals("Camry")) { //if "Camry" is in ArrayList Camry = "A Camry is available."; //variable changes if "Camry" exists } } System.out.println(Camry); //print whether Camry exists or not challenge What happens if you: add cars.remove(1); to the line directly below cars.add("Highlander");? try to modify the code above so that the algorithm will look for Prius in the array and will print A Prius is available. if Prius is an element and A Prius is not available. if it is not an element. Sample Solution ArrayList cars = new ArrayList(); String Prius = "A Prius is not available."; cars.add("Corolla"); cars.add("Camry"); cars.add("Prius"); cars.add("RAV4"); cars.add("Highlander"); for (String s : cars) { if (s.equals("Prius")) { Prius = "A Prius is available."; } } System.out.println(Prius); Finding a Minimum or Maximum Value ArrayList grades = new ArrayList(); grades.add(72); grades.add(84); grades.add(63); grades.add(55); grades.add(98); int min = grades.get(0); //set min to the first element in the array for (int i : grades) { //enhanced for loop if (i < min) { //if element is less than min min = i; //set min to element that is less } } //elements are not modified so enhanced for loop can be used System.out.println("The lowest grade is " + min); //print lowest element challenge What happens if you: add grades.set(0, 42); to the line directly below grades.add(98);? try to modify the code so that the algorithm will look for the maximum element instead? Sample Solution ArrayList grades = new ArrayList(); grades.add(72); grades.add(84); grades.add(63); grades.add(55); grades.add(98); int max = grades.get(0); for (int i : grades) { if (i > max) { max = i; } } System.out.println("The highest grade is " + max); Reversing the Order of Elements ArrayList letters = new ArrayList(); letters.add("A"); letters.add("B"); letters.add("C"); letters.add("D"); letters.add("E"); int original = letters.size(); //original size //regular for loops needed to access element indices for (int i = letters.size() - 1; i >= 0; i--) { letters.add(letters.get(i)); } //add elements in reverse order to the ArrayList for (int j = 0; j < original; j++) { letters.remove(0); } //remove all the original elements System.out.println(letters); //print new ArrayList important IMPORTANT Note that we used letters.remove(0) rather than letters.remove(j) in the code above because remove() deletes both the element and the index. Thus, the next element in the ArrayList becomes the new 0th index which we want to continue to delete. Formative Assessment 1

Use Quizgecko on...
Browser
Browser