ARRAY AND ARRAYLIST IN JAVA Abrahem P. Anqui
Learning Objective ■ Discuss the fundamental concept of Array and ArrayList ■ Simulate the process of an array in data storing and retrieval ■ Create a java program that implements the array and ArrayList concepts.
Agenda ■ Arrays – Index – Single dimensional array – Multi-dimensional array/two-dimensional array ■ ArrayList – Add item – Access an item – Change an item – Remove an item – ArrayList Size
Arrays ■ In computer science, an array data structure, or simply an array, is a data structure consisting of a collection of elements, each identified by at least one array index or key. An array is stored such that the position of each element can be computed from its index tuple by a mathematical formula. ■ Java provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type. ■ Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables.
Declaring Array Variables ■ To use an array in a program, you must declare a variable to reference the array, and you must specify the type of array the variable can reference. Here is the syntax for declaring an array variable − ■ Syntax – dataType[] arrayRefVar; // preferred way. – or – dataType arrayRefVar[]; // works but not preferred way. ■ Note − The style dataType[] arrayRefVar is preferred. The style dataType arrayRefVar[] comes from the C/C++ language and was adopted in Java to accommodate C/C++ programmers. Example The following code snippets are examples of this syntax − – double[] myList; // preferred way. – or – double myList[]; // works but not preferred way.
Creating an Array ■ You can create an array by using the new operator with the following syntax − Syntax ■ arrayRefVar = new dataType[arraySize]; ■ The above statement does two things − – It creates an array using new dataType[arraySize]. – It assigns the reference of the newly created array to the variable arrayRefVar. ■ Declaring an array variable, creating an array, and assigning the reference of the array to the variable can be combined in one statement, as shown below − – dataType[] arrayRefVar = new dataType[arraySize]; Alternatively you can create arrays as follows − – dataType[] arrayRefVar = {value0, value1, ..., valuek}; ■ The array elements are accessed through the index. Array indices are 0-based; that is, they start from 0 to arrayRefVar.length-1.
Example ■ Following statement declares an array variable, myList, creates an array of 10 elements of double type and assigns its reference to myList − ■ double[] myList = new double[10];
Processing Arrays ■ When processing array elements, we often use either for loop or foreach loop because all of the elements in an array are of the same type and the size of the array is known. ■ Example ■ Here is a complete example showing how to create, initialize, and process arrays − public class TestArray { public static void main(String[] args) { double[] myList = {1.5, 2.7, 3.4, 3.1}; for (int i = 0; i < myList.length; i++) { System.out.println(myList[i] + " "); } double total = 0; for(int i = 0; i < myList.length; i++) { total += myList[i]; } System.out.println("Total is " + total); double max = myList[0]; for (int i = 1; i < myList.length; i++) { if (myList[i] > max) max = myList[i]; } System.out.println("Max is " + max); } } 1.5 2.7 3.4 3.1 Total is 10.7 Max is 3.4
Advantages vs Disadvantages of Array ■ Advantages – Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently. – Random access: We can get any data located at an index position. ■ Disadvantages – Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its size at runtime. To solve this problem, a collection framework is used in Java which grows automatically.
Types of Array ■ There are two types of array. – Single Dimensional Array – Multidimensional Array Single Dimensional Array in Java Syntax to Declare an Array in Java dataType[] arr; (or) dataType []arr; (or) dataType arr[]; Instantiation of an Array in Java arrayRefVar=new datatype[size]; Example of Java Array Let's see the simple example of java array, where we are going to declare, instantiate, initialize and traverse an array. //Java Program to illustrate how to declare, instantiate, initialize //and traverse the Java array. class Testarray{ public static void main(String args[]){ int a[]=new int[5];//declaration and instantiation a[0]=10;//initialization a[1]=20+a[0]; a[2]=70-a[1]; a[3]=40*a[0]; a[4]=50%a[3]; //traversing array for(int i=0;i<a.length;i++)//length is the property of array System.out.println(a[i]); }} 10 30 40 400 50
Types of Array Multidimensional Array in Java (Use Excel to Illustrate further) In such case, data is stored in row and column based index (also known as matrix form). Syntax to Declare Multidimensional Array in Java dataType[][] arrayRefVar; (or) dataType [][]arrayRefVar; (or) dataType arrayRefVar[][]; (or) dataType []arrayRefVar[]; Example to instantiate Multidimensional Array in Java int[][] arr=new int[3][3];//3 row and 3 column Example to initialize Multidimensional Array in Java arr[0][0]=1; arr[0][1]=2; arr[0][2]=3; arr[1][0]=4; arr[1][1]=5; arr[1][2]=6; arr[2][0]=7; arr[2][1]=8; Example of Multidimensional Java Array Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional array. //Java Program to illustrate the use of multidimensional array class Testarray3{ public static void main(String args[]){ //declaring and initializing 2D array int arr[][]={{1,2,3},{4,5,6},{7,8,9}}; //printing 2D array for(int i=0;i<3;i++){ for(int j=0;j<3;j++){ System.out.print(arr[i][j]+" "); } System.out.println(); } }} 1 2 3 4 5 6 7 8 9
For-each Loop for Array (Java Context) We can also print the Java array using for-each loop. The Java for-each loop prints the array elements one by one. It holds an array element in a variable, then executes the body of the loop. The syntax of the for-each loop is given below: for(data_type variable:array){ //body of the loop } for(int x:arrayList){ } For(initialization;condition;iteration){ Statement; } Let us see the example of print the elements of Java array using the for-each loop. //Java Program to print the array elements using for-each loop class Testarray1{ public static void main(String args[]){ int arr[]={33,3,4,5}; //printing array using for-each loop for(int i:arr) System.out.println(i); }} 33 3 4 5
Passing Array to a Method (Java Context) ■ We can pass the java array to method so that we can reuse the same logic on any array. ■ Let's see the simple example to get the minimum number of an array using a method. //Java Program to demonstrate the way of passing an array //to method. class Testarray2{ //creating a method that receives an array as a parameter static void min(int arr[]){ int min=arr[0]; for(int i=1;i<arr.length;i++) if(min>arr[i]) min=arr[i]; System.out.println(min); } public static void main(String args[]){ int a[]={33,3,4,5};//declaring and initializing an array min(a);//passing array to method }} 3
Returning Array from the Method (Java Context) ■ We can also return an array from the method in Java. //Java Program to return an array from the method class TestReturnArray{ //creating method which returns an array static int[] get(){ return new int[]{10,30,50,90,60}; } public static void main(String args[]){ //calling method which returns an array int arr[]=get(); //printing the values of an array for(int i=0;i<arr.length;i++) System.out.println(arr[i]); }} 10 30 50 90 60
ArrayIndexOutOfBoundsException ■ The Java Virtual Machine (JVM) throws an ArrayIndexOutOfBoundsException if length of the array is negative, equal to the array size or greater than the array size while traversing the array. //Java Program to demonstrate the case of //ArrayIndexOutOfBoundsException in a Java Array. public class TestArrayException{ public static void main(String args[]){ int arr[]={50,60,70,80}; for(int i=0;i<=arr.length;i++){ System.out.println(arr[i]); } }} Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4 at TestArrayException.main(TestArrayException.java:5) 50 60 70 80
ArrayList The ArrayList class is a resizable array, which can be found in the java.util package. The difference between a built-in array and an ArrayList in Java, is that the size of an array cannot be modified (if you want to add or remove elements to/from an array, you have to create a new one). While elements can be added and removed from an ArrayList whenever you want. The syntax is also slightly different:
Example ■ Create an ArrayList object called cars that will store strings: import java.util.ArrayList; // import the ArrayList class ArrayList<String> cars = new ArrayList<String>(); // Create an ArrayList object
Add Items ■ The ArrayList class has many useful methods. For example, to add elements to the ArrayList, use the add() method: import java.util.ArrayList; public class Main { public static void main(String[] args) { ArrayList<String> cars = new ArrayList<String>(); cars.add("Volvo"); cars.add("BMW"); cars.add("Ford"); cars.add("Mazda"); System.out.println(cars); } }
Access an Item ■ To access an element in the ArrayList, use the get() method and refer to the index number: import java.util.ArrayList; public class Main { public static void main(String[] args) { ArrayList<String> cars = new ArrayList<String>(); cars.add("Volvo"); cars.add("BMW"); cars.add("Ford"); cars.add("Mazda"); System.out.println(cars.get(0)); } }
Change an Item ■ To modify an element, use the set() method and refer to the index number: import java.util.ArrayList; public class Main { public static void main(String[] args) { ArrayList<String> cars = new ArrayList<String>(); cars.add("Volvo"); cars.add("BMW"); cars.add("Ford"); cars.add("Mazda"); cars.set(0, "Opel"); System.out.println(cars); } }
Remove an Item ■ To remove an element, use the remove() method and refer to the index number: import java.util.ArrayList; public class Main { public static void main(String[] args) { ArrayList<String> cars = new ArrayList<String>(); cars.add("Volvo"); cars.add("BMW"); cars.add("Ford"); cars.add("Mazda"); cars.remove(0); System.out.println(cars); } } To remove all the elements in the ArrayList, use the clear() method: import java.util.ArrayList; public class Main { public static void main(String[] args) { ArrayList<String> cars = new ArrayList<String>(); cars.add("Volvo"); cars.add("BMW"); cars.add("Ford"); cars.add("Mazda"); cars.clear(); System.out.println(cars); } }
ArrayList Size ■ To find out how many elements an ArrayList have, use the size method: import java.util.ArrayList; public class Main { public static void main(String[] args) { ArrayList<String> cars = new ArrayList<String>(); cars.add("Volvo"); cars.add("BMW"); cars.add("Ford"); cars.add("Mazda"); System.out.println(cars.size()); } }
Loop Through an ArrayList ■ Loop through the elements of an ArrayList with a for loop, and use the size() method to specify how many times the loop should run: public class Main { public static void main(String[] args) { ArrayList<String> cars = new ArrayList<String>(); cars.add("Volvo"); cars.add("BMW"); cars.add("Ford"); cars.add("Mazda"); for (int i = 0; i < cars.size(); i++) { System.out.println(cars.get(i)); } } } You can also loop through an ArrayList with the for-each loop: public class Main { public static void main(String[] args) { ArrayList<String> cars = new ArrayList<String>(); cars.add("Volvo"); cars.add("BMW"); cars.add("Ford"); cars.add("Mazda"); for (String i : cars) { System.out.println(i); } } }
Other Types ■ Elements in an ArrayList are actually objects. In the examples above, we created elements (objects) of type "String". Remember that a String in Java is an object (not a primitive type). To use other types, such as int, you must specify an equivalent wrapper class: Integer. For other primitive types, use: Boolean for boolean, Character for char, Double for double, etc: import java.util.ArrayList; public class Main { public static void main(String[] args) { ArrayList<Integer> myNumbers = new ArrayList<Integer>(); myNumbers.add(10); myNumbers.add(15); myNumbers.add(20); myNumbers.add(25); for (int i : myNumbers) { System.out.println(i); } } }
Sort an ArrayList ■ Another useful class in the java.util package is the Collections class, which include the sort() method for sorting lists alphabetically or numerically: import java.util.ArrayList; import java.util.Collections; // Import the Collections class public class Main { public static void main(String[] args) { ArrayList<String> cars = new ArrayList<String>(); cars.add("Volvo"); cars.add("BMW"); cars.add("Ford"); cars.add("Mazda"); Collections.sort(cars); // Sort cars for (String i : cars) { System.out.println(i); } } } import java.util.ArrayList; import java.util.Collections; // Import the Collections class public class Main { public static void main(String[] args) { ArrayList<Integer> myNumbers = new ArrayList<Integer>(); myNumbers.add(33); myNumbers.add(15); myNumbers.add(20); myNumbers.add(34); myNumbers.add(8); myNumbers.add(12); Collections.sort(myNumbers); // Sort myNumbers for (int i : myNumbers) { System.out.println(i); } } }
Lecture Quiz
Lecture Activity
Hands-on Activity/Quiz ■ Write a program that accepts ten integers from a user, stores them in an array, and then calculates and displays (count) the number of odd and even integers entered.
■ Write a program that accepts ten integers from a user, stores them in an array, and then asks the user to search for a certain value and return the position(not the index) of that value if it is present in the array otherwise print not found. ■ Write a program in java implementing a 2D array that computes and displays a multiplication table. To compute the product/item to be stored in the array using the formula x=row*column. Important note, first store the values in the array before displaying it in a matrix form.
Data Structures and Algorithm Array and Arraylists

Data Structures and Algorithm Array and Arraylists

  • 1.
    ARRAY AND ARRAYLISTIN JAVA Abrahem P. Anqui
  • 2.
    Learning Objective ■ Discussthe fundamental concept of Array and ArrayList ■ Simulate the process of an array in data storing and retrieval ■ Create a java program that implements the array and ArrayList concepts.
  • 3.
    Agenda ■ Arrays – Index –Single dimensional array – Multi-dimensional array/two-dimensional array ■ ArrayList – Add item – Access an item – Change an item – Remove an item – ArrayList Size
  • 4.
    Arrays ■ In computerscience, an array data structure, or simply an array, is a data structure consisting of a collection of elements, each identified by at least one array index or key. An array is stored such that the position of each element can be computed from its index tuple by a mathematical formula. ■ Java provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type. ■ Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables.
  • 5.
    Declaring Array Variables ■To use an array in a program, you must declare a variable to reference the array, and you must specify the type of array the variable can reference. Here is the syntax for declaring an array variable − ■ Syntax – dataType[] arrayRefVar; // preferred way. – or – dataType arrayRefVar[]; // works but not preferred way. ■ Note − The style dataType[] arrayRefVar is preferred. The style dataType arrayRefVar[] comes from the C/C++ language and was adopted in Java to accommodate C/C++ programmers. Example The following code snippets are examples of this syntax − – double[] myList; // preferred way. – or – double myList[]; // works but not preferred way.
  • 6.
    Creating an Array ■You can create an array by using the new operator with the following syntax − Syntax ■ arrayRefVar = new dataType[arraySize]; ■ The above statement does two things − – It creates an array using new dataType[arraySize]. – It assigns the reference of the newly created array to the variable arrayRefVar. ■ Declaring an array variable, creating an array, and assigning the reference of the array to the variable can be combined in one statement, as shown below − – dataType[] arrayRefVar = new dataType[arraySize]; Alternatively you can create arrays as follows − – dataType[] arrayRefVar = {value0, value1, ..., valuek}; ■ The array elements are accessed through the index. Array indices are 0-based; that is, they start from 0 to arrayRefVar.length-1.
  • 7.
    Example ■ Following statementdeclares an array variable, myList, creates an array of 10 elements of double type and assigns its reference to myList − ■ double[] myList = new double[10];
  • 8.
    Processing Arrays ■ Whenprocessing array elements, we often use either for loop or foreach loop because all of the elements in an array are of the same type and the size of the array is known. ■ Example ■ Here is a complete example showing how to create, initialize, and process arrays − public class TestArray { public static void main(String[] args) { double[] myList = {1.5, 2.7, 3.4, 3.1}; for (int i = 0; i < myList.length; i++) { System.out.println(myList[i] + " "); } double total = 0; for(int i = 0; i < myList.length; i++) { total += myList[i]; } System.out.println("Total is " + total); double max = myList[0]; for (int i = 1; i < myList.length; i++) { if (myList[i] > max) max = myList[i]; } System.out.println("Max is " + max); } } 1.5 2.7 3.4 3.1 Total is 10.7 Max is 3.4
  • 9.
    Advantages vs Disadvantagesof Array ■ Advantages – Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently. – Random access: We can get any data located at an index position. ■ Disadvantages – Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its size at runtime. To solve this problem, a collection framework is used in Java which grows automatically.
  • 10.
    Types of Array ■There are two types of array. – Single Dimensional Array – Multidimensional Array Single Dimensional Array in Java Syntax to Declare an Array in Java dataType[] arr; (or) dataType []arr; (or) dataType arr[]; Instantiation of an Array in Java arrayRefVar=new datatype[size]; Example of Java Array Let's see the simple example of java array, where we are going to declare, instantiate, initialize and traverse an array. //Java Program to illustrate how to declare, instantiate, initialize //and traverse the Java array. class Testarray{ public static void main(String args[]){ int a[]=new int[5];//declaration and instantiation a[0]=10;//initialization a[1]=20+a[0]; a[2]=70-a[1]; a[3]=40*a[0]; a[4]=50%a[3]; //traversing array for(int i=0;i<a.length;i++)//length is the property of array System.out.println(a[i]); }} 10 30 40 400 50
  • 11.
    Types of Array MultidimensionalArray in Java (Use Excel to Illustrate further) In such case, data is stored in row and column based index (also known as matrix form). Syntax to Declare Multidimensional Array in Java dataType[][] arrayRefVar; (or) dataType [][]arrayRefVar; (or) dataType arrayRefVar[][]; (or) dataType []arrayRefVar[]; Example to instantiate Multidimensional Array in Java int[][] arr=new int[3][3];//3 row and 3 column Example to initialize Multidimensional Array in Java arr[0][0]=1; arr[0][1]=2; arr[0][2]=3; arr[1][0]=4; arr[1][1]=5; arr[1][2]=6; arr[2][0]=7; arr[2][1]=8; Example of Multidimensional Java Array Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional array. //Java Program to illustrate the use of multidimensional array class Testarray3{ public static void main(String args[]){ //declaring and initializing 2D array int arr[][]={{1,2,3},{4,5,6},{7,8,9}}; //printing 2D array for(int i=0;i<3;i++){ for(int j=0;j<3;j++){ System.out.print(arr[i][j]+" "); } System.out.println(); } }} 1 2 3 4 5 6 7 8 9
  • 12.
    For-each Loop forArray (Java Context) We can also print the Java array using for-each loop. The Java for-each loop prints the array elements one by one. It holds an array element in a variable, then executes the body of the loop. The syntax of the for-each loop is given below: for(data_type variable:array){ //body of the loop } for(int x:arrayList){ } For(initialization;condition;iteration){ Statement; } Let us see the example of print the elements of Java array using the for-each loop. //Java Program to print the array elements using for-each loop class Testarray1{ public static void main(String args[]){ int arr[]={33,3,4,5}; //printing array using for-each loop for(int i:arr) System.out.println(i); }} 33 3 4 5
  • 13.
    Passing Array toa Method (Java Context) ■ We can pass the java array to method so that we can reuse the same logic on any array. ■ Let's see the simple example to get the minimum number of an array using a method. //Java Program to demonstrate the way of passing an array //to method. class Testarray2{ //creating a method that receives an array as a parameter static void min(int arr[]){ int min=arr[0]; for(int i=1;i<arr.length;i++) if(min>arr[i]) min=arr[i]; System.out.println(min); } public static void main(String args[]){ int a[]={33,3,4,5};//declaring and initializing an array min(a);//passing array to method }} 3
  • 14.
    Returning Array fromthe Method (Java Context) ■ We can also return an array from the method in Java. //Java Program to return an array from the method class TestReturnArray{ //creating method which returns an array static int[] get(){ return new int[]{10,30,50,90,60}; } public static void main(String args[]){ //calling method which returns an array int arr[]=get(); //printing the values of an array for(int i=0;i<arr.length;i++) System.out.println(arr[i]); }} 10 30 50 90 60
  • 15.
    ArrayIndexOutOfBoundsException ■ The JavaVirtual Machine (JVM) throws an ArrayIndexOutOfBoundsException if length of the array is negative, equal to the array size or greater than the array size while traversing the array. //Java Program to demonstrate the case of //ArrayIndexOutOfBoundsException in a Java Array. public class TestArrayException{ public static void main(String args[]){ int arr[]={50,60,70,80}; for(int i=0;i<=arr.length;i++){ System.out.println(arr[i]); } }} Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4 at TestArrayException.main(TestArrayException.java:5) 50 60 70 80
  • 16.
    ArrayList The ArrayList classis a resizable array, which can be found in the java.util package. The difference between a built-in array and an ArrayList in Java, is that the size of an array cannot be modified (if you want to add or remove elements to/from an array, you have to create a new one). While elements can be added and removed from an ArrayList whenever you want. The syntax is also slightly different:
  • 17.
    Example ■ Create anArrayList object called cars that will store strings: import java.util.ArrayList; // import the ArrayList class ArrayList<String> cars = new ArrayList<String>(); // Create an ArrayList object
  • 18.
    Add Items ■ TheArrayList class has many useful methods. For example, to add elements to the ArrayList, use the add() method: import java.util.ArrayList; public class Main { public static void main(String[] args) { ArrayList<String> cars = new ArrayList<String>(); cars.add("Volvo"); cars.add("BMW"); cars.add("Ford"); cars.add("Mazda"); System.out.println(cars); } }
  • 19.
    Access an Item ■To access an element in the ArrayList, use the get() method and refer to the index number: import java.util.ArrayList; public class Main { public static void main(String[] args) { ArrayList<String> cars = new ArrayList<String>(); cars.add("Volvo"); cars.add("BMW"); cars.add("Ford"); cars.add("Mazda"); System.out.println(cars.get(0)); } }
  • 20.
    Change an Item ■To modify an element, use the set() method and refer to the index number: import java.util.ArrayList; public class Main { public static void main(String[] args) { ArrayList<String> cars = new ArrayList<String>(); cars.add("Volvo"); cars.add("BMW"); cars.add("Ford"); cars.add("Mazda"); cars.set(0, "Opel"); System.out.println(cars); } }
  • 21.
    Remove an Item ■To remove an element, use the remove() method and refer to the index number: import java.util.ArrayList; public class Main { public static void main(String[] args) { ArrayList<String> cars = new ArrayList<String>(); cars.add("Volvo"); cars.add("BMW"); cars.add("Ford"); cars.add("Mazda"); cars.remove(0); System.out.println(cars); } } To remove all the elements in the ArrayList, use the clear() method: import java.util.ArrayList; public class Main { public static void main(String[] args) { ArrayList<String> cars = new ArrayList<String>(); cars.add("Volvo"); cars.add("BMW"); cars.add("Ford"); cars.add("Mazda"); cars.clear(); System.out.println(cars); } }
  • 22.
    ArrayList Size ■ Tofind out how many elements an ArrayList have, use the size method: import java.util.ArrayList; public class Main { public static void main(String[] args) { ArrayList<String> cars = new ArrayList<String>(); cars.add("Volvo"); cars.add("BMW"); cars.add("Ford"); cars.add("Mazda"); System.out.println(cars.size()); } }
  • 23.
    Loop Through anArrayList ■ Loop through the elements of an ArrayList with a for loop, and use the size() method to specify how many times the loop should run: public class Main { public static void main(String[] args) { ArrayList<String> cars = new ArrayList<String>(); cars.add("Volvo"); cars.add("BMW"); cars.add("Ford"); cars.add("Mazda"); for (int i = 0; i < cars.size(); i++) { System.out.println(cars.get(i)); } } } You can also loop through an ArrayList with the for-each loop: public class Main { public static void main(String[] args) { ArrayList<String> cars = new ArrayList<String>(); cars.add("Volvo"); cars.add("BMW"); cars.add("Ford"); cars.add("Mazda"); for (String i : cars) { System.out.println(i); } } }
  • 24.
    Other Types ■ Elementsin an ArrayList are actually objects. In the examples above, we created elements (objects) of type "String". Remember that a String in Java is an object (not a primitive type). To use other types, such as int, you must specify an equivalent wrapper class: Integer. For other primitive types, use: Boolean for boolean, Character for char, Double for double, etc: import java.util.ArrayList; public class Main { public static void main(String[] args) { ArrayList<Integer> myNumbers = new ArrayList<Integer>(); myNumbers.add(10); myNumbers.add(15); myNumbers.add(20); myNumbers.add(25); for (int i : myNumbers) { System.out.println(i); } } }
  • 25.
    Sort an ArrayList ■Another useful class in the java.util package is the Collections class, which include the sort() method for sorting lists alphabetically or numerically: import java.util.ArrayList; import java.util.Collections; // Import the Collections class public class Main { public static void main(String[] args) { ArrayList<String> cars = new ArrayList<String>(); cars.add("Volvo"); cars.add("BMW"); cars.add("Ford"); cars.add("Mazda"); Collections.sort(cars); // Sort cars for (String i : cars) { System.out.println(i); } } } import java.util.ArrayList; import java.util.Collections; // Import the Collections class public class Main { public static void main(String[] args) { ArrayList<Integer> myNumbers = new ArrayList<Integer>(); myNumbers.add(33); myNumbers.add(15); myNumbers.add(20); myNumbers.add(34); myNumbers.add(8); myNumbers.add(12); Collections.sort(myNumbers); // Sort myNumbers for (int i : myNumbers) { System.out.println(i); } } }
  • 26.
  • 27.
  • 28.
    Hands-on Activity/Quiz ■ Writea program that accepts ten integers from a user, stores them in an array, and then calculates and displays (count) the number of odd and even integers entered.
  • 29.
    ■ Write aprogram that accepts ten integers from a user, stores them in an array, and then asks the user to search for a certain value and return the position(not the index) of that value if it is present in the array otherwise print not found. ■ Write a program in java implementing a 2D array that computes and displays a multiplication table. To compute the product/item to be stored in the array using the formula x=row*column. Important note, first store the values in the array before displaying it in a matrix form.

Editor's Notes

  • #1 A student attendance system: use an array when the number of students is fixed, but use an ArrayList if students can be added/removed. Can you think of a real-life example where you would prefer an ArrayList over an array?
  • #2 Which of these three objectives do you think will be the most useful in your future programming tasks?
  • #3 Explanation/Discussion: Walk students through the roadmap: starting with arrays (declaration, single/multi-dimensional), then moving to ArrayList operations (add, access, change, remove, size, loops, sorting). Example: “Today’s lesson is like a journey: we’ll begin with arrays (the foundation), then expand to ArrayList (a more flexible tool).” Question: Why do you think we should learn arrays before ArrayList?
  • #4 Explanation/Discussion: Define arrays as a fixed-size data structure that stores elements of the same type. Indices start at 0. Example: Instead of making 100 separate variables for exam scores, use one array: int[] scores = new int[100]; Question: What happens if you try to access an index outside the array’s size?
  • #8 public class TestArray { // Define a class named TestArray public static void main(String[] args) { // Program starts running here (the main method) double[] myList = {1.5, 2.7, 3.4, 3.1}; // Create an array of doubles with 4 values for (int i = 0; i < myList.length; i++) { // Loop from i=0 up to (but not including) array length System.out.println(myList[i] + " "); // Print the current number plus a space, then a newline } // End of print-each-element loop double total = 0; // Start a running sum at 0 for(int i = 0; i < myList.length; i++) { // Loop over all elements again total += myList[i]; // Add the current element to the sum (total = total + myList[i]) } // End of sum loop System.out.println("Total is " + total); // Print the final sum double max = myList[0]; // Assume the first element is the largest to start for (int i = 1; i < myList.length; i++) { // Check the rest of the elements (start at index 1) if (myList[i] > max) // If the current element is bigger than what we have in max max = myList[i]; // Update max to that bigger value } // End of max-finding loop System.out.println("Max is " + max); // Print the largest value found } // End of main method } // End of class
  • #10 // Java Program to illustrate how to declare, instantiate, initialize // and traverse the Java array. class Testarray { public static void main(String args[]) { int a[] = new int[5]; // Declare an array 'a' of size 5 (can hold 5 integers) a[0] = 10; // Initialize index 0 with 10 a[1] = 20 + a[0]; // Initialize index 1 with 20 + a[0] → 20 + 10 = 30 a[2] = 70 - a[1]; // Initialize index 2 with 70 - a[1] → 70 - 30 = 40 a[3] = 40 * a[0]; // Initialize index 3 with 40 * a[0] → 40 * 10 = 400 a[4] = 50 % a[3]; // Initialize index 4 with 50 % a[3] → 50 % 400 = 50 (remainder) // traversing array for (int i = 0; i < a.length; i++) // Loop runs from i = 0 to i < length of array (5) System.out.println(a[i]); // Print each element of array } }
  • #11 // Java Program to illustrate the use of multidimensional array class Testarray3 { // Define a class named Testarray3 public static void main(String args[]) { // Main method (program execution starts here) // declaring and initializing 2D array (3 rows and 3 columns) int arr[][] = { {1,2,3}, {4,5,6}, {7,8,9} }; // printing 2D array for (int i = 0; i < 3; i++) { // Outer loop → controls rows (0 to 2) for (int j = 0; j < 3; j++) { // Inner loop → controls columns (0 to 2) System.out.print(arr[i][j] + " "); // Print the element at row i and column j } System.out.println(); // Move to the next line after each row is printed } } }
  • #12 // Java Program to print the array elements using for-each loop class Testarray1 { public static void main(String args[]) { int arr[] = {33, 3, 4, 5}; // Declare and initialize an array with 4 elements // printing array using for-each loop for (int i : arr) // For-each loop → takes each element of arr one by one System.out.println(i); // Print the current element (i) } } for (int i : arr) means → take each element from arr and put it into i. First loop → i = 33 → print 33 Second loop → i = 3 → print 3 Third loop → i = 4 → print 4 Fourth loop → i = 5 → print 5
  • #13 // Java Program to demonstrate the way of passing an array // to a method. class Testarray2 { // creating a method that receives an array as a parameter static void min(int arr[]) { // Method 'min' accepts an integer array int min = arr[0]; // Assume first element is the minimum for (int i = 1; i < arr.length; i++) { // Loop through rest of the array (from index 1) if (min > arr[i]) // If we find an element smaller than current min min = arr[i]; // Update min with that smaller value } System.out.println(min); // Print the final smallest element } public static void main(String args[]) { int a[] = {33, 3, 4, 5}; // Declare and initialize an array min(a); // Pass the array 'a' to the min() method } } a[] = {33, 3, 4, 5} Call min(a) → array is passed into the method. min = arr[0] = 33 (start with first element). Compare with others: 33 > 3 → update min = 3 3 > 4 → false, keep min = 3 3 > 5 → false, keep min = 3 Print result → 3.
  • #14 // Java Program to return an array from the method class TestReturnArray { // creating a method which returns an array static int[] get() { return new int[]{10, 30, 50, 90, 60}; // Return a new array with 5 elements } public static void main(String args[]) { // calling method which returns an array int arr[] = get(); // Store the returned array in variable 'arr' // printing the values of an array for (int i = 0; i < arr.length; i++) // Loop through array from index 0 to last System.out.println(arr[i]); // Print each element of array } } Program starts at main. get() method is called → it creates and returns an array {10, 30, 50, 90, 60}. The returned array is stored in arr. for loop goes through each element of arr: Prints 10 Prints 30 Prints 50 Prints 90 Prints 60
  • #15 // Java Program to demonstrate the case of // ArrayIndexOutOfBoundsException in a Java Array. public class TestArrayException { public static void main(String args[]) { int arr[] = {50, 60, 70, 80}; // Declare and initialize an array with 4 elements // Loop to print array elements // ❌ Problem: condition is i <= arr.length → this goes out of array size for (int i = 0; i <= arr.length; i++) { System.out.println(arr[i]); // Try to access arr[i] } } } Array elements are at indexes: arr[0] = 50 arr[1] = 60 arr[2] = 70 arr[3] = 80 arr.length = 4. Loop runs with condition i <= arr.length: i = 0 → arr[0] = 50 i = 1 → arr[1] = 60 i = 2 → arr[2] = 70 i = 3 → arr[3] = 80 i = 4 → arr[4] ❌ (this does not exist, so program throws ArrayIndexOutOfBoundsException).