Array Lists CSE 1310 – Introduction to Computers and Programming

Slides:



Advertisements
Similar presentations
1 Various Methods of Populating Arrays Randomly generated integers.
Advertisements

Chapter 7 – Arrays.
Methods (Functions) CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Boolean Expressions and Conditionals (If Statements) CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington.
1 CSC 221: Computer Programming I Spring 2008 ArrayLists and arrays  example: letter frequencies  autoboxing/unboxing  ArrayLists vs. arrays  example:
Chapter 10 Strings, Searches, Sorts, and Modifications Midterm Review By Ben Razon AP Computer Science Period 3.
Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.
Arrays Chapter 8. What if we need to store test scores for all students in our class. We could store each test score as a unique variable: int score1.
Arrays and Array Lists CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
Loops (While and For) CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Collection 105 Yola. To store data in RAM Variables (name all the types with their length) Arrays (one, two or more) Collections and Maps.
Data Structures and Algorithms Lecture 1 Instructor: Quratulain Date: 1 st Sep, 2009.
ArrayList Class An ArrayList is an object that contains a sequence of elements that are ordered by position. An ArrayList is an object that contains a.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 20 Lists, Stacks, Queues, and Priority.
Formatted Output (printf) CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
CSE 110 Review Session Hans Hovanitz, Kate Kincade, and Ian Nall.
Introduction to array: why use arrays ?. Motivational example Problem: Write a program that reads in and stores away 5 double numbers After reading in.
Arrays and ArrayLists Topic 6. One Dimensional Arrays Homogeneous – all of the same type Contiguous – all elements are stored sequentially in memory For.
CSE 1201 Object Oriented Programming ArrayList 1.
Simple algorithms on an array - compute sum and min.
Arrays and Array Lists CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Chapter 9 Introduction to Arrays Fundamentals of Java.
CSE 143 Lecture 3 Implementing ArrayIntList reading: slides created by Marty Stepp and Hélène Martin
Arrays and Array Lists CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos and Alexandra Stefan University of Texas at Arlington 1.
Common Mistakes with Functions CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
CMSC 202 ArrayList Aug 9, 2007.
Chapter 7 – Arrays and Array Lists
Sixth Lecture ArrayList Abstract Class and Interface
Array Lists An array list stores a sequence of values whose size can change. An array list can grow and shrink as needed. ArrayList class supplies methods.
Exercise 1- I/O Write a Java program to input a value for mile and convert it to kilogram. 1 mile = 1.6 kg. import java.util.Scanner; public class MileToKg.
Boolean Expressions and Conditionals (If Statements)
(like an array on steroids)
Exceptions and User Input Validation
John Hurley Cal State LA
Fundamentals of Java: AP Computer Science Essentials, 4th Edition
Software Development Java Collections
Chapter 20 Lists, Stacks, Queues, and Priority Queues
COP 3503 FALL 2012 Shayan Javed Lecture 8
Repetition-Counter control Loop
Data Structures 1 1.
Top Ten Words that Almost Rhyme with “Peas”
Stack Lesson xx   This module shows you the basic elements of a type of linked list called a stack.
Common Mistakes with Functions
Java Array Lists 2/13/2017.
CS 106A, Lecture 19 ArrayLists
Methods (Functions) CSE 1310 – Introduction to Computers and Programming Alexandra Stefan and Vassilis Athitsos University of Texas at Arlington.
7 Arrays.
Chapter 8 Slides from GaddisText
© A+ Computer Science - Arrays and Lists © A+ Computer Science -
CMSC 202 ArrayList Aug 9, 2007.
ArrayLists.
Object Oriented Programming in java
CMSC 202 ArrayList Aug 9, 2007.
Arrays CSE 1310 – Introduction to Computers and Programming
Announcements Lab 7 due Wednesday Assignment 4 due Friday.
Arrays and Array Lists CS 21a.
slides created by Ethan Apter
CSC 221: Computer Programming I Fall 2009
Java Array Lists 2/13/2017.
Lecture 13: ArrayLists AP Computer Science Principles
ArrayLists 22-Feb-19.
CSE 143 Lecture 5 References and Linked Nodes
CSE 143 Lecture 3 Implementing ArrayIntList reading:
Strings CSE 1310 – Introduction to Computers and Programming
CSE 143 Lecture 2 ArrayIntList, binary search
Lecture 6: References and linked nodes reading: 16.1
Arrays & Loops.
Arrays & Loops.
Presentation transcript:

Array Lists CSE 1310 – Introduction to Computers and Programming University of Texas at Arlington Last modified: 4/17/18

DEPARTAMENTAL FINAL EXAM Monday, DEC 10, 5:30pm-8pm rooms will be determined

Limitations of Arrays Fixed size: Hard to insert or remove elements must know the size when you create it. Hard to insert or remove elements Must slide the following ones over Assume that an array has this actual data: 5 names in sorted order. Note that: the array size is 10, but the number of useful items is 5. 1 2 3 4 5 6 7 8 9 "Alice" "Cane" "Jess" "Sue" "Tom" null Insert "Ben" in the correct place so that the array is still sorted. How will the array look now? "Alice", "Ben", "Cane", "Jess", "Sue", "Tom" How will you manipulate the data to achieve this effect? Write the code that implements the action above. Next remove "Jess" : How will the array look now? "Alice", "Ben", "Cane", "Sue", "Tom",

Limitations of Arrays (cont) Applications where this is inconvenient: Reading data from a file and storing it in an array: I do not know the size: how many are there in the file? Phone book program: The user should be allowed to add new entries and remove old entries. Many more…

Array Lists ArrayList is an alternative to an array in Java. It makes it easy to: Initialize without specifying a size. Add elements at the end Remove elements. Insert elements at any position. It automatically adjusts the size as needed based on the operation (add/remove).

ArrayList of Strings Example new … add(val) add(idx, val) get(idx) set(idx, val) remove(idx) remove(val) size() import java.util.Scanner; import java.util.ArrayList; . . . public static void arrayListPractice() { ArrayList<String> strList = new ArrayList<String>();//empty list(size 0) System.out.println(strList); // [] // Note: can be printed directly. strList.add("Alice"); // add/insert a new element at the end strList.add("Cane"); strList.add("Jess"); System.out.println(strList); // [Alice, Cane, Jess] strList.add(1,"Ben"); // insert a new element at index 1 System.out.println(strList); // [Alice, Ben, Cane, Jess] System.out.println(strList.get(2)); // Cane //returns element at given index (2). strList.set(3,"Jody"); // modify existing element from given index System.out.println(strList); // [Alice, Ben, Cane, Jody] strList.remove(0); // remove element from index 0 System.out.println(strList); // [Ben, Cane, Jody] strList.remove("Cane"); // remove element with the given value System.out.println(strList); // [Ben, Jody] System.out.println(strList.size()); // 2 // returns the size (number of items) strList.add(3,"Matt"); // IndexOutOfBoundsException: Index: 3, Size: 2 }

Removing a Value in an Array List Removing Matches (6.8.8., pg 295) Note that if you iterate with a loop over the ArrayList and you remove an element (e.g. because it has a specific value) as the counter gets incremented, you will skip the element coming after the removed one.

Variables Pointing to Same Set This topic is a VERY COMMON SOURCE OF MISUNDERSTANDINGS. – See the array slides. 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.

Sorting ArrayLists with the Collections Class import java.util.Collections; ... Collections.sort(arrList); // sort in reverse order Collections.sort(arrList, Collections.reverseOrder()); System.out.println("Sorted arrayList: " + arrList);

Items of ArrayList must be Objects => use the Integer class instead of int import java.util.ArrayList; … 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); System.out.printf("\n"); for (int i = 0; i < numbers.size(); i++) { System.out.printf("position %d: = %d\n", i, numbers.get(i)); Creates an empty ArrayList object. (initial size is 0) Add number at the end. Automatically converts int to Integer. Automatically adjusts the size. Get the current size (with useful data). Returns the element at index i

See File I/O slides for reading from a file into an ArrayList of strings: ArrayList<String> .

Another Example (Useful student practice)

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.

Finding the Smallest Value Solution for arrays: public static int find_min(int[] vals) { int result = vals[0]; for (int i=0;i<vals.length;i++) if (vals[i] < result) result = vals[i]; } return result; Solution for array lists: public static int find_min(ArrayList<Integer> vals) { int result = vals.get(0); for (int i=0;i<vals.size();i++) if (vals.get(i) < result) result = vals.get(i); } return result;

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;

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. See sample output to the right. Example Output: Enter a number, or q to quit: 40 Enter a number, or q to quit: 10 Enter a number, or q to quit: 80 Enter a number, or q to quit: 90 Enter a number, or q to quit: 20 Enter a number, or q to quit: q position 0: 40 position 1: 10 *** smallest value *** position 2: 80 position 3: 90 *** largest value *** position 4: 20

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

Practice Problems Shift an ArrayList by k positions to the (left or to the right). (Start with special method for k = 1.) Given ArrayList of strings and array of int, find the smallest string from the strings at positions given by the array of int. Given ArrayList of strings return ArrayList of Integer with the lengths of the corresponding strings.