The ArrayList Class and the enum Keyword

Slides:



Advertisements
Similar presentations
Recursion Chapter 14. Overview Base case and general case of recursion. A recursion is a method that calls itself. That simplifies the problem. The simpler.
Advertisements

Review Generics and the ArrayList Class
Two Dimensional Arrays and ArrayList
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;
Sequence of characters Generalized form Expresses Pattern of strings in a Generalized notation.
1 StringBuffer & StringTokenizer Classes Chapter 5 - Other String Classes.
1 Arrays An array is a special kind of object that is used to store a collection of data. The data stored in an array must all be of the same type, whether.
Purpose : To convert this string to a new character array. Return Type : char[ ] Parameters : none Declaration : public char[ ] toCharArray() Returns.
Java POWERED BY: ARVIND DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING RADHA GOVIND GROUP OF INSTITUTIONS,MEERUT.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 9 Strings.
SCJP 6.0 Lecturer Kuo-Yi Chen 151, 153, 154, 155, 156, 157
CS18000: Problem Solving and Object-Oriented Programming.
Chapter 6 The Collections API. Simple Container/ Iterator Simple Container Shape [] v = new Shape[10]; Simple Iterator For( int i=0 ; i< v.length ; i++)
Chapter 7 Strings F To process strings using the String class, the StringBuffer class, and the StringTokenizer class. F To use the String class to process.
1 Strings and Text I/O. 2 Motivations Often you encounter the problems that involve string processing and file input and output. Suppose you need to write.
Chapter 7 Strings F Processing strings using the String class, the StringBuffer class, and the StringTokenizer class. F Use the String class to process.
Java Programming Strings Chapter 7.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 9 Strings and Text I/O.
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.
©2004 Brooks/Cole Chapter 7 Strings and Characters.
Strings and Arrays The objectives of this chapter are:  To discuss the String class and some of its methods  To discuss the creation and use of Arrays.
1 Chapter 2 Introductory Programs. 2 Getting started To create and run a Java program –Create a text file with a.java extension for the source code. For.
Fundamental Programming Structures in Java: Strings.
Alice in Action with Java
Fundamental Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
 2003 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to Arrays Introduction to Computers and Programming in.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 7 User-Defined Methods.
Building Java Programs
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
Chapter 3 Introduction to Collections – Stacks Modified
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 22 Java Collections.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 22 Java Collections.
AP Comp Sci A Chapter 12 - Arrays. Ch 12 Goals: Goals: Declare and create arrays Declare and create arrays Access elements in arrays Access elements in.
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.
BUILDING JAVA PROGRAMS CHAPTER 7 Arrays. Exam #2: Chapters 1-6 Thursday Dec. 4th.
CSE 143 Lecture 4 ArrayList Reading: 10.1 slides created by Marty Stepp
Copyright 2008 by Pearson Education Building Java Programs Chapter 10 Lecture 10-1: ArrayList reading: 10.1.
Chapter 18 Java Collections Framework
Chapter 14 Generics and the ArrayList Class Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights.
10-Nov-15 Java Object Oriented Programming What is it?
Chapter overview This chapter focuses on Array declaration and use Bounds checking and capacity Arrays storing object references Variable length parameter.
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.
Chapter 7: Characters, Strings, and the StringBuilder.
Introduction to Generics
Copyright 2010 by Pearson Education Building Java Programs Chapter 10 Lecture 21: ArrayList reading: 10.1.
Chapter 5 Objects and Classes Inheritance. Solution Assignments 3 & 4 Review in class…..
Chapter 4 Generic Vector Class. Agenda A systemic problem with Vector of Object – Several approaches at a solution – Generic structures Converting classes.
Strings and Related Classes String and character processing Class java.lang.String Class java.lang.StringBuffer Class java.lang.Character Class java.util.StringTokenizer.
int [] scores = new int [10];
CS1020 Data Structures and Algorithms I Lecture Note #6 Vector and ArrayList.
Basic Syntax อ. ยืนยง กันทะเนตร คณะเทคโนโลยีสารสนเทศและการสื่อสาร มหาวิทยาลัยพะเยา Chapter 2.
Lecture 5:Interfaces and Abstract Classes Michael Hsu CSULA.
Chapter VII: Arrays.
Sixth Lecture ArrayList Abstract Class and Interface
Chapter 7 User-Defined Methods.
More About Objects and Methods
Chapter 7: Strings and Characters
Lecture 2: Implementing ArrayIntList reading:
Unit-2 Objects and Classes
Arrays and Collections
Grouped Data Arrays, and Array Lists.
int [] scores = new int [10];
Fundamental OOP Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
In this class, we will cover:
Presentation transcript:

The ArrayList Class and the enum Keyword Chapter 7

Overview Introduction to ArrayLists. These are similar to arrays, but we do not have to specify the array size. Immutable Classes (e.g., String, Integer, Double). The StringBuffer class (Similar to the String class, but the characters can be modified). The enum keyword. Used to define a new type that enumerates all possible values.

Introduction to ArrayList ArrayList<Employee> emps = new ArrayList<Employee>(); Creates an ArrayList of Employee objects. Note that the size of the ArrayList is not specified. ArrayList is a generic class. This means that it takes as input (in angle brackets) the name of another class. The above definition creates a list of Employee objects. We can insert/delete objects into/from the list. Of course, we need to use new to create an employee before we can add it to the list. Shortcut (as of Java 7): ArrayList<Employee> emps = new ArrayList<>();

An ArrayList of Primitive Type ArrayList<int> a = new ArrayList<int>(); doesn't work! We need to specify the name of a class in the angle brackets. Alternatively, this works! ArrayList<Integer> a = new ArrayList<Integer>(); Integer is called a wrapper class. There are similar classes: Double, Character, Boolean, etc. Note that all wrapper classes are immutable!

class Test{ public static void inc(Integer i){ i++; } public static void main(String[] args){ Integer i=3; inc(i); System.out.println(i);// 3 will be printed

import java.util.*; class Test{ public static void inc(MyInteger i){ i.setValue(i.getValue()+1); } public static void main(String[] args){ MyInteger i = new MyInteger(3); inc(i); System.out.println(i);// 4 will be printed

class MyInteger{ private int i; public MyInteger(int i){ this.i = i; } public int getValue(){ return i; public void setValue(int i){ public String toString(){ return i+"";

The StringBuffer Class It's a mutable version of the String class. The constructor can take as input a String object. Contains methods: (counting starts at 0) charAt(i) returns character at position i setChar(i, c) changes the character at position i deleteCharAt(i) deletes the character at position i; the rest of the characters are shifted automatically. insert(i,c) inserts character at position i; the rest of the characters are shifted automatically. append(s) appends a string to the StringBuffer StringBuffer s = new StringBuffer("dog"); s.append("cat"); System.out.println(s); //will print dogcat

Remove First Character public class Example{ public static void removeFirstCharacter(StringBuffer s){ for(int i = 1; i < s.length(); i++){ s.setCharAt(i-1, s.charAt(i)); } s.deleteCharAt(s.length()-1);//deletes last character public static void main(String[] args) { StringBuffer s = new StringBuffer("hello"); removeFirstCharacter(s); System.out.println(s); // of course, we can also use s.deleteCharAt(0);

The Interface of an ArrayList Different from arrays. No [] interface. One does not specify the size. Use size() to get the number of elements of the ArrayList (not the capacity). Use get(i) to get the element at position i, where counting starts at 0. However, get(i) cannot be used to modify the list.

Example Alternatively, we can use: public static Employee[] convert(ArrayList<Employee> emps){ Employee[] result = new Employee[emps.size()]; for(int i=0; i < emps.size(); i++){ result[i] = emps.get(i); } return result; Alternatively, we can use: Employee[] emps = (Employee[]) empArrayList.toArray(); Note that the result needs to be casted.

Inserting an Element Creating an ArrayList of a single element. ArrayList<Employee> emps = new ArrayList<Employee>(); emps.add(new Employee("John")); Note that the element will be inserted at the end of the ArrayList. Alternatively, consider the syntax: emps.add(0,new Employee("John")); Now, the element is inserted at position 0. All the elements in the list will be shifted one to the right. Consider: emps.add(5,new Employee("John")); If there are no at least 5 elements already in the list (positions 0-4), then an exception will be generated and the program will crash.

Deleting an Element a.remove(3);// removes the element at position 3, elements are shifted a.remove(o); // removes the first occurrence of the object o, elements are shifted. sometimes, it is difficult to distinguish between the two! import java.util.*; public class Test { public static void main(String[] args) { ArrayList<Integer> a = new ArrayList<Integer>(); for(int i = 0; i < 10; i++){ a.add(i+5); } a.remove(6); //element at position 6 or the number 6? System.out.println(a); Answer: Element at position 6!

Alternative Version Number 6 this time! import java.util.*; public class Test { public static void main(String[] args) { ArrayList<Integer> a = new ArrayList<Integer>(); for(int i = 0; i < 10; i++){ a.add(i+5); } a.remove(new Integer(6)); System.out.println(a); Number 6 this time!

Changing an Element a.set(3,new_value); //changes the element at position 3. Note that if an element at position 3 does not exist (i.e., at least 4 elements do not exist), then an exception is raised. Note that we must use the add method to add elements before we can use the set method to change an element. We cannot add a new element using the set method! ArrayList<Integer> a = new ArrayList<Integer>(); for(int i = 0; i < 10; i++){ a.add(i); } a.set(3,10); //changes the 4th element to 10

The Coin Game We have 10 coins that are randomly generated. Our score is the sum of the coins that are tails (i.e., the coins that we can see the value of). The user may flip all (or maybe some) coins, and get a new score. The purpose of the game is to get the biggest score possible. Our solution will use an ArrayList of coins. We will use a bottom-up design (i.e., start with the Coin class).

public class Coin { public static final double DEFAULT_BIAS = 0.5; private int value; private boolean face; private double bias; public Coin(){ this.bias = DEFAULT_BIAS; this.value = getRandomCoinValue(); flip(); } public Coin(int value){ this.value = value; public Coin(int value, double bias){ this.bias = bias;

public void flip(){ face = (Math.random()<bias) ? true : false; } public String toString(){ switch(value){ case 1: return "penny that is "+((face)?"heads":"tails"); case 5: return "nickel that is " +((face)?"heads":"tails"); case 10: return "dime that is " ((face)?"heads":"tails"); case 25: return "quarter that is " default: return "";

private int getRandomCoinValue(){ double randomNumber = Math.random(); if(randomNumber < 0.25){ return 1; } if(randomNumber < 0.5){ return 5; if(randomNumber < 0.75){ return 10; return 25; public int getValue(){ return value; public boolean isHeads(){ return face;

Notes getRandomCoinValue method is private (i.e., an auxiliary method). All constructors initialize all local variables. If a value is not specified, then a default (or random) value is used. The toString method returns the name and face of a coin. For example, dime that is heads. Problem with design: Nothing prevents us from making a coin that is 37 cents. toString method seems awkward. Can't we just save somewhere that dime is 10 cents? The enum keyword solves both problems.

Example enum Currency { PENNY(1), NICKEL(5), DIME(10), QUARTER(25); private int value; private Currency(int value) { this.value = value; } public int getValue(){ return value;

The enum keyword Stands for enumerate. Similar syntax to a class (can have a constructor). However, it starts by enumerating all possible values. Can associate a value with every constant. If we do that, then we need to define a variable of this type and a constructor that initializes the variable. The constructor must be private. It is never directly called. If no values are associated: enum Currency { PENNY, NICKEL, DIME, QUARTER; }

enum Keyword (cont'd) Currency value; // defines the variable value of type Currency enum therefore defines a new type. It is not a primitive type or a class. Not a class because we do not use new! However we can call methods on the variable (e.g., getValue) and therefore behaves similar to an object. We can use the syntax: value = Currency.PENNY; (similar to how a static variable of a class is referenced). A toString method is automatically created. It returns the name of the constant (e.g. PENNY). It is similar to a primitive type because a method cannot modify the value of a parameter of type enum. We CAN use == to compare variables of type enum. Similarly, we can use = for assignment.

values Method It is a static method. It returns an array of all the elements of the enum type. One can examine the elements of the array, but can not modify them. enum Car { Ford, Toyota, BMW; } public class Test { public static void main(String[] args) { int i = (int)(Math.random()*3); System.out.println(Car.values()[i]);

enum Face { HEADS(true), TAILS(false); private boolean value; private Face(boolean value) { this.value = value; } public boolean getValue(){ return value; public class Coin { public static final double DEFAULT_BIAS = 0.5; private Currency value; private Face face; private double bias; public Coin() { this.bias = DEFAULT_BIAS; this.value = getRandomCoinValue(); flip();

public Coin(Currency value) { this.value = value; this.bias = DEFAULT_BIAS; flip(); } public Coin(Currency value, double bias) { this.bias = bias; public void flip() { face = (bias < Math.random()) ? Face.HEADS : Face.TAILS; // true is heads

private Currency getRandomCoinValue(){ double randomNumber = Math.random(); if(randomNumber < 0.25){ return Currency.PENNY; } if(randomNumber < 0.5){ return Currency.NICKEL; if(randomNumber < 0.75){ return Currency.DIME; return Currency.QUARTER; public String toString() { return value+" that is "+face;//toString method explicitly } //called public int getValue(){ return value.getValue(); public boolean isHeads(){ return (face == Face.HEADS);

The Change Class We next present the Change class (i.e., an ArrayList of coins). It will allow us to flip all coins, or only some of the coins. It has an appropriate toString method that returns the value of all the coins that are tails. For coins that are heads, the value is not included. We will also add a computeSum method that computes the sum of all the coins that are tails.

public class Change { ArrayList<Coin> coins = new ArrayList<Coin>(); public Change(){} public Change(int count){ for(int i = 0; i < count; i++){ coins.add(new Coin()); } public Change(ArrayList<Currency> values) { for (Currency value : values) { coins.add(new Coin(value)); public void flipAllCoins() { for (Coin c : coins) { c.flip();

public void flipSomeCoins(ArrayList<Integer> indexes) { for (int i : indexes) { coins.get(i).flip(); } public int computeSum() { int sum = 0; for (Coin c : coins) { if (!c.isHeads()) { sum = sum + c.getValue(); return sum; public String toString() { String result = ""; result = result+c+" "; result = result + " Total: "+ computeSum(); return result;

The Coin Game (Main Class) We will create two versions of the main class of the coin game. In the first version, the user will be able to specify which coins to flip. In the second version, the user will only be allowed to flip all coins. Since we already created the Change class, the main method will be relatively short.

Flip Some Coins Version import java.util.*; public class CoinGame { public static final int NUMBER_FLIPS=2; public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); ArrayList<Currency> currency = new ArrayList<>(); System.out.println(change); for (int i = 0; i < NUMBER_FLIPS; i++) { System.out.print("Which coins do you want to flip:"); change.flipSomeCoins(convert(keyboard.nextLine())); }

static ArrayList<Integer> convert(String s) { StringTokenizer st = new StringTokenizer(s); ArrayList<Integer> result = new ArrayList<Integer>(); while (st.hasMoreTokens()) { result.add(Integer.parseInt(st.nextToken())-1); } return result; } // same as the method in the Yahtzee game

Flip All Coins Version public class CoinGame { public static final int NUMBER_FLIPS=2; public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); Change change = new Change(10); System.out.println(change); for (int i = 0; i < NUMBER_FLIPS; i++) { System.out.print("Flip all?: "); if(!keyboard.nextLine().equals("yes")){ break; } change.flipAllCoins();

Example Output Flip some coins version: Flip all coins version: HEADS HEADS HEADS HEADS QUARTER HEADS PENNY HEADS QUARTER HEADS Total: 51 Which coins do you want to flip: 1 2 3 HEADS NICKEL PENNY HEADS QUARTER HEADS PENNY HEADS QUARTER HEADS Total: 57 Which coins do you want to flip: 1 Flip all coins version: HEADS QUARTER QUARTER HEADS QUARTER NICKEL QUARTER PENNY DIME HEADS Total: 116 Flip all?: no

Summary The ArrayList class. Easier (and more powerful) then arrays. No [] interface. We need to use get, set, add, and delete methods. The enum keyword. We can use it to define our own type by enumerating values. Variables of this type behave like objects (methods can be called on them) and like primitive types (can be directly assigned values and we do not use the new keyword).