Week 11-12 Array & Arraylist PDF
Document Details
Uploaded by Deleted User
NU Dasmariñas
Tags
Summary
This document is a lecture presentation on arrays and arraylists in Java. It covers concepts including array declaration, instantiation, initialization, access, and manipulation, as well as loops and multidimensional arrays. It also covers ArrayList in detail.
Full Transcript
Week 11-12 Array & Arraylist CCPRGG1L- Fundamentals of Programming Checking of Attendance ICE BREAKER THE NUMBERS GAME 7241356 RECAP Repetition Statement For Loop While Loop Do While A Java statem...
Week 11-12 Array & Arraylist CCPRGG1L- Fundamentals of Programming Checking of Attendance ICE BREAKER THE NUMBERS GAME 7241356 RECAP Repetition Statement For Loop While Loop Do While A Java statement that executes a The while loop is designed for The condition of the loop is tested group of statements repeatedly until a repeating a after the body of the loop is given test fails. set of operations on data items when performed. we Syntax: don't know how many data items Syntax: for ( ; there will ; ) { be. ; } Syntax: Two TRUTHS & A LIE 1. A Loop is a structure that allows repeated execution of a block of statement as long as a tested expression is True. 2. If a loop’s tested BOOLEAN expression is true, a block of statements called the loop body executes before the Boolean Expression is evaluated again. 3. When the Boolean evaluation tested in a loop becomes false, the loop body executes one last time. Week 11-12 Array & Arraylist CCPRGG1L- Fundamentals of Programming At the end of the session, the students shall be able to: Arrays An array is collection of items stored at contiguous memory locations. The idea is to store multiple items of same type together. An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed. Each item in an array is called an element, and each element is accessed by its numerical index. Array Declaration Syntax: [ ] ; Example: int [ ] arr; String [ ] list; Note: You are only declaring the array here, not creating them. Array Instantiation To create an instance of an array, you need to use the new keyword. Syntax for instantiating an array: If the array is already declared: [ ] ; //array declaration = new []; Example: int [ ] arr; arr = new int ; //creates an array of 10 integers Array Instantiation To create an instance of an array, you need to use the new keyword. Syntax for instantiating an array: If the array is not yet declared: [ ] = new []; Example: int [ ] arr = new int; String [ ] list = new String; Array Initialization Initializing values to an array can be done in two ways: During instantiation of the array int [ ] arrayInt = {1,2,3,4,5}; double [ ] arrayDouble = {2.5,3.2,7.0}; Assigning values by its numerical index arrayInt = 2; arrayInt = 4; arrayInt = 7;... Accessing the array You access an array element by referring to the index number. String[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; System.out.print(cars + “,”); System.out.print(cars + “,”); System.out.println(cars); Output: Volvo, BMW, Ford Change the element in an array You can change the value of an element by referring to its index String[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; cars = “Jaguar”; System.out.print(cars); Output: Jaguar Loop through an array You can loop through the array elements with the for loop, and use the length property to specify how many times the loop should run. String[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; for (int i = 0; i < cars.length; i++) { System.out.println(cars[i]); } Loop through an array You can loop through the array elements using for-each loop. Syntax: for (type variable : arrayname) {... } Example: String[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; for (String i : cars) { System.out.println(i); } Multidimensional Array Multidimensional array A multidimensional array is an array containing one or more arrays. To create a two-dimensional array, add each array within its own set of curly braces: int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7, 8} }; Multidimensional array To access the elements of the myNumbers array, specify two indexes: one for the array, and one for the element inside that array. This example accesses the third element (2) in the second array (1) of myNumbers: int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7, 8} }; int x = myNumbers; System.out.println(x); // Outputs 7 Multidimensional array We can also use a for loop inside another for loop to get the elements of a two-dimensional array (we still have to point to the two indexes): public class MyClass { public static void main(String[] args) { int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7, 8} }; for (int i = 0; i < myNumbers.length; ++i) { for(int j = 0; j < myNumbers[i].length; ++j) { System.out.println(myNumbers[i][j]); } } } } Array list Array list ArrayList is a part of collection framework and is present in java.util package. It provides us dynamic arrays in Java. Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in the array is needed. Since it is a collection, it can only accommodate objects, not primitive data types, so Java has a built-in objects for these data types. int -> Integer char -> Character float -> Float short -> Short double -> Double boolean -> Boolean long -> Long Array vs. Array list Array has a fixed size Array list can grow as needed Array list is easier to manipulate than array E.g. Removing an element Constructors of Array list ArrayList(): This constructor is used to build an empty array list ArrayList(Collection c): This constructor is used to build an array list initialized with the elements from collection c ArrayList(int capacity): This constructor is used to build an array list with initial capacity being specified Syntax ArrayList arrName= new ArrayList(); Example: ArrayList arrInt = new ArrayList(); ArrayList arrDouble = new ArrayList(); ArrayList arrStr = new ArrayList(); add(Object o) remove(int index) Common Methods set(int index, Object o) contains(Object o) for ArrayList indexOf(Object o) get(int index) clear( ) size( ) Limitations of Array Arrays have several limitations as your programs get more complex Arrays are a fixed size Arrays only provide low level get and set methods. What if you want to do more? Array Lists ArrayList is like an array with extra powers It can automatically resize and also comes with other helpful methods Creating an ArrayList //Import the ArrayList class import java.util.ArrayList; Or import java.util.*; will import all classes Creating an ArrayList Syntax: ArrayList list = new ArrayList(); Variable Type Variable Name ArrayList of size 0 ArrayList to store Integers ArrayList list = new ArrayList(); For ints use Integer For doubles use Double Add to an ArrayList ArrayList list = new ArrayList(); list.add(5); list.add(3); list.add(10); list.add(4); Get a Value in an ArrayList int val = list.get(1); //has value 3 Set a Value in an ArrayList // Set index 2 to value 88 list.set(2,88); Length or Size of ArrayList To get the size of an ArrayList use the size() method int length = list.size(); Loop Over ArrayList Say you have an ArrayList called list, you can loop with for(int i = 0; i < list.size(); i++) { int elem = list.get(i); // use elem… } Loop Over ArrayList: Enhanced for loop Say you have an ArrayList called list, you can loop with the enhanced for loop like for(int elem: list) { // use elem here… } Loop Over ArrayList: Enhanced for loop Say you have an ArrayList called list, you can loop with the enhanced for loop like for(String elem: list) { // use elem here… } ArrayList Quick Reference myList.add("Hello"); import java.util.*; public class ExampleLists { // Add the element "World" to our list public static void main(String[] myList.add("World"); args) { // Print the element at index 0 // Declare and Create an ArrayList of our list: "Hello" of Strings. System.out.print(myList.get(0)); ArrayList myList = new ArrayList() // Print the element at index 1 of our list: "World" // Add the element "Hello" to our list System.out.println(" " +myList.get(1)); } } ArrayList myList = new ArrayList(); // Add the element 100 to our list myList.add(100); // Add the element 200 to our list myList.add(200); // Print the element at index 0 of our list: 100 System.out.println(myList.get(0)); // Print the element at index 1 of our list: 200 System.out.println(myList.get(1)); ArrayList numbers = new ArrayList(); for(int i = 0; i < 100; i ++) { numbers.add(i); } // Print out the size of the ArrayList. System.out.println(numbers.size()); public static void main(String[] args) { ArrayList numbers = new ArrayList(); // Add 5 numbers to `numbers` numbers.add(1); numbers.add(2); numbers.add(3); numbers.add(4); numbers.add(5); numbers.add(3,10); // Print out the first element in `numbers` System.out.println(numbers.get(0)); } References Dale, Nell and Weems, Chip, Introduction to Pascal and Structured Design, 4th edition, D. C. Heath and Company, Lexington, Massachusetts, 1994. Java Objects and Classes. Retrieved from https://www.tutorialspoint.com/java/java_object_classes.htm Introduction to programming. Retrieved from https://ocw.mit.edu/courses/electrical-engineering-and- computer-science/6-092-introduction-to-programming-in-java- january-iap-2010/