The ArrayList Data Structure Standard Arrays at High Speed!

Slides:



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

Lists and the Collection Interface Chapter 4. Chapter Objectives To become familiar with the List interface To understand how to write an array-based.
Generics and the ArrayList Class
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.
OO Programming Objectives for today: Casting Objects Introduction to Vectors The instanceof keyword.
Arrays.
CS 106 Introduction to Computer Science I 11 / 09 / 2007 Instructor: Michael Eckmann.
Slides prepared by Rose Williams, Binghamton University Chapter 14 Generics and the ArrayList Class.
Loops Notes adapted from Dr. Flores. It repeats a set of statements while a condition is true. while (condition) { execute these statements; } “while”
Using ArrayList. Lecture Objectives To understand the foundations behind the ArrayList class Explore some of the methods of the ArrayList class.
Lists and the Collection Interface Chapter 4. Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.
ECE122 L11: For loops and Arrays March 8, 2007 ECE 122 Engineering Problem Solving with Java Lecture 11 For Loops and Arrays.
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.
Slides prepared by Rose Williams, Binghamton University Chapter 14 Generics and the ArrayList Class.
Chapter 14 Generics and the ArrayList Class Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Fall 2007CS 2251 Lists and the Collection Interface Chapter 4.
CS 106 Introduction to Computer Science I 03 / 30 / 2007 Instructor: Michael Eckmann.
Aalborg Media Lab 28-Jun-15 Software Design Lecture 8 “Arrays”
15-Jul-15 Generics. ArrayList s and arrays A ArrayList is like an array of Object s, but... Arrays use [ ] syntax; ArrayList s use object syntax An ArrayList.
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.
Programming With Java ICS201 University Of Ha’il1 Chapter 14 Generics and The ArrayList Class.
P Object type and wrapper classes p Object methods p Generic classes p Interfaces and iterators Generic Programming Data Structures and Other Objects Using.
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.
Chapter 10 Strings, Searches, Sorts, and Modifications Midterm Review By Ben Razon AP Computer Science Period 3.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
GENERIC COLLECTIONS. Type-Wrapper Classes  Each primitive type has a corresponding type- wrapper class (in package java.lang).  These classes are called.
ArrayList, Multidimensional Arrays
Lists Ellen Walker CPSC 201 Data Structures Hiram College.
What is an Array? An array is a collection of variables. Arrays have three important properties: –group of related items(for example, temperature for.
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 14 Generics and the ArrayList Class Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights.
Arrays Construct array: new double[10] Store in variable of type double[] double[] data = new double[10];
1 Building Java Programs Chapter 7: Arrays These lecture notes are copyright (C) Marty Stepp and Stuart Reges, They may not be rehosted, sold, or.
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.
Some Standard Classes Goals The Object class The String class Wrapper classes The Math class Random Numbers.
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.
AP Computer Science edition Review 1 ArrayListsWhile loopsString MethodsMethodsErrors
The Math Class Methods Utilizing the Important Math Operations of Java!
©SoftMoore ConsultingSlide 1 Generics “Generics constitute the most significant change in the Java programming language since the 1.0 release.” – Cay Horstmann.
The ArrayList Data Structure Standard Arrays at High Speed! More Safety, More Efficient, and Less Overhead!
List Interface and Linked List Mrs. Furman March 25, 2010.
1 CSC 2053 New from AutoBoxing 3 Before J2SE 5.0, working with primitive types required the repetitive work of converting between the primitive.
CSE 1201 Object Oriented Programming ArrayList 1.
Java Software Solutions Lewis and Loftus Chapter 6 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Objects for Organizing Data.
ArrayList JavaMethods An Introduction to Object-Oriented Programming Maria Litvin Gary Litvin Copyright © 2003 by Maria Litvin, Gary Litvin, and Skylight.
Chapter 12 The ArrayList Data Structure Section 1 - How to Instantiate an ArrayList Section 2 - The ArrayList Subset Section 3 - Declaring an ArrayList.
The ArrayList Data Structure The Most Important Things to Review.
1 Chapter 21 Generics. 2 Objectives F To use generic classes and interfaces (§21.2). F To declare generic classes and interfaces (§21.3). F To understand.
Chapter 9 Introduction to Arrays Fundamentals of Java.
Chapter VII: Arrays.
Fundamentals of Java: AP Computer Science Essentials, 4th Edition
The ArrayList Class An ArrayList is a complex data structure that allows you to add or remove objects from a list and it changes size automatically. The.
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.
Arrays versus ArrayList
CMSC 202 ArrayList Aug 9, 2007.
Topics Covered: Arrays, 1-D & 2-D Passing & Returning Arrays
Object Oriented Programming in java
CMSC 202 ArrayList Aug 9, 2007.
Grouped Data Arrays, and Array Lists.
ArrayLists 22-Feb-19.
Can store many of the same kind of data together
Review of Previous Lesson
Review: libraries and packages
Arrays.
Presentation transcript:

The ArrayList Data Structure Standard Arrays at High Speed!

The Java ArrayList Class Java provides an ArrayList class to make it easier to work with arrays. An ArrayList is a one-dimensional array. There is a lot of overhead code to set up a standard array, fill it, track its logical size, and manipulate values in the array. An ArrayList make these operations easier. However, an ArrayList holds only objects, not primitive values like int, double, char or boolean. But in particular Java has the Integer and Double classes so you can place numbers in an ArrayList.

Instantiating an ArrayList When you declare a standard array, you have to tell Java a fixed number of memory locations that you want the array to contain. During the run of a program, this cannot be changed unless you create a new standard array and copy all of the elements to it. This would be awkward to do and implement in every program that uses standard arrays. When you declare an ArrayList, you don’t have to tell Java how much storage space you need. The ArrayList will be created for a beginning amount and then it will automatically resize itself when it becomes full and more elements need to be added.

Instantiating an ArrayList Declaring and instantiating a standard array: double [ ] nums = new double [20]; Declaring and instantiating an ArrayList: ArrayList nums = new ArrayList ( ); No square bracket [ ] notation is used for an ArrayList. Note the use of the templating angle brackets that enclose the type of object to be placed in the array.

Instantiating an ArrayList Declaring and instantiating an ArrayList of other types: ArrayList nums = new ArrayList ( ); ArrayList names = new ArrayList ( ); ArrayList students = new ArrayList ( ); ArrayList shapes = new ArrayList ( ); The ArrayList API says that all of the above ArrayLists will be constructed with an initial capacity of ten. Note the empty ( ) parentheses at the end of the constructor call. Don’t forget to include these.

Instantiating an ArrayList You can declare and instantiate an ArrayList with an initial capacity of a certain size if you know approximately how many elements you will place in the ArrayList. The only real reason to do this is to keep the ArrayList from automatically resizing itself over and over again until all of the elements have been added to the ArrayList. However, this is not particularly inefficient for today’s computers unless you need to store many elements. For example, if you know you will have 1000 random integers in an ArrayList, you could use: ArrayList nums = new ArrayList (1000 );

Raw or Generic ArrayList? When you instantiate an ArrayList as you have just seen, we call it a generic ArrayList, because the programmer must specify the element type for the list as in … ArrayList names = new ArrayList ( ); Making a generic ArrayList with templating became available beginning with Java 1.5 (Java 5) and higher. Prior to that, programmers could only make a raw ArrayList, where you could put all kinds of objects in the same ArrayList, but care had to be taken to makes sure only put one kind of object in a list. You can still declare and instantiate a raw ArrayList, like the following, but most compilers will “complain” and at least give you a warning. ArrayList names = new ArrayList ( );

Advantages of ArrayList Operations are much much easier and less complex for: traversing an ArrayList (accessing the elements to print or perform an operation on) insertions anywhere in the ArrayList removals anywhere in the ArrayList searching an ArrayList An ArrayList tracks its own logical size and grows or shrinks automatically depending on the number of elements it has.

ArrayList Differences Instead of using [] to manipulate elements, methods are called to perform operations. An ArrayList tracks its logical size and physical size. We don’t necessarily know what the physical size is and we don’t need to, because if more memory locations are needed then it will automatically resize itself. It is helpful to be able to access the logical size of an ArrayList when performing certain operation. The size() method is used to find the number of elements in the list. The logical size is 0 when an ArrayList is created and its logical size is automatically adjusted when an element is added or deleted. An ArrayList does have indices and the positions of the elements range from index 0 to index logical size - 1.

java.util.ArrayList The ArrayList class is part of the java.util package. So it is necessary to import the class using: import java.util.ArrayList; The ArrayList class implements the List interface. That means that the ArrayList class must have all of the methods that are defined in the List interface. You will learn more about interfaces very soon, but we want to make you familiar with this fact now. The formal way to state this is: class java.util.ArrayList implements java.util.List The E in simply stands for any kind of object or class name.

Declaring Variables of type List Declaring and instantiating an ArrayList where the variable is of type List interface is the preferred way to go: List students = new ArrayList ( ); Declaring variables of type List has an advantage in some circumstances. One is we may want a LinkedList instead of an ArrayList. So we would just change: List students = new LinkedList ( ); So the only code in an entire program that needs to change is the name of the class after the word new in the constructor.

Declaring Variables of type List Also, if we declare the variable shapes to be of type List, then if the Shape is the parent of several classes like Circle, Rectangle, and Triangle, then we can hold all of those kinds of objects in the same list. This can be a real advantage. Now you are starting to learn about inheritance! List shapes = new ArrayList ( );

The ArrayList Subset of Methods There are many methods in the ArrayList class if you look up its API on line. However, we only want to work with a few methods of the ArrayList class … those in particular that you are expected to know for the AP Exam. You might not receive full credit on a free response coding question if you try to use methods other than the ones specified by the College Board. The specified methods and what they do are listed on the next slide.

The ArrayList Subset of Methods ArrayList methodWhat the Operation Does int size ( )returns the logical size of the list boolean add (E obj)appends the object obj to the end of the list and returns true if successful (the fact that it returns true may be helpful sometimes) void add (int index, E obj)inserts the object obj at position index where index fulfills the expression 0 ≤ index ≤ size. If index is out of bounds in the range of index size(), then Java throws an IndexOutOfBoundsException. Once obj is inserted, then the elements at position index and higher are moved to the right so that 1 is added to their indices and then the logical size is adjusted. Note: if there are 3 elements in the list at indices 0, 1, and 2, then obj can be added at index 3 without an out of bounds error E get (int index)returns the element at position index in the list E set (int index, E obj)replaces the element at position index with obj and returns the element formerly at the specified position E remove (int index)removes the element from position index in the list and then moves all elements at position index + 1 and higher to the left … subtracting 1 from their indices and then adjusting the logical size. The element formerly at the specified position is returned

Wrapper Classes The Integer and Double classes are called wrapper classes, because they are used to “wrap up” primitive int and double values as objects so they can be put in an ArrayList or other kind of data structure. We used the Integer and Double classes earlier this year when we used … Integer.parseInt() and Double.parseDouble() to get the values from JTextFields or InputDialog boxes. Now let’s look a little closer at the Integer and Double classes see how to wrap up an int or double as an object.

Wrapping & Unwrapping ints You don’t need to know the parseInt() method for the AP Exam, but you do need to know how to use the following methods of the Integer class: The constructor that has one parameter that is an int. If you want to wrap up an int, like 345, as an Integer object, then you would use the constructor to wrap it up: Integer intObj = new Integer(345); You have now wrapped up the int 345 and made it an Integer object and the variable intObj refers to that object! To unwrap the Integer object intObj and get the int value 345 out of it and store it in the int variable x, then you have to call the intValue() method … int x = intObj.intValue();

Wrapping & Adding Integers For the ArrayList … ArrayList nums = new ArrayList ( ); if we want to place the values 5, 10, and 15 in nums, in that order, we would wrap them up and add them as follows: Integer intObj1 = new Integer(5); nums.add(intObj1); // adds to the end of the list Integer intObj2 = new Integer(10); nums.add(intObj2); // adds to the end of the list You can also combine the lines by using … nums.add(new Integer(15)); // adds to the end of the list

Autoboxing Integers Prior to Java 1.5, with a raw ArrayList, you had to wrap up int values. However, with the advent of Java 1.5 autoboxing became available. Here is the same code with autoboxing: ArrayList nums = new ArrayList ( ); nums.add(5);// autoboxing 5 and adding it nums.add(10);// autoboxing 10 and adding it nums.add(15);// autoboxing 15 and adding it However, the College Board still wants you to know how to wrap up int values.

Unboxing Integers Prior to Java 1.5 with a raw ArrayList, you had to unwrap int values before using them. However, with the advent of Java 1.5 unboxing became available. Here is the code with unboxing: int x = nums.get(0); // get Integer at index 0 & unwrap using unboxing int y = nums.get(1); // get Integer at index 1 & unwrap using unboxing int z = nums.get(2); // get Integer at index 2 & unwrap using unboxing Here intValue() is called automatically by Java to unwrap the Integer object returned by get(i) so it can be stored in x, y, or z. You don’t have to call intValue() to unwrap because of unboxing! However, the College Board still wants you to know how to unwrap Integer objects.

Wrapping & Unwrapping doubles You don’t need to know the parseDouble() method for the AP Exam, but you do need to know how to use the following methods of the Double class: The constructor that has one parameter that is a double. If you want to wrap up a double, like 12.3, as a Double object, then you would use the constructor to wrap it up: Double floatObj = new Double(12.3); You have now wrapped up the double 12.3 and made it a Double object and the variable floatObj refers to that object! To unwrap the Double object floatObj and get the double value 12.3 out of it and store it in the double variable d, then you have to call the doubleValue() method … double d = floatObj.doubleValue();

Wrapping & Adding Doubles For the ArrayList … ArrayList floats = new ArrayList ( ); if we want to place the values 5.5, 6.6, and 7.7 in floats, in that order, we would wrap them up and add them as follows: Double floatObj1 = new Double (5.5); floats.add(floatObj1); // adds to the end of the list Double floatObj2 = new Double (6.6); floats.add(floatObj2 ); // adds to the end of the list You can also combine the lines by using … floats.add(new Double (7.7)); // adds to the end of the list

Autoboxing Doubles Prior to Java 1.5, with a raw ArrayList, you had to wrap up double values. However, with the advent of Java 1.5 autoboxing became available. Here is the same code with autoboxing: ArrayList floats = new ArrayList ( ); floats.add(5.5);// autoboxing 5.5 and adding it floats.add(6.6);// autoboxing 6.6 and adding it floats.add(7.7);// autoboxing 7.7 and adding it However, the College Board still wants you to know how to wrap up double values.

Unboxing Doubles Prior to Java 1.5 with a raw ArrayList, you had to unwrap double values before using them. However, with the advent of Java 1.5 unboxing became available. Here is the code with unboxing: double b = floats.get(0); // get Double at index 0 & unwrap using unboxing double c = floats.get(1); // get Double at index 1 & unwrap using unboxing double d = floats.get(2); // get Double at index 2 & unwrap using unboxing Here doubleValue() is called automatically by Java to unwrap the Double object returned by get(i) so it can be stored in b, c, or d. You don’t have to call doubleValue() to unwrap because of unboxing! However, the College Board still wants you to know how to unwrap Integer objects.

Adding Elements to an ArrayList - add(obj) The following code stores the first 100 multiples of 3 in nums in order: ArrayList nums = new ArrayList ( ); int value = 3; for (int i = 0; i < 100; i++) { nums.add(value); // adds at the end of the list value += 3; } Note: if nums was a standard array, we would use … nums [i] = value; in place of nums.add(value);

Getting Elements from an ArrayList - get(i) The following code prints the values stored in nums with 10 values per line with a field width of 5: for (int i = 0; i < nums.size(); i++) { if ( (i + 1) % 10 == 0 ) System.out.printf( “%5d%n”, nums.get(i) ); else System.out.printf( “%5d”, nums.get(i) ); } Note: if nums was a standard array, we would use … System.out.printf( “%5d”, nums[i] );

Getting Elements from an ArrayList - get(i) To obtain the first element in an ArrayList always use … nums.get(0); To obtain the last element in an ArrayList always use … nums.get(nums.size() - 1); Note that since there are num.size() elements in the ArrayList, then the index of the first element is 0 and the index of the last element is nums.size() - 1.

Removing Elements from a Position - remove(i) The following code removes and prints all of the multiples of 6 from nums in a field width of 5: int i = 0; while ( i < nums.size() ) { if ( nums.get(i) % 6 == 0 ) { int x = nums.remove(i) ; System.out.printf( “%5d”, x ); // don’t increment i because elements are shifted down } else // if not evenly divisible by 6 increment i i++; }

Removing Elements from a Position - remove(i) The following code removes and prints all of the multiples of 6 from nums in a field width of 5 using a for loop: for (int i = 0; i < nums.size() ; i++) { if ( nums.get(i) % 6 == 0 ) { int x = nums.remove(i) ; System.out.printf( “%5d”, x ); i--; // to cancel the effect of i++ in loop header }

Removing Elements from a Position - remove(i) To delete the first element in an ArrayList always use … nums.remove(0); To delete the last element in an ArrayList always use … nums. remove(nums.size() - 1); Again, since there are num.size() elements in the ArrayList, then the index of the first element is 0 and the index of the last element is nums.size() - 1.

Adding Elements at a Position - add(i, obj) The following code adds the integer 3 at the first of the list named nums using the add(i, obj) method, where the list initially contains 6, 9, 12. nums.add (0, 3); // add 3 at index 0. The list now contains: The following code adds the integer 15 at the end of the list no matter how many elements there are using the add(i, obj) method. nums.add (nums.size(), 15); // add 15 after the last element Since nums.size() is 4 before adding 15, then 15 is added at index 4. Obviously 3, 6, 9, &12 are in indices 0, 1, 2, & 3. The list now contains:

Replacing Elements at a Position - set(i, obj) Assume nums contains: The following code replaces the element at index 2 with the value 10 using the set(i, obj) method. It returns the replaced element and prints it out. int x = nums.set (2, 10); // replace 9 at index 2 with 10. System.out.println(“The replaced value was ” + x); The list now contains: Replacing the last value in the ArrayList … int x = nums.set (nums.size() - 1, 20); The list now contains: