Arrays and ArrayLists Ananda Gunawardena. Introduction Array is a useful and powerful aggregate data structure presence in modern programming languages.

Slides:



Advertisements
Similar presentations
Programming and Data Structure
Advertisements

Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. It is common to use two nested loops when filling or searching: for.
Week 10 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
Chapter 13 ARRAY LISTS AND ARRAYS. CHAPTER GOALS To become familiar with using array lists to collect objects To learn about common array algorithms To.
Chapter 13 ARRAY LISTS AND ARRAYS CHAPTER GOALS –To become familiar with using array lists to collect objects –To learn about common array algorithms –To.
Arrays Chapter 6. Outline Array Basics Arrays in Classes and Methods Sorting Arrays Multidimensional Arrays.
Arrays. Memory organization Table at right shows 16 bytes, each consisting of 8 bits Each byte has an address, shown in the column to the left
For use of IST410 Students only Arrays-1 Arrays. For use of IST410 Students only Arrays-2 Objectives l Declaring arrays l Instantiating arrays l Using.
Lecture 05 - Arrays. Introduction useful and powerful aggregate data structure Arrays allow us to store arbitrary sized sequences of primitive values.
Computer Science A 10: 20/3. Array Array: Sequence of values of the same type Construct array: new double[10] Store in variable of type double[] double[]
1 2-D Arrays Overview l Why do we need Multi-dimensional array l 2-D array declaration l Accessing elements of a 2-D array l Declaration using Initializer.
Arrays. A group of data with same type stored under one variable. It is assumed that elements in that group are ordered in series. In C# language arrays.
Using ArrayList. Lecture Objectives To understand the foundations behind the ArrayList class Explore some of the methods of the ArrayList class.
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.
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.
Chapter 14 Generics and the ArrayList Class Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Arrays. The array data structure An array is an indexed sequence of components –Typically, the array occupies sequential storage locations –The length.
Chapter 8 Arrays and Strings
Chapter 9 Introduction to Arrays
Arrays And ArrayLists - S. Kelly-Bootle
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 l Array Basics l Arrays in Classes and Methods l Programming with Arrays.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 10. Pointers & Dynamic Data Structures.
Week 10 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
Arrays. Arrays as ADTs An array is an Abstract Data Type –The array type has a set of values The values are all the possible arrays –The array type has.
Chapter 8 Arrays and Strings
French Territory of St. Pierre CSE 114 – Computer Science I Arrays.
Comp 248 Introduction to Programming Chapter 6 Arrays Part B Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,
ArrayList, Multidimensional Arrays
Lists Ellen Walker CPSC 201 Data Structures Hiram College.
Arrays. Arrays in Java  Arrays in Java are objects.  Like all objects are created with the new keyword.
5-Aug-2002cse Arrays © 2002 University of Washington1 Arrays CSE 142, Summer 2002 Computer Programming 1
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.
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.
1 © 2002, Cisco Systems, Inc. All rights reserved. Arrays Chapter 7.
Java SE 8 for Programmers, Third Edition
ARRAYS Computer Engineering Department Java Course Asst. Prof. Dr. Ahmet Sayar Kocaeli University - Fall
C++ Programming: From Problem Analysis to Program Design, Second Edition1 Objectives In this chapter you will: Learn about the pointer data type and pointer.
IMPLEMENTING ARRAYLIST – Part 2 COMP 103. RECAP  Abstract Classes – overview, details in 2 nd year  Implementing the ArrayList: size(), get(), set()
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Arrays.
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.
OBJECTS FOR ORGANIZING DATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. : array declaration and use.
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.
Aug 9, CMSC 202 ArrayList. Aug 9, What’s an Array List ArrayList is  a class in the standard Java libraries that can hold any type of object.
Dynamic Array. An Array-Based Implementation - Summary Good things:  Fast, random access of elements  Very memory efficient, very little memory is required.
Arrays. Related data items Collection of the same types of data. Static entity – Same size throughout program.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
CMSC 202 Arrays 2 nd Lecture. Aug 6, Array Parameters Both array indexed variables and entire arrays can be used as arguments to methods –An indexed.
Arrays. Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional  Java.
Arrays. Background  Programmer often need the ability to represent a group of values as a list List may be one-dimensional or multidimensional  Java.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Arrays and ArrayLists Topic 6. One Dimensional Arrays Homogeneous – all of the same type Contiguous – all elements are stored sequentially in memory For.
Arrays Chapter 6. Objectives learn about arrays and how to use them in Java programs learn how to use array parameters and how to define methods that.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Java – An Object Oriented Language CS 307 Lecture Notes Lecture Weeks 5-6 Khalid Siddiqui.
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
int [] scores = new int [10];
Arrays. Arrays as ADTs An array is an Abstract Data Type –The array type has a set of values The values are all the possible arrays –The array type has.
Arrays (part 2) 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
1 ENERGY 211 / CME 211 Lecture 4 September 29, 2008.
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 7A Arrays (Concepts)
Chapter 9 Introduction to Arrays Fundamentals of Java.
LESSON 8: INTRODUCTION TO ARRAYS. Lesson 8: Introduction To Arrays Objectives: Write programs that handle collections of similar items. Declare array.
Principles of Computer Science I
Chapter 8 – Arrays and Array Lists
Computer Programming BCT 1113
Arrays.
Presentation transcript:

Arrays and ArrayLists Ananda Gunawardena

Introduction Array is a useful and powerful aggregate data structure presence in modern programming languages Arrays allow us to store arbitrary sized sequences of primitive values or sequences of references to objects Arrays allow easy access and manipulation to the values/objects that they store Arrays are indexed by a sequence of integers classes can use arrays as instance variables to store databases of value/references

Arrays new is used to construct a new array: new double[10] Store 10 double type variables in an array of doubles double[] data = new double[10];

integer Arrays int[] A = new int[5];

Array of Object References class foo() { ….} foo[ ] myFooList = new foo[N]; 0 1 N-1 Foo[0] Foo[1] Foo[N-1] myFooList

Array of Strings An array of Strings –String[] s = new String[]{"ABC", "LMN", "XYZ"};

Array of Bytes We can create array of bytes and perhaps return them from a method public byte[ ] foo(){ byte[] temp = new byte[10]; for (int i=0;i<10;i++) temp[i] = new Byte(i); return temp; }

Arrays Arrays have fixed length Arrays have element of specific type or references to Objects Operator [ ] is used to access array elements data[4] = 29.95; Use length attribute to get array length. –data.length. (Not a method!)

Array is a homogeneous data structure: each of its members stores the same type (either primitive or reference) the indices go from 0 to one less than the length of the array each array object stores a public final int length instance variable that stores the length of the array we can access the value stored in this field, in the example above, by writing a.length

Copying Arrays Copying an array reference yields a second reference to the same array double[] data = new double[10]; // fill array... double[] prices = data; previousprevious | start | nextstartnext previousprevious | start | nextstartnext

Use clone to make true copy double[] prices = (double[])data.clone(); Cloning Arrays

Copying Array Elements System.arraycopy(from, fromStart, to, toStart, count);

Question Write your own version of arraycopy for int arrays public static void arraycopy(int[] from,int fromstart, int[] to, int tostart, int count) { }

Shifting and Copying System.arraycopy(data, i, data, i + 1, data.length - i - 1); data[i] = x;

System.arraycopy(data, i + 1, data, i, data.length - i - 1); More Shifting

Shifting Elements Shift all elements to Right by 1 starting at index i Shift all elements left by 1 starting at index i (i>0)

Swapping Array Elements Suppose you want to swap two elements in the array, say entries with indices i and j. Assuming we are dealing with an array of ints –int temp = A[i]; // save a copy of A[i] in temp –A [i] = A[j]; // copy the content of A[j] to A[i] –A[j] = temp; // copy the content of temp to A[j] Note that : A[i]= A[j] and A[j] = A[i] do not swap content Exercise: Reverse an array using swaps

Accessing Arrays int[] a = new int[]{4, 2, 0, 1, 3}; system.out.println( a[0] ); if (a[5] == 0)...some statement if the value computed for the index is less than 0, or greater than OR EQUAL TO the length of the array –trying to access the member at an illegal index causes Java to throw the – ArrayIndexOutOfBoundsException which contains a message showing what index was attempted to be accessed

Partially Filled Arrays Array.length = maximum capacity of the array Usually, array is partially filled Need companion variable to keep track of current size final int capacity = 100; double[] data = new double[capacity]; int size = 0; Update size as array is filled: data[size] = x; size++;

Partially Filled Arrays

Remember to stop at dataSize-1 when looking at array elements: for (int i = 0; i < dataSize; i++) sum = sum + data[i]; Be careful not to overfill the array if (dataSize >= data.length) System.out.println("Sorry--array full");

Resizing an Array

Dynamic Arrays Arrays are typically static structures However we can design a new array class that is dynamic (that is, you never run out of space) Java already has a dynamic array class called ArrayList See Java API for arrayList class – ArrayList.html

Dynamic Array Class public class myArrayList { int capacity; …… public void add(Object O){ } … }

Multidimensional Arrays

Dimensions Some application solutions require tables with multiple dimensions –Modeling a matrix require a 2-dimensional array or table –Modeling an application that require 3- dimensional array Example: in Graphics, representing a point (x, y, z)

Two-Dimensional Arrays Matrix with rows and columns Example: Tic Tac Toe board char[][] board = new char[3][3]; board[i][j] = 'x';

Matrix Access A matrix or 2D array require access using two indices. Example: for (int i=0; i<N; i++) for (int j=0; j<N; j++) A[i][j] = 0; Write a method that converts a matrix A to a matrix B, where B[i][j] = A[j][i]

Memory Allocation Java (and many other language compilers) allocate memory for 2D arrays as an array of 1D arrays

ArrayLists java.util Class ArrayList java.lang.Object java.util.AbstractCollection java.util.AbstractList java.util.ArrayList

ArrayList Resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null. In addition to implementing the List interface, this class provides methods to manipulate the size of the array that is used internally to store the list. Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically. The details of the growth policy are not specified beyond the fact that adding an element has constant amortized time cost. An application can increase the capacity of an ArrayList instance before adding a large number of elements using the ensureCapacity operation. This may reduce the amount of incremental reallocation.

ARRAYLIST METHODS See API for More

Summary Arrays are homogeneous linear structures with direct access to content Arrays are simple and easy to use in applications Most applications require use of an array –Sorting, searching