Download presentation
Presentation is loading. Please wait.
Published byRussell Burns Modified over 9 years ago
1
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); example.add(11); example.add(34); example.add(15);...
2
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.
3
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.*; 4 11 34 15 0 1 2 3
4
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.
5
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
6
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
7
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.
8
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);
9
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()-1 1 1 0 4 0 myList
10
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)); }
11
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.
12
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)); }
13
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
14
What is an ArrayList? What is always the starting index of an ArrayList? Questions
15
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
16
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);
17
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); }
18
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);
19
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
20
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.
21
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)
22
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
23
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);
24
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
25
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.
26
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();
27
Review of READING FROM A FILE (for today's lab)
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.