ArrayLists (and the for-each loop) 4 11 34 15 2 1 0 214 124 2 3 4 5 1 0 1 2 3 4 5 6 7 8 9 10 11 12 13 ArrayList example = new ArrayList (); example.add(4);

Slides:



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

Programming with Alice Computing Institute for K-12 Teachers Summer 2011 Workshop.
CATHERINE AND ANNIE Python: Part 3. Intro to Loops Do you remember in Alice when you could use a loop to make a character perform an action multiple times?
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.
Week 2: Primitive Data Types 1.  Programming in Java  Everything goes inside a class  The main() method is the starting point for executing instructions.
CIT 590 Intro to Programming Java lecture 4. Agenda Types Collections – Arrays, ArrayLists, HashMaps Variable scoping Access modifiers – public, private,
CS 106 Introduction to Computer Science I 04 / 27 / 2007 Instructor: Michael Eckmann.
1 Dynamic Arrays  Why Dynamic Arrays?  A Dynamic Array Implementation  The Vector Class  Program Example  Array Versus Vector.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 10 *Arrays with more than one dimension *Java Collections API.
Strings as objects Strings are objects. Each String is an instance of the class String They can be constructed thus: String s = new String("Hi mom!");
Chapter 10 2D Arrays Collection Classes. Topics Arrays with more than one dimension Java Collections API ArrayList Map.
CS 106 Introduction to Computer Science I 04 / 30 / 2010 Instructor: Michael Eckmann.
ARRAYS AND ARRAYLISTS Chapter 7. Array  Sequence of values of the same type  Primitive types  Objects  Create an Array  double[] values = new double[10]
Arrays And ArrayLists - S. Kelly-Bootle
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.
Week 2 - Monday.  What did we talk about last time?  Software development  Lab 1.
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.
CS 106 Introduction to Computer Science I 04 / 25 / 2007 Instructor: Michael Eckmann.
ARRAYLIST.. Hazen High School. Vocabulary to Know ArrayList Generic Class ArrayList Operations ArrayList Methods ArrayList Searching For-Each Wrapper.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Week 6 - Wednesday.  What did we talk about last time?  Exam 1 post-mortem  Recursive running time.
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.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Arrays Chapter 8. What if we need to store test scores for all students in our class. We could store each test score as a unique variable: int score1.
Arrays BCIS 3680 Enterprise Programming. Overview 2  Array terminology  Creating arrays  Declaring and instantiating an array  Assigning value to.
Arrays An array is a data structure that consists of an ordered collection of similar items (where “similar items” means items of the same type.) An array.
CSE 143 Lecture 4 ArrayList Reading: 10.1 slides created by Marty Stepp
5 BASIC CONCEPTS OF ANY PROGRAMMING LANGUAGE Let’s get started …
Winter 2006CISC121 - Prof. McLeod1 Last Time Misc. useful classes in Java: –String –StringTokenizer –Math –System.
CS107 References and Arrays By Chris Pable Spring 2009.
Can we talk?. In Hello World we already saw how to do Standard Output. You simply use the command line System.out.println(“text”); There are different.
Copyright 2008 by Pearson Education Building Java Programs ArrayList Reading: 10.1.
CS 106 Introduction to Computer Science I 04 / 25 / 2008 Instructor: Michael Eckmann.
Textbook: Data Structures and the Java Collections Framework 3rd Edition by William Collins William Collins.
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.
ArrayList By Neil Butcher. What is the difference between an ArrayList and an Array? An ArrayList is in many ways similar to an array, but has a few subtle.
Java 1.5 The New Java Mike Orsega Central Carolina CC.
Introduction to Arrays (and the for-each loop) int[] example = new int[14]; example[0]
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.
Arrays…JavaCPython have fixed lengthyes*yesno are initialized to default values yesno? track their own lengthyesnoyes trying to access “out of bounds”
Lecture 121 CS110 Lecture 12 Tuesday, March 9, 2004 Announcements –hw5 due Thursday –Spring break next week Agenda –questions –ArrayList –TreeMap.
Copyright 2010 by Pearson Education Building Java Programs Chapter 10, 11 Lecture 22: 143 Preview optional reading: 10.1,
Chapter 6 Object-Oriented Design Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/20 The this Reference The this reference allows an object.
1 CSC 2053 New from AutoBoxing 3 Before J2SE 5.0, working with primitive types required the repetitive work of converting between the primitive.
Arrays and ArrayLists Topic 6. One Dimensional Arrays Homogeneous – all of the same type Contiguous – all elements are stored sequentially in memory For.
Arrays-. An array is a way to hold more than one value at a time. It's like a list of items.
COMP 110: Spring Announcements Program 5 Milestone 1 was due today Program 4 has been graded.
Chapter 2: Data and Expressions. Variable Declaration In Java when you declare a variable, you must also declare the type of information it will hold.
1 Arrays Chapter 8. Objectives You will be able to Use arrays in your Java programs to hold a large number of data items of the same type. Initialize.
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 11 GEORGE KOUTSOGIANNAKIS 1 Copyright: 2015 Illinois Institute of Technology_ George Koutsogiannakis.
19-Mar-16 Collections and ArrayLists.. 2 Collections Why use Collections. Collections and Object-Orientation. ArrayLists. Special Features. Creating ArrayLists.
Chapter 9 Introduction to Arrays Fundamentals of Java.
CS202 Java Object Oriented Programming Introduction to Collection Classes Chengyu Sun California State University, Los Angeles.
Week 2 - Wednesday CS 121.
(like an array on steroids)
CS 106A, Lecture 19 ArrayLists
Lecture 2: Implementing ArrayIntList reading:
Grouped Data Arrays, and Array Lists.
ArrayLists 22-Feb-19.
CS 200 Objects and ArrayList
Review: libraries and packages
CS 200 Objects and ArrayList
Review for Midterm 3.
Presentation transcript:

ArrayLists (and the for-each loop) ArrayList example = new ArrayList (); example.add(4); example.add(11); example.add(34); example.add(15);...

ArrayLists? Where I have heard of that before? After our last written test a few weeks ago, we looked at some notes over ArrayLists for bonus. I did that early so those people doing CodeWars would be familiar with them before the event. Now, everybody has to know them. But don't worry, they aren't that bad.

An ArrayList is a DYNAMIC ARRAY class in Java. It is a data structure with: –a dynamic (changing) size: as new elements are added to the ArrayList with the add() method, it makes more room to hold them. –methods such as size(), add(), remove(), get() and set() that can tell you additional information about the ArrayList and let you modify it –a set type. The that comes after the ArrayList is a generic type that should be replaced with whatever the list is actually holding when you declare or use it. For instance, if you have an ArrayList of Strings, you would declare it as ArrayList list; ArrayLists have to be imported from java.util.*;

ArrayLists ArrayLists can do the same things an Array can do, but it has some additional benefits that can make them a little easier to work with ArrayLists act more like a "normal" Java class that arrays do: they use methods, have a toString method that is correctly overriden, and don't use the [ ] syntax that arrays use.

Declaring ArrayList Declare an ArrayList just like you would any other data type, except now you have to also say what type of data the list will be holding using the <> symbols (don't actually put E, put whatever it is the ArrayList will hold): ArrayList myList; //list of Strings ArrayList list; //list of Integers ArrayList r; //list of JButtons

ArrayList constructors (instantiating ArrayLists) We will only be using the default constructor for ArrayList For instance, if I wanted to have a collection of strings, I would declare an ArrayList by saying: ArrayList list = new ArrayList (); Class Name Variable name Call to constructor method/instantiating ArrayList

ArrayLists and Primitive Data Types ArrayLists CANNOT hold primitive data types (like ints or doubles) directly. If you want to store a primitive type in an ArrayList, you must use the wrapper classes Integer, Double, Character, and so on. Once you declare the ArrayList (or whatever wrapper class you are using), you can then add normal ints to it. The ability of Java to convert from int to Integer, and double to Double is called Autoboxing. Meanwhile, the ability to automatically convert from Integer to int and Double to double is called Auto Unboxing.

Which will work? Which won't? ArrayList x = new ArrayList (); x.add(new Integer(3)); x.add(new Integer(2)); System.out.println(x); ArrayList x = new ArrayList (); x.add(3); x.add(2); System.out.println(x);

The size (length) of ArrayLists Once an ArrayList is created, its size is dynamic (changing) and accessed with the the size() METHOD (NOT property): arrayListVariable.size() For example, if you have myList. size() returns 5 Note that length is a METHOD, so it has parenthesis after it. This is DIFFERENT from a regular array (and thus kind of confusing) The last element of the array is found at the index size() myList

Assigning elements to ArrayLists After you declare and create an array, you can add values to it by saying: listName.add(value); For instance, if I have an ArrayList called buttons, then I can add the first button with: buttons.add(new JButton()); Loops are often used to initialize the values of a list. For example: for(int i=0; i<9; i++){ buttons.add(new JButton()); buttons.get(i).setSize(new Dimension(50,50)); panel.add(buttons.get(i)); }

IndexOutOfBounds If you enter a negative number as the index (like myList.get(-2)), or a number that is equal to or greater than the length of the array (like myList.get(5), assuming myList has a size of 5), you will get an IndexOutOfBoundsException. This is a very common error when dealing with ArrayLists.

Loops and Arrays Because they use numbered indexes from 1 to the length of the array, loops are very often used with arrays. Simply write a for loop that starts at 0 (the first element in the array), and goes while the control variable is <arrayName.length //assume ArrayList intArr is declare and instantiated elsewhere for(int i=0; i<intArr.size(); i++) { intArr.set(i, new Integer(i)); }

Examples Declare a String ArrayList named stringArr. Write a loop to add five strings with the value "CS" to stringArr Declare an ArrayList to hold doubles named list

What is an ArrayList? What is always the starting index of an ArrayList? Questions

ArrayList ArrayList has the following non-static methods: –public boolean add(E o) //add an object to the collection –public boolean add(int index, E o) //add o at index, //and scoot everything else in the //collection over one to make room –public E get(int index) //return the element at the given //index in the collection –public E set(int index, E o) //replace the element at index //with o –public int size() //returns how many elements are in the collection –public E remove(int index) //remove and return the element that used to //to be at index, and scoots everything else in the array //down one so there is no empty space in the collection

Looping through an ArrayList ArrayList stringList = new ArrayList (); stringList.add("dog"); stringList.add("cat"); stringList.add("cow"); System.out.println(stringList); while(stringList.size()>0) { System.out.println("Removing: "+stringList.remove(0)); } System.out.println(stringList);

Looping through an ArrayList JPanel panel = new JPanel(); ArrayList labelList = new ArrayList (); labelList.add(new JLabel(“Label A")); labelList.add(new JLabel(“Label B")); labelList.add(new JLabel(“Label C")); for(int i=0; i< labelList.size(); i++) //loop through list { JLabel tmp = labelList.get(i); //get out i th element tmp.setBackground(Color.RED); tmp.setForeground(Color.WHITE); panel.add(tmp); }

The "For-Each" loop The for-each loop we looked at with arrays can also be used for ArrayLists. ArrayList arr = new ArrayList (); list.add(4); list.add(6); list.add(20); int sum = 0; for(int temp : arr) sum+=temp; System.out.println(sum);

Other useful method for ArrayLists the static method Collections.sort() takes in an ArrayList and sorts it (similar to what Arrays.sort() from last time did to arrays) the static method Collections.reverse() takes in an ArrayList and reverses it (so after the method is run the first element will be the last and so on) the ArrayList class's non-static contains() element returns true if a value is found in the list, and false otherwise the ArrayList class's non-static toArray() method returns an array version of all the elements in the ArrayList

When to use ArrayLists instead of Arrays ArrayLists are good to use when we don't know how many total elements we will need to store. So that's what we'll do in the lab today. Some people will also end up using ArrayLists in our game projects later on…if we don't know beforehand how many bullets or enemies or whatever will be on the screen at once, we will have to store them in an ArrayList so it can grow or shrink as needed Virtually all CodeWars or CS UIL programs make you work with an unknown number of inputs, so most of the time you will store these inputs in an ArrayList as you read them, then deal with them after you finish reading everything in.

Classes to read in from a file (we've actually used them before, in November) Scanner: used for scanning in data from command line or text file File: a file (text, folder, or whatever)

Scanner Scanner can scan in data into your program in one of two ways (for now): from the user via the command line or from a text file, depending on which constructor you use. It has the following useful non-static methods (plus many other more you can find in the API): –nextInt() //returns an int –nextDouble() //returns a double –next() //returns a String (anything in quotes) –nextLine() //returns a String w/o a newline character –hasNext() //is there anything left to read in? –hasNextLine() //are there more lines left to read in? –close() //for use when you are done with the Scanner

From the command line Constructor: public Scanner(InputStream source) What is an InputStream? Well, System.out is an OutputStream object. System.in is the corresponding InputStream, that lets you read in data from the command line. Ex: Scanner scan = new Scanner(System.in); int x = scan.nextInt(); //read int from user double y = scan.nextDouble(); //read double in System.out.println(x+y);

From a File Constructor: public Scanner(File source) A File is another class...so of course we need to look that one up as well. The constructor for a File takes in a String giving the name and path of the file you want to use You may want to use JFileChooser's showOpenDialog method to ask the user to select a file, then give the selected file to a Scanner

the File class You can do a bunch of things with the File class (delete, verify it exists, get its file name, determine whether it is a file or a folder, get a list of files inside of it if it is a folder, etc). We won't do much with it now, though, other than use it to read in data with Scanner.

JFileChooser JFileChooser is a nice GUI for selecting a file that we can assign to a File variable, then read from using Scanner. Constructor: public JFileChooser() Ex: JFileChooser chooser = new JFileChooser(); chooser.showOpenDialog(null); //brings up dialog box File selectedFile = chooser.getSelectedFile(); Scanner scan = new Scanner(selectedFile); String firstWordInFile = scan.next();

Review of READING FROM A FILE (for today's lab)