1 Dynamic Arrays  Why Dynamic Arrays?  A Dynamic Array Implementation  The Vector Class  Program Example  Array Versus Vector.

Slides:



Advertisements
Similar presentations
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by.
Advertisements

CSC 205 – Java Programming II Lecture 25 March 8, 2002.
5-May-15 ArrayLists. 2 ArrayList s and arrays A ArrayList is like an array of Object s Differences between arrays and ArrayList s: Arrays have special.
L2. Necessary Java Programming Techniques (Vector) Packages  Java.util import Java.util.*; Classes  Vector Interfaces  Enumeration Java API.
An Array-Based Implementation of the ADT List public class ListArrayBased implements ListInterface { private static final int MAX_LIST = 50; private Object.
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.
For use of Cleveland State's IST410 Students only 1 Vectors and Collections.
1 One-Dimensional (1-D) Array Overview l Why do we need 1-D array l 1-D array declaration and Initialization l Accessing elements of a 1-D array l Passing.
Using final We use the notion of constant data to represent data that cannot be changed. public class Test { static final int someInt = 10; static final.
Using ArrayList. Lecture Objectives To understand the foundations behind the ArrayList class Explore some of the methods of the ArrayList class.
CHAPTER 6 Stacks Array Implementation. 2 Stacks A stack is a linear collection whose elements are added and removed from one end The last element to be.
Unit 291 Java Collections Framework: Interfaces Introduction to the Java Collections Framework (JCF) The Comparator Interface Revisited The Collection.
Vectors. Vectors and arrays A Vector is like an array of Object s Differences between arrays and Vector s: –Arrays have special syntax; Vector s don’t.
1 One-Dimensional Arrays  What are and Why 1-D arrays?  1-D Array Declaration  Accessing elements of a 1-D Array  Initializer List  Passing Array.
CS 106 Introduction to Computer Science I 04 / 30 / 2010 Instructor: Michael Eckmann.
Arrays And ArrayLists - S. Kelly-Bootle
Session 5 java.lang package Using array java.io package: StringTokenizer, ArrayList, Vector Using Generic.
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.
Announcements  I will discuss the labtest and the written test #2 common mistakes, solution, etc. in the next class  not today as I am still waiting.
04/29/ Introduction to Vectors?... A vector is a dynamic array. - It can be expanded and shrunk as required - A Component of a vector can be accessed.
ARRAYLIST.. Hazen High School. Vocabulary to Know ArrayList Generic Class ArrayList Operations ArrayList Methods ArrayList Searching For-Each Wrapper.
Generalized Containers CSIS 3701: Advanced Object Oriented Programming.
French Territory of St. Pierre CSE 114 – Computer Science I Arrays.
ArrayList, Multidimensional Arrays
Lists Ellen Walker CPSC 201 Data Structures Hiram College.
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.00/ Lecture 8 Arrays and Vectors. Arrays-1 Arrays are a simple data structure Arrays store a set of values of the same type – Built-in types.
Arrays of Objects 1 Fall 2012 CS2302: Programming Principles.
CSE 143 Lecture 4 ArrayList Reading: 10.1 slides created by Marty Stepp
Data Design and Implementation. Definitions of Java TYPES Atomic or primitive type A data type whose elements are single, non-decomposable data items.
Arrays Construct array: new double[10] Store in variable of type double[] double[] data = new double[10];
OBJECTS FOR ORGANIZING DATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. : array declaration and use.
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.
Dynamic Data Structures and Generics Chapter 10. Outline Vectors Linked Data Structures Introduction to Generics.
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.
Title Slid CSC 444 Java Programming Arrays By Ralph B. Bisland, Jr.
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.
ArrayLists (and the for-each loop) ArrayList example = new ArrayList (); example.add(4);
Arrays and ArrayLists Topic 6. One Dimensional Arrays Homogeneous – all of the same type Contiguous – all elements are stored sequentially in memory For.
IMPLEMENTING ARRAYLIST COMP 103. RECAP  Comparator and Comparable  Brief look at Exceptions TODAY  Abstract Classes - but note that the details are.
CS 180 Recitation 7 Arrays. Used to store similar values or objects. An array is an indexed collection of data values of the same type. Arrays are the.
Object-Oriented Programming (Java) Review Unit 1 Class Design Basic Console I/O StringTokenizer Exception UML class diagram.
CS1020 Data Structures and Algorithms I Lecture Note #6 Vector and ArrayList.
CS 116: Object Oriented Programming II. Topics Vectors Multidimensional Arrays ArrayList.
The ArrayList Data Structure The Most Important Things to Review.
The ArrayList Data Structure Standard Arrays at High Speed!
1 The copy constructor in the BankAccounts class. Two alternatives here: /** copy constructor */ public BankAccounts(BankAccounts L){ theAccounts = L.theAccounts.clone();
19-Mar-16 Collections and ArrayLists.. 2 Collections Why use Collections. Collections and Object-Orientation. ArrayLists. Special Features. Creating ArrayLists.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 6 GEORGE KOUTSOGIANNAKIS Copyright: 2016 Illinois Institute of Technology/George Koutsogiannakis 1.
An Array-Based Implementation of the ADT List
The Class ArrayLinearList
COP 3503 FALL 2012 Shayan Javed Lecture 8
List Representation - Array
Programming in Java Lecture 11: ArrayList
Arrays of Objects Fall 2012 CS2302: Programming Principles.
Arrays of Objects Fall 2012 CS2302: Programming Principles.
Java Arrays & Strings.
L2. Necessary Java Programming Techniques
Grouped Data Arrays, and Array Lists.
The Vector Class An object of class Vector is similar to an array in that it stores multiple values However, a vector only stores objects does not have.
L2. Necessary Java Programming Techniques
Java Utilities and Bit Manipulation
ArrayLists 22-Feb-19.
Collections Framework
Web Design & Development Lecture 6
Presentation transcript:

1 Dynamic Arrays  Why Dynamic Arrays?  A Dynamic Array Implementation  The Vector Class  Program Example  Array Versus Vector

2 Why Dynamic Arrays?  A problem with arrays is that their size must be fixed at creation.  Thus, once an array of size n is declared, it cannot be extended to hold more than n elements.  But the programmer may not know the size required.  Is there a way out?  Yes, Java provides the Vector class in the java.util package that can grow dynamically as needed.  To understand how it works, we shall implement a similar class.

3 A Dynamic Array Implementation  The following defines a class that works like array but whose size can grow dynamically: public class DynamicArray{ private int[] b; private int numberOfElements; //Constructor: Creates an array with default size of 10 public DynamicArray(){ b = new int[10]; } //Constructor: Creates an array with specified size public DynamicArray(int size){ b = new int[size]; } public int size(){ return numberOfElements; } public int capacity(){ // returns total number of cells return b.length; // including unused ones }

4 A Dynamic Array Implementation public int getElement(int i){ if(i numberOfElements – 1) throw new IllegalArgumentException(“index out of Bounds”); return b[i]; } public void set(int i, int value){ if(i numberOfElements) throw new IllegalArgumentException(“index out of Bounds”); if(i == numberOfElements && i == b.length){ // For efficiency purposes, double the array capacity int[] newb = new int[2*b.length]; for(int k = 0; k < numberOfElements; k++) newb[k] = b[k]; b = newb; } b[i] = value; if(i == numberOfElements) numberOfElements++; }

5 Our Class Versus Array  We can create an instance of our DynamicArray class as follows: DynamicArray c = new DynamicArray(20);  c can be viewed as an int array of size 20. However, c can store more than 20 integers.  How we access and modify content of c is also slightly different: 1. Corresponding to: b[i], we use a function call: c.getElement(i) 2. Corresponding to: b[i] = value ;, we use a function call: c.set(i, value); 3. Corresponding to: b.length, we use a function call: c.capacity()

6 The Vector Class  Vector is similar to our DynamicArray, but it has much more.  It has the following Constructors:  To Create a vector with an initial capacity of 20 elements: Vector v = new Vector(20); Vector() Creates a vector of size 10, It doubles the capacity when exhausted. Vector(int initialCapacity) Creates a vector of size initialCapacity, It doubles the capacity when exhausted. Vector(int initialCapacity, int increment) Creates a vector of size initialCapacity, increases by increment when the capacity is exhausted.

7 Adding an Element  The base type of our DynamicArray is int What about Vector?  The base type of Vector is Object.  Thus, primitive types must be wrapped using wrapper classes.  Elements can be added using the following add method:  The following adds 10 objects into a vector of initial capacity 4: Vector v = new Vector(4); for(int i = 0; i < 10; i++) v.add(new Integer(i*2));  The capacity is automatically increased to take the 10 objects add(Object element) Adds element to the next empty cell, increases the capacity if necessary.

8 Adding an Element (cont’d)  The following add method can also be used to add an element:  The following adds 6 objects into a vector, it then inserts an Integer object with value of 20 at index 3: Vector v = new Vector(4); for(int i = 0; i < 6; i++) v.add(new Integer(i*2)); v.add(3, new Integer(20));  Note that this method does not allow an empty cell in-between: v.add(8, new Integer(100)); // Run-time error, cell 7 will be empty add(int index, Object element) Adds element at index, shifts element at index and beyond, if any, by 1. Increases capacity if necessary. If index size, it throws IndexOutOfBoundsException. reference v

9 Accessing and Changing an Element Object get(int index) Returns the element at index. throws IndexOutOfBoundsException if index size. Object set(int index, Object element) Replaces the object at index with element and returns the replaced object. Throws IndexOutOfBoundsException if index size.  The following method can be used to access an element:  However since the return type is object, we have to cast-down to get the original object.  The following prints the result of dividing the element at index 3 with 2: Integer element = (Integer) v.get(3); System.out.println(element.intValue() / 2);  To modify an element we use the set method:  The following replaces the element at index 3 with 100: v.set(3, new Integer(100));

10 Searching for an Element boolean contains(Object element) Returns true if element is contained in the vector and false otherwise. int indexOf(Object element) Returns the index of element if found; -1 otherwise.  To check if an element is in a vector use the contains method:  The contains method uses the equals method of the vector element in its search.  The following checks if the vector v contains 100: if(v.contains(new Integer(100)) System.out.println(“100 found”); else System.out.println(“100 not found”);  If you also need to know the index of the object when found, use: int index = v.indexOf(new Integer(100)); if(index != -1) System.out.println(“100 found at index ” + index); else System.out.println(“100 not found”);

11 Size versus Capacity int capacity() Returns the current capacity of the vector. int size() Returns the actual number of elements stored in the vector.  Two related accessor methods for the Vector class are:  size() is more useful. It is usually used in a loop to process all the vector elements public static void main(String[] args){ Vector v = new Vector(4); System.out.println(“SIZE\tCAPACITY”); for(int i = 0; i < 10; i++){ v.add(new Integer(i*2)); System.out.println(v.size()+”\t” + v.capacity()); } for(int i = 0; i < v.size(); i++) System.out.println(v.get(I) + “ “); } Output: SIZE CAPACITY

12 Removing an Element boolean remove(Object element) Removes element from the vector and returns true if successful; returns false if element is not found. The elements after the removed element are shifted to the left Object remove(int index) Removes element at index and returns it; throws IndexOutOfBoundsException if index size. The elements after the removed element are shifted to the left void trimToSize() Trims the capacity of this vector to be the vector’s current size.  An element can be removed from a vector using any of the following methods:  The following removes 100 from a vector v and prints a message if successful: if(v.remove(new Integer(100)) System.out.println(“100 removed”); else System.out.println(“100 not found”);  Does the capacity of a vector shrink automatically after a deletion?:  No. However, we can use the following method to shrink it:

13 Program Example  The following example reads an unknown number of grades, it then prints the average and the grades above the average: public static void main(String[] args)throws IOException{ Vector grade = new Vector(); readGrades(grade); double average = getAverage(grade); System.out.print(“The average grade is: “ + average); System.out.print(“Grades above average are: “); printAboveAverage(grade, average); } public static void readGrades(Vector v)throws IOException{ BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); System.out.print(“Enter grade: “); double value = Double.parseDouble(stdin.readLine()); while(value >= 0){ v.add(new Double(value)); System.out.print(“Enter next grade(negative value to terminate): “ ); value = Double.parseDouble(stdin.readLine()); }

14 Program Example (cont’d) public static double getAverage(Vector v){ if(v.size() == 0) throw new IllegalArgumentException(“vector size is zero”); double sum = 0; for(int i = 0; i < v.size(); i++){ Double element = (Double) v.get(i); sum = sum + element.doubleValue(); } return sum/v.size(); } public static void printAboveAverage(Vector v, double average){ for(int i = 0; i < v.size(); i++){ Double element = (Double) v.get(i); if(element.doubleValue() > average) System.out.println(element); }

15 Array versus Vector  Vectors can grow and shrink, arrays cannot.  Vector elements must be object references. Array elements can be object references or a primitive type.