Arrays and ArrayLists Topic 6. One Dimensional Arrays Homogeneous – all of the same type Contiguous – all elements are stored sequentially in memory For.

Slides:



Advertisements
Similar presentations
Lists and the Collection Interface Chapter 4. Chapter Objectives To become familiar with the List interface To understand how to write an array-based.
Advertisements

Arrays.
Hip Hip Array! AP Computer Science. Remember Strings? Strings are an array of characters An array is a collection of variables all of the same type. Arrays.
CSC 205 – Java Programming II Lecture 25 March 8, 2002.
An Array-Based Implementation of the ADT List public class ListArrayBased implements ListInterface { private static final int MAX_LIST = 50; private Object.
CIT 590 Intro to Programming Java lecture 4. Agenda Types Collections – Arrays, ArrayLists, HashMaps Variable scoping Access modifiers – public, private,
Lecture 05 - Arrays. Introduction useful and powerful aggregate data structure Arrays allow us to store arbitrary sized sequences of primitive values.
Chapter 7 – Arrays.
Loops Notes adapted from Dr. Flores. It repeats a set of statements while a condition is true. while (condition) { execute these statements; } “while”
Datalogi A 8: 27/10. Array Array: Sequence of values of the same type Construct array: new double[10] Store in variable of type double[] double[] data.
Lists and the Collection Interface Chapter 4. Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.
1 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 8 focuses on: array declaration and use passing arrays and array.
Fall 2007CS 2251 Lists and the Collection Interface Chapter 4.
CSC 142 J 1 CSC 142 Arrays [Reading: chapter 10].
One Dimensional Arrays. Declaring references to array objects How would you declare a variable somearray that is an array of ints? int[] somearray;
Arrays And ArrayLists - S. Kelly-Bootle
Week 10 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
1 ArrayList  Array’s are limited because we need to know the size before we use them.  An ArrayList is an extension of an array that grows and shrinks.
AP CS Workshop ArrayList It is very common for applications to require us to store a large amount of data. Array lists store large amounts of data.
French Territory of St. Pierre CSE 114 – Computer Science I Arrays.
ArrayList, Multidimensional Arrays
Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 9 Arrays.
ARRAYS 1 Week 2. Data Structures  Data structure  A particular way of storing and organising data in a computer so that it can be used efficiently 
JAVA Array 8-1 Outline  Extra material  Array of Objects  enhanced-for Loop  Class Array  Passing Arrays as Arguments to Methods  Returning Arrays.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
AP Comp Sci A Chapter 12 - Arrays. Ch 12 Goals: Goals: Declare and create arrays Declare and create arrays Access elements in arrays Access elements in.
Arrays and ArrayLists in Java L. Kedigh. Array Characteristics List of values. A list of values where every member is of the same type. Each member in.
Chapter 8: Arrays.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Arrays An array is a data structure that consists of an ordered collection of similar items (where “similar items” means items of the same type.) An array.
Arrays Construct array: new double[10] Store in variable of type double[] double[] data = new double[10];
M180: Data Structures & Algorithms in Java Arrays in Java Arab Open University 1.
Chapter overview This chapter focuses on Array declaration and use Bounds checking and capacity Arrays storing object references Variable length parameter.
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.
(c) University of Washington15-1 CSC 143 Java List Implementation via Arrays Reading: 13.
ArrayList By Neil Butcher. What is the difference between an ArrayList and an Array? An ArrayList is in many ways similar to an array, but has a few subtle.
Week # 2: Arrays.  Data structure  A particular way of storing and organising data in a computer so that it can be used efficiently  Types of data.
AP Computer Science edition Review 1 ArrayListsWhile loopsString MethodsMethodsErrors
Arrays…JavaCPython have fixed lengthyes*yesno are initialized to default values yesno? track their own lengthyesnoyes trying to access “out of bounds”
Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006 by Maria Litvin, Gary Litvin, and Skylight.
MCQ Which is the correct syntax for placing the string "boat" into an ArrayList name recVehicles in position 3 (index 2) for the first time? a)recVehicles.set(3,
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 7.
UniMAP Sem2-10/11 DKT121: Fundamental of Computer Programming1 Arrays.
CS1020 Data Structures and Algorithms I Lecture Note #2 Arrays.
Two Dimensional Arrays Found in chapter 8, Section 8.9.
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
Puzzle 2 1  what does the following program print? public class Puzzle02 { public static void main(String[] args) { final long MICROS_PER_DAY = 24 * 60.
Arrays and Array Lists CS 21a. Problem 1: Reversing Input Problem: Read in three numbers and then print out the numbers in reverse order Straightforward.
SEQUENTIAL AND OBJECT ORIENTED PROGRAMMING Arrays.
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 7A Arrays (Concepts)
Chapter 9 Introduction to Arrays Fundamentals of Java.
Arrays. What is an array? An array is a collection of data types. For example, what if I wanted to 10 different integers? int num1; int num2; int num3;
KUKUM-06/07 EKT120: Computer Programming 1 Week 6 Arrays-Part 1.
LESSON 8: INTRODUCTION TO ARRAYS. Lesson 8: Introduction To Arrays Objectives: Write programs that handle collections of similar items. Declare array.
Can store many of the same kind of data together
Arrays We often want to organize objects or primitive data in a way that makes them easy to access and change. An array is simple but powerful way to.
EKT150 : Computer Programming
Grouped Data Arrays, and Array Lists.
Arrays and Array Lists CS 21a.
ArrayLists 22-Feb-19.
Can store many of the same kind of data together
Dr. Sampath Jayarathna Cal Poly Pomona
slides created by Ethan Apter and Marty Stepp
Review for Midterm 3.
First Semester Review.
Arrays.
Presentation transcript:

Arrays and ArrayLists Topic 6

One Dimensional Arrays Homogeneous – all of the same type Contiguous – all elements are stored sequentially in memory For an array of size n, valid indexed elements in an array range from 0 to n – 1 Individual elements are referenced using their index (subscript) If an invalid index is referenced, an ArrayIndexOutOfBoundsException is thrown

One Dimensional Arrays General Syntax – Declarations: dataType[] variableName; dataType variableName[]; dataType[] varName1, varName2; – Initializations: variableName = new dataType[size]; variableName = {elmt1, elmt2, elmt3, elmt4, …}; – Declaration/Initializations: dataType[] varName = new dataType[size]; dataType varName[] = new dataType[size]; dataType[] varName1 = new dataType[size1], varName2 = new dataType[size2]; dataType can be ANY data type, primitive or reference – There are some implications of creating an array of reference data type – Be careful of NullPointerExceptions! Initializing elements (see above) – variableName[0] = value0; variableName[1] = value1; etc

One Dimensional Arrays Length – A Java array has a final public instance variable (constant) called length Note this is a field, not a method For declaration: int[] ar = new int[5]; ar.length is an int with the value of 5 – Often used as a bound – i.e.: while(x < ar.length) for(int i = 0; i < ar.length; i++) Here an off by one error could cause an ArrayIndexOutOfBoundsException

One Dimensional Arrays Traversing an array – for loop most often used – for each loop (also called enhanced for loop) for(dataType dummyVar : iterator) – dataType must match the list you are iterating through – dummyVar continually references each element in the list linearly – Iterator is the list you want to iterate through; can be any type of list (array, ArrayList, etc) for each loop caveat – can’t replace or remove elements – Note a for each loop can change array elements if they are reference variables being accessed through methods (example: for an array of BankAccount variables, withdrawal $50 from each account) – Exercise 1: count the number of even numbers that exist in an array of type int – Exercise 2: change even indexed elements in an int array to the value of 0

Arrays as Parameters Passing an array as a parameter means passing its object reference (no copy is made) – Thus the elements of the actual array can be accessed and modified Example 1 – array elements accessed but not modified – public static int findMin(int[] arr) Example 2 – array elements modified – public static void squareContents(int[] arr) Example 3 – public static void swap(int[] arr, int i, int j) Example 4 – public int[] getIntegers()

KENO Array Project (Keno).doc

Arrays and Classes Arrays as class variables – Deck.java Data: – private int[] myDeck; – public static final int NUMCARDS = 52; Methods – Deck() – public void writeDeck() – private void swap(int[] arr, int i, int j) – public void shuffle() Array of class objects – ManyDecks.java Data: – private Deck[] allDecks; – public static final int NUMDECKS = 500; Methods – ManyDecks() – public void shuffleAll() – public void printDecks()

Two Dimensional Arrays Declarations – int [][] table;//table currently a null reference – double [][] matrix = new double[3][4]; //3x4 array of real numbers, each element is 0.0 – String [][] strs = new String[2][5]; //2x5 array of String objects, each element is null – int [][] mat = {{3, 4, 5}, {6, 7, 8}};//2x3 array Processing a 2-D array – nested for loops

Two Dimensional Arrays For declaration: int [][] mat = new int[3][4]; – mat[r][c] represents element at row r, column c Valid values for r are 0 – 2 Valid values for c are 0 – 3 – Rows are numbered from 0 – mat.length - 1 – Columns are numbered from 0 – mat[r].length – 1 – To use a for each loop: for(int[] row : mat) for(int element : row) //executable statement

Two Dimensional Arrays Example 1: Find the sum of all elements in a matrix (2- d array) mat Example 2: Write a method that returns an array which holds the values of the sum of each row of a matrix Example 3: Write a method that returns an array which holds the values of the sum of each column in a matrix Example 4: Add 10 to each element in row 2 of a matrix mat Example 5: Write a method that returns a double which is equal to the sum of the major left to right diagonal of a matrix

ArrayLists In util package Can grow and shrink as needed size() can access the number of elements currently in the ArrayList Indexes range from 0 to arrayList.size() – 1 Insertion or deletion of elements can be done with a single statement Is in Collections API – prepackaged data structures – implementation of these container classes should not concern the programmer No primitive types in Collections classes – must contain objects – Remember auto-boxing and unboxing

ArrayLists Methods to know – boolean add(E obj) – int size() – E get(int index) – E set(int index, E element) – void add(int index, E element) – E remove(int index)

ArrayList Example Example 1: practice ArrayList methods Example 2: print the elements in an ArrayList, one per line Example 3: write a method with the following pre and post conditions and header: – Precondition: ArrayList list contains Integer values sorted in increasing order – Postcondition: value inserted in its correct position in list – public static void insert(ArrayList list, Integer value) Example 4: write a method that returns an ArrayList (of user entered size) of random integers from -50 to 50 Example 5: write a method that swaps two values in list, indexed at I and j Example 6: write a method that prints all negatives in list a (assume that list contains Integer values) Example 7: write a method that changes every even-indexed element of strList to the empty String (assume that strList contains String values)