AP CS Unit 7: Interfaces. Programs

Similar documents
AP CS Unit 7: Interfaces Exercises Assume all code compiles unless otherwise suggested.

AP CS Unit 7: Interfaces Exercises 1. Select the TRUE statement(s).

Adam Blank Lecture 5 Winter 2019 CS 2. Introduction to Programming Methods

CS1083 Week 2: Arrays, ArrayList

Adam Blank Lecture 5 Winter 2015 CSE 143. Computer Programming II

Algorithmic Thinking and Structured Programming (in Greenfoot) Teachers: Renske Smetsers-Weeda Sjaak Smetsers Ana Tanase

Advanced Topics in Java and on Security in Systems Effective Generics. Eirik Eltvik 26 th of February 2007

Unit 4: Classes and Objects Notes

Rules and syntax for inheritance. The boring stuff

Array Based Lists. Collections

Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

3. Convert 2E from hexadecimal to decimal. 4. Convert from binary to hexadecimal

Abstract classes are used to define a class that will be used only to build new classes. No objects will ever be instantiated from an abstract class.

Binghamton University. CS-140 Fall Problem Solving. Creating a class from scratch

Some examples and/or figures were borrowed (with permission) from slides prepared by Prof. H. Roumani. The Collection Framework

AP Computer Science Unit 1. Programs

This exam is open book. Each question is worth 3 points.

CS 455 Midterm 2 Spring 2018 [Bono] Apr. 3, 2018

Back public class HelloWorld { public static void main ( String arg[] ) { Front Basic Setup. Java Quick Sheet. ~ 35 Flashcards. 1 AP CS - Rodriguez

1) Consider the following code segment, applied to list, an ArrayList of Integer values.

Lesson 26: ArrayList (W08D1)

public static boolean isoutside(int min, int max, int value)

CS 200 Objects and ArrayList Jim Williams, PhD

CS 61B Discussion 5: Inheritance II Fall 2014

1. ArrayList and Iterator in Java

class objects instances Fields Constructors Methods static

Comparing Objects 3/14/16

Advanced Java Concepts Unit 2: Linked Lists.

CS108, Stanford Handout #8. Java Generics

Generics. Computer Science and Engineering College of Engineering The Ohio State University. Lecture 10

Csci 102: Sample Exam

Set<Integer> s = new TreeSet<Integer>(); s.add( 7 ); s.add( 7 ); System.out.println( s.size() );

APCS Semester #1 Final Exam Practice Problems

AP Computer Science Midterm Review Part 1

Practice Midterm 1. Problem Points Score TOTAL 50

Getting started with Java

Practice Midterm 1 Answer Key

C Sc 227 Practice Final Summer 13 Name 200 pts

Unit 10: Sorting/Searching/Recursion

AP Computer Science A Summer Assignment 2017

Comparing Objects 3/28/16

Lab Activity Plan. John Dalbey CPE /30/2013

Parametric polymorphism and Generics

Introduction to Computer Science Unit 2. Exercises

Intro to Computer Science II

CS Week 13. Jim Williams, PhD

Csci 102: Sample Exam

CS 101 Fall 2006 Midterm 3 Name: ID:

CMPSCI 187: Programming With Data Structures. Lecture #11: Implementing Stacks With Arrays David Mix Barrington 28 September 2012

Advanced Java Concepts Unit 3: Stacks and Queues

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

Unit 10: Sorting/Searching/Recursion

JAVA V Source files Java, winter semester

Program Fundamentals

CSC 172 Data Structures and Algorithms. Lecture 3 Spring 2018 TuTh 3:25 pm 4:40 pm

Homework 2: Imperative Due: 5:00 PM, Feb 15, 2019

Introduction to Generics in Java 5

CMP 326 Midterm Fall 2015

CITS1001 week 4 Grouping objects

09/02/2013 TYPE CHECKING AND CASTING. Lecture 5 CS2110 Spring 2013

CS 113 PRACTICE FINAL

I. True/False: (2 points each) On your bubble form fill out a for true and b for false.

Chair of Software Engineering. Java and C# in Depth. Prof. Dr. Bertrand Meyer. Exercise Session 7. Nadia Polikarpova

C Sc 227 Practice Final Summer 12 Name 200pt

AP CS Unit 6: Inheritance Notes

1. Is it currently raining in Tucson (4pts) a) Yes b) No? c) Don't know d) Couldn't know (not in Tucson)

Binghamton University. CS-140 Fall Interfaces

CS163/164 Final Exam Study Session

CS 307 Midterm 2 Spring 2008

Midterm Exam 2 CS 455, Spring 2014

Java Programming Fundamentals - Day Instructor: Jason Yoon Website:

QUIZ 2 Introduction to Computer Science (COMP 250) Mon. March 2, 2009 Professor Michael Langer

Software Engineering. Prof. Agostino Poggi

JAVA V Assertions Java, winter semester

AP CS Unit 7: Arrays Exercises

Today. Reading. Homework. Lecture Notes CPSC 224 (Spring 2012) hashcode() method. Collections class. Ch 9: hw 7 out (due in a week)

The newest, most different stuff is Java variable declaration, array syntax, class instance syntax. Expect those to be emphasized.

The class Object. Lecture CS1122 Summer 2008

Lesson 12: OOP #2, Accessor Methods (W03D4)

EECS2030 Week 7 worksheet Tue Feb 28, 2017

CSC 1051 Algorithms and Data Structures I. Final Examination May 2, Name:

CS2141 Software Development using C/C++ C++ Basics

CSE 331 Software Design and Implementation. Lecture 14 Generics 2

AP Computer Science Unit 1. Writing Programs Using BlueJ

CSE 1223: Introduction to Computer Programming in Java Chapter 6 ArrayLists

CSE 331 Software Design and Implementation. Lecture 14 Generics 2

CIS133J. Working with Numbers in Java

Fall CS 101: Test 2 Name UVA ID. Grading. Page 1 / 4. Page3 / 20. Page 4 / 13. Page 5 / 10. Page 6 / 26. Page 7 / 17.

Timing ListOperations

1.00 Introduction to Computers and Engineering Problem Solving. Quiz 1 March 7, 2003

Question 1. [5 points] What output is printed by the following program (which begins on the left and continues on the right)?

Topic 3 Encapsulation - Implementing Classes

1- Differentiate between extends and implements keywords in java? 2- What is wrong with this code:

COMP200 GENERICS. OOP using Java, from slides by Shayan Javed

CS-140 Fall 2018 Test 2 Version A Nov. 12, Name:

CS 251 Intermediate Programming Inheritance

CSE 142 Wi03 Midterm 2 Sample Solution All Versions Page 1 of 6

Points off Total off Net Score. CS 314 Final Exam Spring 2016

CS Week 14. Jim Williams, PhD

Transcription:

AP CS Unit 7: Interfaces. Programs You cannot use the less than (<) and greater than (>) operators with objects; it won t compile because it doesn t always make sense to say that one object is less than or greater than another. If you need to compare objects, Java provides the following interface: public interface Comparable{ public int compareto( Object x ); The compareto method returns a negative value if this object is less than the parameter; zero if they are equal, and a positive value if this object is greater than the parameter. The String and Integer classes both implement this interface. Program 1a. Complete the up method so that rearranges the elements in the array in increasing order. Assume the length of the array is exactly 2. You may not use Arrays.sort. Do not cast anything. Note. You will probably get a warning about an unchecked call to compareto( T ). Ignore it for now. public class Runner1{ Integer [] a1 = { 8, 4 ; up( a1 ); for ( int n : a1 ) System.out.println( n ); String [] a2 = { "rock", "paper" ; up( a2 ); for ( String s : a2 ) System.out.println( s ); String [] a3 = { "ant", "boat" ; up( a3 ); for ( String s : a3 ) System.out.println( s ); public static void up( Comparable[] c ){ complete this method 4 8 paper rock ant boat Program 1b. Copy these and run the main method. They compile but crash. Why? public class Runner2{ public static void main(string [] args){ Bat [] b1 = new Bat[ 2 ]; b1[0] = new Bat( 34 ); b1[1] = new Bat( 16 ); Arrays.sort( b1 ); for ( Bat b : b1 ) System.out.println( b ); public class Bat{ private int n; public Bat( int n ){ this.n = n; public String tostring(){ return "bat " + n; page 1

Program 2. Complete the max method so that it returns the largest value in the array. And don t even think of using Arrays.sort. public class Runner3{ String [] a1 = { "hat", "what", "why", "apple" ; Comparable c = max( a1 ); System.out.println( c ); // why Integer [] a2 = { 56, 22, 109, 5, 8, 13 ; c = max( a2 ); System.out.println( c ); // 109 public static Comparable max( Comparable[] c ){ write the code Program 3. This program consists of 5 files. 1) Create a Product interface that has two methods: public double getprice() public void setprice( double x ) 2) Create a Fruit class that implements Product. - There are two instance variables: private double cost; private String name; - The constructor has two parameters to initialize the instance variables. - Override the equals method. If the prices and names are the same then return true, otherwise return false. - Override the tostring method so it returns the name and cost. - Remember that you are implementing the Product interface. 3) Create a Book class that implements Product - There are three instance variables: private double cost; private String title; private int pages; // # pages in book - The constructor has three parameters to initialize the instance variables. - Override the equals method. If the titles are the same then return true, otherwise return false. The cost and number of pages do not matter. - Override the tostring method so that it shows the title, cost, and # of pages. Put quotes around the title. - Write an accessor method that returns the number of pages. - And I m not going to remind you about those other two methods you must write. page 2

4) Complete the Grocer class public class Grocer{ private Product [] inventory; // contains all the products the grocer has public Grocer( int size ){ inventory = new Product[ size ]; public void add( Product p ){ Add p to the first null element found in inventory. If there are no null elements, nothing happens. No casting needed. public void remove( Product p ){ Search for the first element that equals p and set that element to null. No casting needed. public void increaseprices( double p ){ Increase the price of all products by p percent. For example, if p is 0.2 then prices increase by 20%. Beware of elements that contain null values. No casting needed. public int totalpages(){ Returns the number of pages in all the books in the inventory. public String tostring() { Return a string that contains the result of calling each non-null element s tostring method. Put a new line character between elements. No casting needed. 5) Test your code with this class. The output is to the right. public class RunStore{ Grocer g = new Grocer( 5 ); g.add( new Book( "Hey", 2, 25 ) ); g.add( new Book( "There", 2.5, 100 ) ); System.out.println( g.totalpages() + " total pages\n" ); g.increaseprices( 0.1 ); g.remove( new Book( "Hey", 399, 1 ) ); g.remove( new Fruit( "Lime", 0.5 ) ); "Hey", 25 pages, $2.0 "There", 100 pages, $2.5 125 total pages "Hey", 25 pages, $2.2 page 3

Program 4. Different classes can implement the List interface. The following program runs a comparison between two different implementations: the ArrayList and LinkedList classes. Copy and run the following program. Be patient, it may take a minute or so to complete. public class RunSpeedTests{ List<Integer> x = new ArrayList<Integer>(); List<Integer> y = new LinkedList<Integer>(); long time = addtofront( x ); System.out.println("Adding to Front of an ArrayList: " + time + " ms" ); time = addtofront( y ); System.out.println("Adding to Front of a LinkedList: " + time + " ms" ); time = accesselement( x, x.size()/2 ); System.out.println("Accessing an element of an ArrayList: " + time + " ms" ); time = accesselement( y, y.size()/2 ); System.out.println("Accessing an element of a LinkedList: " + time + " ms" ); private static long addtofront( List<Integer> list ){ long start_time = System.currentTimeMillis(); for ( int n = 0; n < 200000; n++ ){ int num = (int)(100*math.random()); list.add( 0, num ); long stop_time = System.currentTimeMillis(); return stop_time - start_time; private static long accesselement( List<Integer> list, int index ){ long start_time = System.currentTimeMillis(); for ( int n = 0; n < 100000; n++ ){ int num = list.get( index ); long stop_time = System.currentTimeMillis(); return stop_time - start_time; Calculates the time in ms to add 200,000 numbers to the front of a list. Calculates the time in ms to access an element at a particular index 100,000 times On school computer Adding to Front of an ArrayList: Adding to Front of a LinkedList: Accessing an element of an ArrayList: Accessing an element of a LinkedList: * My times were 10, 60, 9150, and 43724 but not in that order. On my home computer* Access times for LinkedList can vary greatly depending on where the element is. We will talk a little about this in class. page 4

The point of program 4 is emphasize the idea that an interface allows us to specify what something should do without specifying how it should do it. The List interface describes what a linear list should be able to do. The ArrayList and LinkedList classes take very different approaches to implementing the List interface. In some situations an ArrayList is much faster; in other situations a LinkedList is the more efficient implementation. Program 5. Create a file and complete this program. public class Runner{ public static void main(string [] args) { String [] words = { "once", "upon", "a", "time", null ; List<String> mylist = filllist( words ); for ( int n = 0; n < mylist.size(); n++ ) System.out.print( mylist.get(n) + ", " ); System.out.println(); once, upon, a, time, null, List<String> list2 = new ArrayList<String>(); list2.add( "Apples" ); list2.add( "are" ); list2.add( null ); list2.add( "red" ); String [] phrases = fillarray( list2 ); for ( int n = 0; n < phrases.length; n++ ) System.out.print( phrases[n] + ", " ); System.out.println(); Appless, ares, s, reds, ArrayList<String> list3 = new ArrayList<String>(); list3.add( "ok" ); System.out.println( "Size of list3: " + list3.size() ); removenulls( list3 ); System.out.println( "Size of list3: " + list3.size() ); Size of list3: 5 Size of list3: 1 public static List<String> filllist( String [] s ){ Returns a List that is a copy of the data in the array. Use an ArrayList. public static String[] fillarray( List<String> list ){ Returns an array of Strings that consists of the original strings except that an s has been added to the end of each string. If an element is null, then replace it with the letter s public static void removenulls( List<String> s ){ Remove all null values (and only null values) from the list page 5