Why not just use Arrays? Java ArrayLists.

Slides:



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

ArrayLists The lazy mans array. Whats the matter here? int[] list = new int[10]; list[0] = 5; list[2] = hey; list[3] = 15; list[4] = 23;
© The McGraw-Hill Companies, 2006 Chapter 17 The Java Collections Framework.
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.
CSC 142 J(part 1) 1 CSC 142 The ArrayList class [Reading: chapter 10]
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.
Collecting Things Together - Lists 1. We’ve seen that Python can store things in memory and retrieve, using names. Sometime we want to store a bunch of.
The Java Collections Framework By the end of this lecture you should be able to: use the ArrayList class to store a list of objects; use the HashSet class.
Built-in Data Structures in Python An Introduction.
CompSci Arrays  Aggregate data type  Deal with items of same type  Lists of words  Numbers  Analogies  Mailboxes in post office  CD racks.
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.
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.
GROUPING OBJECTS CITS1001. Lecture outline The ArrayList collection Process all items: the for-each loop 2.
Chapter 5 Array-Based Structures © 2006 Pearson Education Inc., Upper Saddle River, NJ. All rights reserved.
CSE 1201 Object Oriented Programming ArrayList 1.
COMP More About Arrays Yi Hong June 05, 2015.
The ArrayList Data Structure Standard Arrays at High Speed!
Coming up ArrayList ArrayList vs Array – Declaration – Insertion – Access – Removal Wrapper classes Iterator object.
CMSC 202 ArrayList Aug 9, 2007.
Using the Java Collection Libraries COMP 103 # T2
CSc 110, Autumn 2016 Lecture 26: Sets and Dictionaries
Comp1004: Loops and Arrays II
(like an array on steroids)
3. Array-Lists.
Fundamentals of Java: AP Computer Science Essentials, 4th Edition
Foundations of Programming: Arrays
JAVA COLLECTIONS LIBRARY
Intro to Collections.
CSc 110, Spring 2018 Lecture 32: Sets and Dictionaries
Welcome to CSE 143!.
Array List Pepper.
Building Java Programs
Java Array Lists 2/13/2017.
CS 106A, Lecture 19 ArrayLists
Lecture 2: Implementing ArrayIntList reading:
ArrayLists.
File Handling Programming Guides.
ArrayLists.
Generics 27-Nov-18.
CS Week 9 Jim Williams, PhD.
CS 200 Objects and ArrayList
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
Building Java Programs
CMSC 202 ArrayList Aug 9, 2007.
ArrayLists.
Welcome to CSE 143!.
Object Oriented Programming in java
CMSC 202 ArrayList Aug 9, 2007.
Grouped Data Arrays, and Array Lists.
Java Array Lists 2/13/2017.
Lecture 13: ArrayLists AP Computer Science Principles
ArrayLists 22-Feb-19.
1D Arrays and Lots of Brackets
CSE 143 Lecture 3 Implementing ArrayIntList reading:
ArrayLists 27-Apr-19.
slides created by Alyssa Harding
Creating and Modifying Text part 3
Review: libraries and packages
Generics, Stack, Queue Based on slides by Alyssa Harding
Generics 2-May-19.
List Interface ArrayList class implements the List Interface
Arrays and ArrayLists.
Arrays.
Java Coding 6 David Davenport Computer Eng. Dept.,
Introduction to Computer Science
Presentation transcript:

Why not just use Arrays? Java ArrayLists

… if only an array could … shrink when you remove something. Tell you if it contains what you’re looking for instead of looping through to check each element. Grow when you need more room... That’s an ArrayList, not an array!

ArrayList is a class in the core Java library That’s the key to surviving in Java... Knowing what’s available already created ready to use It’s all in the API! # 1

What can you do with an ArrayList? Add new objects to the list Remove old objects from the list Ask the list if it contains a certain object Ask if the list is empty Find the index of a certain object Get the size of the list Get an object from a certain position in the list. A powerful collection of methods!

How do you do it? Make a list Put something in it Here’s the crate, it’s small because it’s empty Make a list ArrayList crate = new ArrayList(); Put something in it Egg chickie = new Egg(); crate.add(chickie); Put something else in it Egg babyRobin = new Egg(); crate.add(babyRobin); It grows to hold the Egg It grows to hold another

But, an ArrayList should have a type Make a list ArrayList<Egg> crate = new ArrayList<Egg>(); Put things in it Egg chickie = new Egg(); crate.add(chickie); Egg babyRobin = new Egg(); crate.add(babyRobin); Here’s the crate, it’s small because it’s empty. But it’s designed to hold eggs It holds the Egg It grows to hold another

Find out how many things are in the crate int howBig = crate.size(); Find out if it contains the chickie boolean isHere = crate.contains(chickie) Find out where the chickie is in the crate int position = crate.indexOf(chickie) Is the crate empty? boolean empty = crate.isEmpty(); Take something out crate.remove(chickie); 2 true =0, like an array, you start counting at zero. false Only babyRobin is left # 2

Important ArrayList points An array needs to know its size and type when it’s created. Not an ArrayList It grows and shrinks as needed There are advantages, however, to declaring a type for an ArrayList other than the default of Object

Point 2 To put an object in an array, you must assign it to a specific location. Not an ArrayList Each time you add something, you just say “add” and the ArrayList finds a place for it. (Though you can add to a specific location)

Point 3 Arrays are homogeneous. All objects in an array must be the same type. Not an ArrayList, it’s heterogeneous IF you make an ArrayList without a specific type. It can hold any kind of object But... It can NOT hold simple variables like int and boolean. (they will be auto-wrapped into objects)

Typed ArrayLists HIGHLY RECOMMENDED to declare an ArrayList to have a type ArrayList<Integer> nums = new ArrayList<Integer>(); ArrayList<Book> library = new ArrayList<Book>(); ArrayList<Car> traffic= new ArrayList<Car>(); Choose a name These MUST match! # 3

How do you do it? Make a list Put something in it ArrayList<String> words= new ArrayList<String>(); Put something in it String w = “supercalifragilisticexpealidocious”; words.add(w);

In Summary Use an ArrayList!!!! Need a bunch of objects, but there’s no way to know how many? Doesn’t really matter what order they’re in? Want to be able to pull something out without having to do a search for it? Want it to shrink as things are removed? Use an ArrayList!!!! fin

True, Java autowraps the ints into Integers. Question Given: ArrayList<Integer> vals= new ArrayList<Integer>(); What are the contents after: vals.add(3); vals.get(1); vals.add(5); vals.set(0,8); vals.remove(0); Wait! I thought you said you can’t put primitive objects in an ArrayList! True, Java autowraps the ints into Integers. # 4

So what methods do I need to know? list.add(e); Adds e to end of list list.add(i, e); Inserts e to location i list.set (i, e); Resets a value at index i list.get(i); Returns value at i list.remove(i); Removes element at I list.size(); Returns size list.contains(e); Is it in there? Returns true/false list.clear(); Empties entire list

Trickier question: Given: ArrayList<String> a = new ArrayList<String>(); What is in the list at the end of this code? a.add(“a”); a.add(0,”b”); a.set(1,”c”); a.add(1,”d”); a.add(“e”); a.remove(1); bce # 5

Some ArrayList method details ArrayList<String> stringList = new ArrayList<String>();  //ArrayList to Store only String objects Putting an Item into ArrayList Second line will result in compilation error because this Java ArrayList will only allow String elements. stringList.add("Item"); //no error because we are storing String stringList.add(new Integer(2)); //compilation error Checking size of ArrayList Size of an ArrayList in Java is total number of elements currently stored in ArrayList. int size = stringList.size(); # 6

Some ArrayList method details ArrayList<String> stringList = new ArrayList<String>();  //ArrayList to Store only String objects stringList.add(“thing”); stringList.add(”item”); Checking Index of an Item in Java Arraylist You can use indexOf() method of ArrayList in Java to find out index of a particular object. int index = stringList.indexOf(”item"); //location of item String in List Retrieving Item from arrayList in a for-each loop traverse an ArrayList and perform some operations on each retrieved item. for(String item: stringList){ System.out.println(item.charAt(0)); } # 7

More methods # 8 Checking ArrayList for an Item Sometimes we need to check whether an element exists in ArrayList in Java or not for this purpose we can use contains () method of Java. contains() method takes type of object defined in ArrayList creation and returns true if this list contains the specified element Checking if ArrayList is Empty We can use isEmpty() method of Java ArrayList to check whether ArrayList is empty. isEmpty() method returns true if this ArrayList contains no elements. You can also use size() method of List to check if List is empty boolean result = stringList.isEmpty(); //isEmpty() will return true if List is empty if(stringList.size() == 0){    System.out.println("ArrayList is empty"); } # 8

Removing an Item from ArrayList There are two ways to remove any elements from ArrayList in Java. Remove an element based on its index or Remove by providing the object itself. remove (int index) and remove (Object o) method is used to remove any element from ArrayList in Java. Since ArrayList allows duplicates its worth noting that remove (Object o) removes the first occurrence of the specified element from this list, if it is present. In below code first call will remove first element from ArrayList while second call will remove first occurrence of item from ArrayList in Java. stringList.remove(0);   stringList.remove(item); # 9

replace Replacing an element at a particular index You can use set (int index, E element) method of Java ArrayList to replace any element at a particular index. Below code will replace first element of stringList from to "Item2". stringList.set(0,"Item2"); # 10

END