CS1020 Data Structures and Algorithms I Lecture Note #6 Vector and ArrayList.

Slides:



Advertisements
Similar presentations
Why not just use Arrays? Java ArrayLists.
Advertisements

11 Copyright © 2005, Oracle. All rights reserved. Using Arrays and Collections.
The ArrayList Class and the enum Keyword
1 Various Methods of Populating Arrays Randomly generated integers.
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.
For use of Cleveland State's IST410 Students only 1 Vectors and Collections.
1 Dynamic Arrays  Why Dynamic Arrays?  A Dynamic Array Implementation  The Vector Class  Program Example  Array Versus Vector.
Using ArrayList. Lecture Objectives To understand the foundations behind the ArrayList class Explore some of the methods of the ArrayList class.
25-Jun-15 Vectors. 2 Vectors and arrays A Vector is like an array of Object s Differences between arrays and Vector s: Arrays have special syntax; Vector.
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.
CS1020 Data Structures and Algorithms I Lecture Note #4 Collection of Data.
CS 106 Introduction to Computer Science I 04 / 30 / 2010 Instructor: Michael Eckmann.
Week 4-5 Java Programming. Loops What is a loop? Loop is code that repeats itself a certain number of times There are two types of loops: For loop Used.
CompSci 100E Gambler's Ruin  One approach. Monte Carlo simulation.  Flip digital coins and see what happens. o Pseudorandom number generation ojava.util.Random.
Session 5 java.lang package Using array java.io package: StringTokenizer, ArrayList, Vector Using Generic.
CS1101: Programming Methodology Aaron Tan.
Copyright © Texas Education Agency, Advanced Computer Programming Data Structures: Collections.
Methods (Functions) CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 22 Java Collections.
Recitation 1 CS0445 Data Structures Mehmud Abliz.
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.
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.
Generalized Containers CSIS 3701: Advanced Object Oriented Programming.
ArrayList, Multidimensional Arrays
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
CSE 143 Lecture 4 ArrayList Reading: 10.1 slides created by Marty Stepp
Chapter 18 Java Collections Framework
1 TCSS 143, Autumn 2004 Lecture Notes Java Collection Framework: Maps and Sets.
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 8 Collection.
Arrays Construct array: new double[10] Store in variable of type double[] double[] data = new double[10];
1 while loops. 2 Definite loops definite loop: A loop that executes a known number of times.  The for loops we have seen so far are definite loops. We.
Collection of Data. Objectives [CS1020 Lecture 4: Collection of Data] 2 Using arrays Generics: Allowing operations not tired to a specific data type Classes:
1 Generics Chapter 21 Liang, Introduction to Java Programming.
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.
CompSci 100E Functions (Static Methods)  Java function.  Takes zero or more input arguments.  Returns one output value.  Applications.  Scientists.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 20 Lists, Stacks, Queues, and Priority.
CS1020 Data Structures and Algorithms I Lecture Note #2 Arrays.
Arrays (part 2) 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
import java.util.Scanner; class myCode { public static void main(String[] args) { Scanner input= new Scanner(System.in); int num1; System.out.println(“Enter.
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 6_1 GEORGE KOUTSOGIANNAKIS Copyright: FALL 2015 Illinois Institute of Technology- George Koutsogiannakis 1.
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.
CSE 143 Lecture 3 Implementing ArrayIntList reading: slides created by Marty Stepp and Hélène Martin
Coming up Implementation vs. Interface The Truth about variables Comparing strings HashMaps.
 2016, Marcus Biel, ArrayList Marcus Biel, Software Craftsman
1 CS162: Introduction to Computer Science II Abstract Data Types.
An Array-Based Implementation of the ADT List
COP 3503 FALL 2012 Shayan Javed Lecture 8
TK1114 Computer Programming
Chapter 4 Unordered List.
TCSS 143, Autumn 2004 Lecture Notes
ArrayLists.
Programming in Java Lecture 11: ArrayList
MSIS 655 Advanced Business Applications Programming
Arrays and Collections
ArrayLists 22-Feb-19.
Collections Framework
Programming II (CS300) Chapter 02: Using Objects Java ArrayList Class
ArrayLists.
ArrayLists 27-Apr-19.
Web Design & Development Lecture 6
Data Structures and Algorithms 2/2561
Presentation transcript:

CS1020 Data Structures and Algorithms I Lecture Note #6 Vector and ArrayList

Objectives [CS1020 Lecture 6: Vector and ArrayList] 2 Using the Vector and ArrayList classes

References 3 CS1020 website  Resources  Lectures ~cs1020/2_resources/lectures. htmlhttp:// ~cs1020/2_resources/lectures. html [CS1020 Lecture 6: Vector and ArrayList]

Outline 1.Vector 1.1Motivation 1.2API Documentation 1.3Example 2.ArrayList 2.1Introduction 2.2API Documentation 2.3Example 4 [CS1020 Lecture 6: Vector and ArrayList]

Drawback of Arrays 5 Array, as discussed in week 2, has a major drawback:  Once initialized, the array size is fixed  Reconstruction is required if the array size changes  To overcome such limitation, we can use some classes related to array Java has an Array class  Check API documentation and explore it yourself However, we will not be using this Array class much; we will be using other classes such as Vector and ArrayList [CS1020 Lecture 6: Vector and ArrayList]

Vector and ArrayList 6 Both provide re-sizable array, i.e. array that is growable Both are implementations of the List interface  We will cover interface later, under Abstract Data Types (ADTs) Differences between Vector and ArrayList are in slide 15 [CS1020 Lecture 6: Vector and ArrayList]

1 Vector class Class for dynamic-size arrays

Motivation 8 1. Vector Java offers a Vector class to provide:  Dynamic size expands or shrinks automatically  Generic allows any reference data types  Useful predefined methods Use array if the size is fixed; use Vector if the size may change. [CS1020 Lecture 6: Vector and ArrayList]

API documentation (1/3) 9 1. Vector [CS1020 Lecture 6: Vector and ArrayList]

API documentation (2/3) Vector //Declaration of a Vector reference Vector myVector; //Initialize a empty Vector object myVector = new Vector (); SYNTAX PACKAGE import java.util.Vector; Commonly Used Method Summary booleanisEmpty() Tests if this vector has no components. intsize() Returns the number of components in this vector. [CS1020 Lecture 6: Vector and ArrayList]

API documentation (3/3) Vector Commonly Used Method Summary (continued) boolean add(E o) Appends the specified element to the end of this Vector. void add(int index, E element) Inserts the specified element at the specified position in this Vector. E remove(int index) Removes the element at the specified position in this Vector. boolean remove(Object o) Removes the first occurrence of the specified element in this Vector If the Vector does not contain the element, it is unchanged. E get(int index) Returns the element at the specified position in this Vector. int indexOf(Object elem) Searches for the first occurrence of the given argument, testing for equality using the equals method. boolean contains(Object elem) Tests if the specified object is a component in this vector. [CS1020 Lecture 6: Vector and ArrayList]

Example Vector import java.util.Vector; public class TestVector { public static void main(String[] args) { Vector courses; courses = new Vector (); courses.add("CS1020"); courses.add(0, "CS1010"); courses.add("CS2010"); System.out.println(courses); System.out.println("At index 0: " + courses.get(0)); if (courses.contains("CS1020")) System.out.println("CS1020 is in courses"); courses.remove("CS1020"); for (String c: courses) System.out.println(c); } TestVector.java Output: [CS1010, CS1020, CS2010] At index 0: CS1010 CS1020 is in courses CS1010 CS2010 Vector class has a nice toString() method that prints all elements The enhanced for-loop is applicable to Vector objects too! [CS1020 Lecture 6: Vector and ArrayList]

2 ArrayList class Another class for dynamic-size arrays

Introduction (1/2) ArrayList Java offers an ArrayList class to provide similar features as Vector:  Dynamic size expands or shrinks automatically  Generic allows any reference data types  Useful predefined methods Similarities:  Both are index-based and use an array internally  Both maintain insertion order of element So, what are the differences between Vector and ArrayList?  This is one of the most frequently asked questions, and at interviews! [CS1020 Lecture 6: Vector and ArrayList]

Introduction (2/2) ArrayList Differences between Vector and ArrayList VectorArrayList Since JDK 1.0Since JDK 1.2 Synchronised * (thread-safe)Not synchronised Slower (price of synchronisation) Faster (  20 – 30%) Expansion: default to double the size of its array (can be set) Expansion: increases its size by  50% ArrayList is preferred if you do not need synchronisation Java supports multiple threads, and these threads may read from/write to the same variables, objects and resources. Synchronisation is a mechanism to ensure that Java thread can execute an object’s synchronised methods one at a time. When using Vector /ArrayList, always try to initialise to the largest capacity that your program will need, since expanding the array is costly. Array expansion: allocate a larger array and copy contents of old array to the new one [CS1020 Lecture 6: Vector and ArrayList]

API documentation (1/3) ArrayList [CS1020 Lecture 6: Vector and ArrayList]

API documentation (2/3) ArrayList //Declaration of a ArrayList reference ArrayList myArrayList; //Initialize a empty ArrayList object myArrayList = new ArrayList (); SYNTAX PACKAGE import java.util.ArrayList; Commonly Used Method Summary booleanisEmpty() Returns true if this list contains no element. intsize() Returns the number of elements in this list. [CS1020 Lecture 6: Vector and ArrayList]

API documentation (3/3) ArrayList Commonly Used Method Summary (continued) boolean add(E e) Appends the specified element to the end of this list. void add(int index, E element) Inserts the specified element at the specified position in this list. E remove(int index) Removes the element at the specified position in this list. boolean remove(Object o) Removes the first occurrence of the specified element from this list, if it is present. E get(int index) Returns the element at the specified position in this list. int indexOf(Object o) Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element. boolean contains(Object elem) Returns true if this list contains the specified element. [CS1020 Lecture 6: Vector and ArrayList]

Example ArrayList import java.util.ArrayList; import java.util.Scanner; public class TestArrayList { public static void main(String[] args) { Scanner sc = new Scanner(System.in); ArrayList list = new ArrayList (); System.out.println("Enter a list of integers, press ctrl-d to end."); while (sc.hasNext()) { list.add(sc.nextInt()); } System.out.println(list); // using ArrayList's toString() // Move first value to last list.add(list.remove(0)); System.out.println(list); } TestArrayList.java Output: Enter a list... to end (user pressed ctrl-d here) [31, 17, -5, 26, 50] [17, -5, 26, 50, 31] [CS1020 Lecture 6: Vector and ArrayList]

Practice Exercises 20 A bumper crop of practice exercises (exercises 15 – 21) are mounted on CodeCrunch this week The files are also available on the CS1020 website: You are urged to work on these exercise as they are important for you to cement your basic understanding of the topics that are covered so far (OOP and arrays) [CS1020 Lecture 6: Vector and ArrayList]

Practice Exercises 21 #15: Missing Digits version 2  Using Vector #16: Set Containment  Using ArrayList and writing your own class #17: Nearest Points  Using ArrayList and Point [CS1020 Lecture 6: Vector and ArrayList] Vector and ArrayList OOP #18: Overlapping Rectangles Version 2 #19: Overlapping Rectangles Version 3 #20: Redeem Coupon OOP and ArrayList #21: Turning Knobs

Detecting Duplicates (1/4) 22 Additional Exercise Using ArrayList class and random number generation.  You may use the Math random() method or the Random class Write a program DetectDuplicates.java to read the following values:  The number of unique random integers to generate; and  Limit of the values: each random number generated should be in the range from 0 (inclusive) to limit (exclusive), or [0, limit – 1].  (Certainly, the second input value must not be smaller than the first) Each time a random integer is generated, you must check if it is a duplicate of an earlier generated value. If it is, it must be discarded. The program goes on to generate the required number of unique random integers. You are to count how many duplicates were detected. [CS1020 Lecture 6: Vector and ArrayList]

Detecting Duplicates (2/4) 23 Additional Exercise Sample run  (In testing your code, each time a random number is generated, you may want to print it to check that the computation is correct) Enter number of unique integers to generate: 10 Enter limit: 20 List: [16, 3, 15, 17, 2, 10, 18, 5, 12, 14] Duplicates detected: 8 [CS1020 Lecture 6: Vector and ArrayList]

Detecting Duplicates (3/4) 24 Additional Exercise import java.util.*; public class DetectDuplicates { public static void main(String[] args) { Scanner sc = new Scanner(System.in); ArrayList list = new ArrayList (); System.out.print("Enter number of unique...: "); int numUnique = sc.nextInt(); System.out.print("Enter limit: "); int limit = sc.nextInt(); Random rnd = new Random(); int countUnique = 0; int countDuplicates = 0; int num; // the random number DetectDuplicates.java [CS1020 Lecture 6: Vector and ArrayList]

Detecting Duplicates (4/4) 25 Additional Exercise System.out.println("List: " + list); System.out.println("Duplicates detected: " + countDuplicates); } DetectDuplicates.java  [CS1020 Lecture 6: Vector and ArrayList]

End of file