Lecture 20: Wrapper Classes and More Loops

Slides:



Advertisements
Similar presentations
Java Review Interface, Casting, Generics, Iterator.
Advertisements

Control Structures. Decision Making Structures The if and if…else are all selection control structures that introduce decision-making ability into a program.
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.
Copyright 2008 by Pearson Education 1 Building Java Programs Chapter 2 Lecture 2-2: The for Loop reading: 2.3 self-check: exercises: 2-14 videos:
Arrays, Loops weeks 4-6 (change from syllabus for week 6) Chapter 4.
CSE373 Optional Section Java Collections 11/12/2013 Luyi Lu.
Multiple Choice Solutions True/False a c b e d   T F.
Copyright 2009 by Pearson Education Building Java Programs Chapter 2 Lecture 2-2: The for Loop reading: 2.3 self-check: exercises: 2-14 videos: Ch.
P Object type and wrapper classes p Object methods p Generic classes p Interfaces and iterators Generic Programming Data Structures and Other Objects Using.
ARRAYLIST Collections of Data. ArrayLists Array lists can grow and shrink as needed ArrayList is a generic class (similar to C++ template) ArrayList has.
ArrayList, Multidimensional Arrays
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
CSE 143 Lecture 4 ArrayList Reading: 10.1 slides created by Marty Stepp
Chapter 18 Java Collections Framework
Java 5 Part 1 CSE301 University of Sunderland Harry Erwin, PhD.
Slides prepared by Rose Williams, Binghamton University Chapter 5 Defining Classes II.
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.
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.
Lists What to do?. Lists  A list is a linear arrangement of data elements.  Items are arranged in sequential (linear) order  Items are therefore ordered.
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.
Copyright 2008 by Pearson Education 1 Building Java Programs Chapter 2 Lecture 2-2: The for Loop reading: 2.3 self-check: exercises: 2-14 videos:
Collections Mrs. C. Furman April 21, Collection Classes ArrayList and LinkedList implements List HashSet implements Set TreeSet implements SortedSet.
The ArrayList Data Structure Standard Arrays at High Speed! More Safety, More Efficient, and Less Overhead!
Arrays and ArrayLists Topic 6. One Dimensional Arrays Homogeneous – all of the same type Contiguous – all elements are stored sequentially in memory For.
CSE 1201 Object Oriented Programming ArrayList 1.
Chapter 5 Defining Classes II Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
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 Standard Arrays at High Speed!
19-Mar-16 Collections and ArrayLists.. 2 Collections Why use Collections. Collections and Object-Orientation. ArrayLists. Special Features. Creating ArrayLists.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 6 GEORGE KOUTSOGIANNAKIS Copyright: 2016 Illinois Institute of Technology/George Koutsogiannakis 1.
Lecture 18: Nested Loops and Two-Dimensional Arrays
EKT472: Object Oriented Programming
CMSC 202 ArrayList Aug 9, 2007.
CompSci 230 S Programming Techniques
Fundamentals of Java: AP Computer Science Essentials, 4th Edition
Lecture 13: More Arrays Building Java Programs: A Back to Basics Approach by Stuart Reges and Marty Stepp Copyright (c) Pearson All rights reserved.
Lecture 17: Polymorphism (Part II)
Array List Pepper.
Java Array Lists 2/13/2017.
TCSS 143, Autumn 2004 Lecture Notes
Can store many of the same kind of data together
Generics 27-Nov-18.
CS Week 9 Jim Williams, PhD.
CS 200 Objects and ArrayList
CMSC 202 ArrayList Aug 9, 2007.
Java Classes and Objects 3rd Lecture
Can store many of the same kind of data together
Dynamic Data Structures and Generics
Topics Covered: Arrays, 1-D & 2-D Passing & Returning Arrays
CMSC 202 ArrayList Aug 9, 2007.
Grouped Data Arrays, and Array Lists.
Lecture 13: Two-Dimensional Arrays
Type Safety, Generics, Lambdas, Class Object
int [] scores = new int [10];
Java Array Lists 2/13/2017.
Lecture 12: 2D Arrays AP Computer Science Principles
Lecture 13: ArrayLists AP Computer Science Principles
ArrayLists 22-Feb-19.
Building Java Programs
Can store many of the same kind of data together
Lecture 16: Arraylist Building Java Programs: A Back to Basics Approach by Stuart Reges and Marty Stepp Copyright (c) Pearson All rights reserved.
Generics, Lambdas, Reflections
Lecture 18: Polymorphism (Part II)
Suggested self-checks: Section 7.11 #1-11
Review: libraries and packages
Building Java Programs
Generics 2-May-19.
Presentation transcript:

Lecture 20: Wrapper Classes and More Loops Building Java Programs: A Back to Basics Approach by Stuart Reges and Marty Stepp Copyright (c) Pearson 2013. All rights reserved.

Wrapper Classes A wrapper class takes an existing value of primitive type and “wraps” or “boxes” it in an object, and provides a new set of methods for that type. It can be used in Java container classes that requires the item to be objects. (Arraylist)

Wrapper Classes The wrapper class allows The construction of an object from a single value(wrapping or boxing the primitive in a wrapper object. The retrieval of a primitive value(unwrapping or unboxing from a wrapper object.)

Wrapper Classes Java allows wrapper object for each of its primitive types. The two that will be on the AP Exam are Integer and Double classes. Primitive Type Wrapper Type int Integer double Double char Character boolean Boolean

Integer Class The Integer class wraps a value of type int in an object. This class has only one instance variable whose type is int. Here are its methods: Integer(int value): Constructs an Integer object from an int(boxing). int compareTo(Integer other): Returns 0 if the value of this Integer is equal to the value of the other, a negative integer if it is less than the value of other and a positive integer if it is greater than the value of other.

Integer Class int intValue(): Returns the value of this Integer as an int(unboxing). boolean equals(Object obj): Returns true if and only if this Integer has the same int value as obj. This method overrides the equals method from class Object. This method throws a ClassCastException if obj is not an Integer. String toString(): Returns a String representing the value of this Integer.

Double Class The Double class wraps a value of type double in an object. This class has only one instance variable whose type is double. Here are its methods: Double(double value): Constructs an Double object from an double(boxing). int compareTo(Double other): Returns 0 if the value of this Double is equal to the value of the other, a negative integer if it is less than the value of other and a positive integer if it is greater than the value of other.

Double Class double doubleValue(): Returns the value of this Double as a double(unboxing). boolean equals(Object obj): Returns true if and only if this Double has the same double value as obj. This method overrides the equals method from class Object. This method throws a ClassCastException if obj is not a Double. String toString(): Returns a String representing the value of this Double.

Examples Integer intObj=new Integer(6);//boxes 6 in Integer object int j=intObj.intValue(); //unboxes 6 from Integer object System.out.println(“Integer value is ”+intObj); //calls toString() for intObj //output is Integer value is 6

Examples Object a=new Integer(5); int j=4; Integer b=new Integer(5); int k=b.intValue(); if(a==b) //false if(a.equals(b)) //true, polymorphism, which equals version? if(a.intValue()==b.intValue()) //error, Object has no intValue if(k==b.intValue()) //ok,comparing primitives if(k.equals(j)) //error, j and k not objects if(b.compareTo(a)<0) //error, need to cast if(b.compareTo((Integer)a)<0)//ok

Examples Double dObj=new Double(2.5);//boxes 2.5 in Double object double d=dObj.doubleValue(); //unboxes 2.5 from Double object Object object=new Double(7.3); Object intObj=new Integer(4); if(dObj.compareTo((Double)object>0) //remember to cast if(dObj.compareTo(intObj)>0) //class cast exception //can’t compare Integer //with Double

Auto-Boxing and Unboxing Auto-boxing is the automatic wrapping of primitive types in their wrapper classes. To retrieve the value of an Integer(or Double), the intValue() (or doubleValue()) method must be invoked(unwrapped). Auto- unboxing is the automatic conversion of a wrapper class to its corresponding primitive type. This means you don’t need to explicitly call the intValue() or doubleValue().

Auto-Boxing and Unboxing Auto-boxing and unboxing reduce code clutter but are still performed behind the scenes and can decrease run time efficiency. When possible, use arrays of integers rather than arraylist of Integers.

Examples Integer a=new Integer(5); int x=a; //auto unboxing Integer b=7; //auto-boxing int y=a+x; //auto-unboxing NOTE: Autoboxing and unboxing will not be test on the AP Exam. However, it is ok to use these features of Java in writing your answers to the free response section.

For-Each Loop

For-Each Loop The for-each or enhanced for loop is used to iterate over an array or arraylist. The general form of the loop is for(SomeType element: collection) { ... } How would we print a multiplication table? try printing each of the following inside the inner loop: System.out.print(i + " "); System.out.print(j + " "); System.out.print((i * j) + " ");

For-Each Loop int[] arr={1,4,3,5}; for(int i=0;i<arr.length;i++) System.out.println(arr[i]); //for each for(int element : arr) System.out.println(element); The for-each loop cannot be used for replacing or removing elements as you traverse. The loop hides the index variable that is used with arrays. How would we print a multiplication table? try printing each of the following inside the inner loop: System.out.print(i + " "); System.out.print(j + " "); System.out.print((i * j) + " ");

For-Each Loop What is the output of the following code? int[] arr={1,4,3,5}; for(int element : arr) element=7; System.out.println(Arrays.toString(arr)); Output: [1,4,3,5] The for-each loop cannot be used for replacing or removing elements as you traverse! In this case, element is a temporary variable and does not refer to any element in the array. How would we print a multiplication table? try printing each of the following inside the inner loop: System.out.print(i + " "); System.out.print(j + " "); System.out.print((i * j) + " ");

For-Each Loop For each is the same for both an array and an arraylist. String[] array=new String[2]; array[0]=“hello”; array[1]=“goodbye”; ArrayList<String> list=new ArrayList<String>(); list.add(“hi”); list.add(“hello”); for(String s: array) System.out.println(s); for(String s: list) How would we print a multiplication table? try printing each of the following inside the inner loop: System.out.print(i + " "); System.out.print(j + " "); System.out.print((i * j) + " ");

For Each The for-each construction is the same for objects. Point[] pts={new Point(),new Point(1,2),new Point(-1,4)}; for(Point element : pts) System.out.println(element+” “); //toString() How would we print a multiplication table? try printing each of the following inside the inner loop: System.out.print(i + " "); System.out.print(j + " "); System.out.print((i * j) + " ");

For Each The for-each construction can be used with 2D arrays. Use nested for each loops. int[][] matrix={{1,5,6}{-3,-1,7},{0,1,-1}} int sum=0; for(int[] row: matrix){ for(int element: row) sum+=element;} for(int i=0;i<matrix.length;i++) for(int j=0;j<matrix[0].length;j++) sum+=matrix[i][j]; How would we print a multiplication table? try printing each of the following inside the inner loop: System.out.print(i + " "); System.out.print(j + " "); System.out.print((i * j) + " ");

Lab 3 Write the Test class with the instance variables and methods listed below. If necessary, modify the Question class written previously. public class Test{ private ArrayList<Question> questions; private int[] points; public Test(ArrayList<Question> questions) {…} public int totalPoints(){…} public void printTest() {…} public void printAnswers() {…} public void setPoints(int mcPoints, int shortPoints) {…} public boolean addChoice(int questionNumber, String choice) {…} public void scrambleTest() {…} }

Lab 3 A Test consists of an arraylist of questions and an array of point value for each question. public Test(ArrayList<Question> questions) The Test class has one constructor to initialize the arraylist questions. This constructor must call setPoints(int mcPoints, int shortPoints) to initialize the points array. Each multiple choice is worth 5 points and each short answer 10 points. public int totalPoints() This method returns the total number of points for the test. public void printTest() This method prints the entire test with proper numbering of the questions.

Lab 3 public void printAnswers() This method prints a numbered list of answers to each question on the test. It should also prints the point value for each question. For example, (5 points) B: George Washington. (10 points) Teddy Roosevelt. etc.. public void setPoints(int mcPoints, int shortPoints) This method initializes the points array. Each multiple choice question is worth mcPoints and each short answer question is worth shortPoints. public boolean addChoice(int questionNumber, String choice) This method adds a choice to the question given by questionNumber. Returns true if added properly and false otherwise.

Lab 3 public void scrambleTest(); This method scrambles the test questions. You must create a new temporary arraylist of questions. The method must pick a random question from the instance variable arraylist questions, remove it and add it to the temporary arraylist. You must use Math.random(). In addition, the method updates the arraylist questions and the points array.