Big Java Chapter 7-8 (ArrayList / Class Design) 2009.OOP.r1.

Slides:



Advertisements
Similar presentations
Lists and the Collection Interface Chapter 4. Chapter Objectives To become familiar with the List interface To understand how to write an array-based.
Advertisements

Chapter 8: Designing Classes
Week 10 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
Chapter 7 Arrays and Array Lists. Chapter Goals To become familiar with using arrays and array lists To learn about wrapper classes, auto-boxing and the.
Designing Classes Chapter 8. Classes Collection of objects Objects are not actions Class names – Nouns Method names – Verbs What Makes a Good Class Represent.
Arrays.
Chapter Goals To learn how to choose appropriate classes to implement
Chapter 7 – Arrays.
Computer Science A 10: 20/3. Array Array: Sequence of values of the same type Construct array: new double[10] Store in variable of type double[] double[]
CSM-Java Programming-I Spring,2005 Class Design Lesson - 4.
Chapter 7  Arrays and Array Lists 1 Chapter 7 Arrays and Array Lists.
Loops Notes adapted from Dr. Flores. It repeats a set of statements while a condition is true. while (condition) { execute these statements; } “while”
Datalogi A 8: 27/10. Array Array: Sequence of values of the same type Construct array: new double[10] Store in variable of type double[] double[] data.
Lists and the Collection Interface Chapter 4. Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.
Chapter 5: Enhancing Classes Presentation slides for Java Software Solutions Foundations of Program Design Second Edition by John Lewis and William Loftus.
1 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 8 focuses on: array declaration and use passing arrays and array.
Chapter 14 Generics and the ArrayList Class Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Fall 2007CS 2251 Lists and the Collection Interface Chapter 4.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 10 *Arrays with more than one dimension *Java Collections API.
Aalborg Media Lab 28-Jun-15 Software Design Lecture 8 “Arrays”
Arrays, Loops weeks 4-6 (change from syllabus for week 6) Chapter 4.
Static Class Members Wrapper Classes Autoboxing Unboxing.
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 Objects OO basics. Topics Basic array syntax/use OO Vocabulary review Simple OO example Instance and Static methods Static vs. instance vs.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 l Array Basics l Arrays in Classes and Methods l Programming with Arrays.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
Java Programming Week 6: Array and ArrayList Chapter 7.
Data Objects (revisited) Recall that values are stored in data objects, and that each data object holds one value of a particular type. Data objects may.
For each primitive type there is a wrapper class for storing values of that type: Double d = new Double(29.95); Wrapper Classes Wrapper objects can be.
Chapter 7 Objects and Memory. Structure of memory The fundamental unit of memory is called a bit, either 0 or 1. In most modern architectures, the smallest.
Class Library, Formatting, Wrapper Classes, and JUnit Testing
Week 10 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
ARRAYLIST Collections of Data. ArrayLists Array lists can grow and shrink as needed ArrayList is a generic class (similar to C++ template) ArrayList has.
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 2.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 8 – Designing Classes.
5-Aug-2002cse Arrays © 2002 University of Washington1 Arrays CSE 142, Summer 2002 Computer Programming 1
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
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?
Fall 2006Slides adapted from Java Concepts companion slides1 Arrays and Array Lists Advanced Programming ICOM 4015 Lecture 7 Reading: Java Concepts Chapter.
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
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.
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. A class represents a single concept from the problem domain, or a.
© 2004 Pearson Addison-Wesley. All rights reserved September 7, 2007 Formatting Output & Enumerated Types & Wrapper Classes ComS 207: Programming I (in.
©SoftMoore ConsultingSlide 1 Generics “Generics constitute the most significant change in the Java programming language since the 1.0 release.” – Cay Horstmann.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Arrays and ArrayLists Topic 6. One Dimensional Arrays Homogeneous – all of the same type Contiguous – all elements are stored sequentially in memory For.
Classes, Interfaces and Packages
Arrays. Array: Sequence of values of the same type Construct array: Store in variable of type double[ ] new double[10] double[] data = new double[10];
Week 9 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
Java Software Solutions Foundations of Program Design Sixth Edition by Lewis & Loftus Chapter 3: Using Classes and Objects Coming up: Creating Objects.
Java How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Chapter 4: More Object Concepts. Objectives Understand blocks and scope Overload a method Avoid ambiguity Create and call constructors with parameters.
Arrays (part 2) 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
(C) 2010 Pearson Education, Inc. All rights reserved. Java How to Program, 8/e.
Arrays Chap. 9 Storing Collections of Values 1. Introductory Example Problem: Teachers need to be able to compute a variety of grading statistics for.
1 Java Review Outline Java Primitives, Program Structure Operators, Control Flow, Loops Classes and Objects Arrays and ArrayList Most of these slides are.
© 2004 Pearson Addison-Wesley. All rights reserved January 27, 2006 Formatting Output & Enumerated Types & Wrapper Classes ComS 207: Programming I (in.
Week 9 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
Coming up ArrayList ArrayList vs Array – Declaration – Insertion – Access – Removal Wrapper classes Iterator object.
Principles of Computer Science I
Chapter 8 – Arrays and Array Lists
Lecture 7 Designing Classes
Can store many of the same kind of data together
Can store many of the same kind of data together
Object Oriented Programming in java
Arrays and Array Lists CS 21a.
Can store many of the same kind of data together
Review for Midterm 3.
Presentation transcript:

Big Java Chapter 7-8 (ArrayList / Class Design) 2009.OOP.r1

Chapter 7 Arrays and ArrayLists

Array Basics Similar to C++, but always allocated: double [] data = new double[10]; Can also have arrays of objects: BankAccount[] accounts = new BankAccount[MAX]; Access is similar to C++, but if code goes beyond array bounds an exception is thrown: for (int i=0; i<=10; ++i) System.out.println(data[i]); // ArrayIndexOutOfBoundsException on data[10] Arrays have built-in field named length for (int i=0; i < data.length; ++i) System.out.println(data[i]);

Array Initialization Common to forget to allocate space double[] data; data[0] = 29.5; Can initialize in declaration, like C++: int[] primes = {2, 3, 5, 7, 11}; Can use an anonymous array as parameter: new int[] {2, 3, 5, 7, 11}

ArrayLists Array lists can grow and shrink as needed ArrayList is a generic class (similar to C++ template) ArrayList has variety of methods for common tasks, for example: ArrayList accounts = new ArrayList (); accounts.add(new BankAccount(1001)); accounts.add(new BankAccount(2010)); BankAccount anAccount = accounts.get(1); int count = accounts.size(); // 0 to size-1 are valid BankAccount account2 = new BankAccount(3000); accounts.set(1, account2); // overwrites accounts.add(0, new BankAccount(1200)); // index < size accounts.remove(1); for (int i=0; i<accounts.size(); ++i) System.out.println(accounts.get(i).getBalance());

ArrayList (continued) With an unparameterized ArrayList, any type of object may be stored, but the object must be cast when retrieved: ArrayList accounts = new ArrayList(); accounts.add(new BankAccount(1500)); BankAccount acct = (BankAccount) accounts.get(0); Exception will occur if cast is incorrect. Much better practice to use generic class (warning in Eclipse if use unparameterized)

Wrappers and Auto-boxing Not in C++ (C++ evolved from C, Java designed from scratch as OO) Numbers are not objects, can’t place directly in ArrayLists All primitive types have “wrapper” classes Wrapper contains one value of corresponding primitive type Also have useful static methods PrimitiveWrapper byteByte booleanBoolean charCharacter doubleDouble floatFloat intInteger longLong shortShort

Wrappers and Auto-boxing (continued) Starting with Java 5.0, conversion between primitive types and wrapper classes is automatic, called auto-boxing (auto-wrapping would be more consistent!) Examples: Double d = 29.95; // Double d = new Double(29.95); double x = 5; // auto-unbox, same as double x = d.doubleValue(); Double e = d + 1; // auto-unbox, add 1, auto-box ArrayList data = new ArrayList (); data.add(32.14); double x = data.get(0);

Efficiency Note Even though you don’t have to write the code, if you have a long sequence of primitive types (numbers or chars), use an array rather than an ArrayList for efficiency

Enhanced for loop Convenient new syntax for iterating an array or ArrayList: double[] data = {... }; double sum = 0; for (double e : data) { sum = sum + e; } With ArrayLists: ArrayList accounts;... add, create sum for (BankAccount a : accounts) { sum += a.getBalance(); }

2D Arrays Similar to C++, but must always allocate memory final int ROWS = 3; final int COLS = 3; String[][] board = new String[ROWS][COLS];

More on Arrays etc. First choice will normally be ArrayList, unless storing large collection of primitives OR need 2D Use “for each” loop pattern when processing all elements To make a copy, use the clone method: double [] data = new double[10];... double [] prices = (double []) data.clone(); Or use System.arraycopy if not copying the entire array (see book or API for details)

On to Chapter 8 Designing Classes

Choosing Classes Common: class names are nouns, methods names are verbs –class BankAccount, methods deposit, withdraw etc. –class CashRegister, methods enterPayment, recordPurchase, etc. Classes may also be actors that do some type of work for you –Scanner scans stream for numbers and strings –Random generates random numbers Utility class may have no objects, but exists to provide static methods and constants –Math class Some classes just exist to start a program (degenerate classes)

Choosing Classes (continued) Which of the following are good classes? –ComputePaycheck –PaycheckProgram –Paycheck –ChessBoard –MoveChessPiece A class should represent a single concept

Cohesion and Coupling Cohesion: All public methods (i.e., the public interface) should be closely related to the single concept the class represents Coupling: Number of dependencies between classes

UML Dependency Relationship CashRegister Coin Unified Modeling Language Booch, Jacobson, Rumbaugh In a class diagram, dependency is a dashed line with a shaped open arrow that points to dependent class. (i.e., CashRegister depends on Coin)

Coupling low coupling high coupling

Static Methods Also known as class method Does not operate on an object, so it has only explicit parameters Example: public class Financial { public static double percentOf(double p, double a) { return (p/100) * a; } double tax = Financial.percentOf(taxRate, total);

Static Fields Used to store values outside any particular object public class BankAccount { private double balance; print int lastAssignedNumber = 1000; // No … } should be: print static int lastAssignedNumber = 1000;

Static Field Initialization 3 options 1.Do nothing. Get default values. 2.Use explicit initializer (like example). Initialization executed when class is loaded. 3.Use static initialization block (rarely used) public class BankAccount {... private static int lastAssignedNumber; static { lastAssignedNumber = 1000; }

Packages A java package is a set of related classes (similar to C++ namespace) Common packages: PackagePurposeSample Class java.langLanguage supportMath java.utilutilitiesRandom java.ioinput/outputPrintStream java.awtAbstractWindowing Toolkit Color java.appletAppletsApplet java.netNetworkingSocket java.sqlDatabase accessResultSet

Create your own Package Put a package statement on first line: package com.horstmann.bigjava To avoid name clashes, common to use domain names Can import an entire package or a single class: import java.util.*; import java.util.ArrayList; Directory structure on disk will match package (e.g., com/horstmann/bigjava) Directories containing packages should be added to the classpath (depends on OS/IDE) In Eclipse, you can use the New Package icon to create a package, and the directory structure will be created for you.

Unit Test Frameworks Good to create a test suite Goal: relieve human from task of comparing expected and actual values JUnit framework available from Also included in Eclipse Idea: design companion test class for each class –In JUnit 3, test class must extend class TestCase from junit.framework –define a method whose name starts with test, e.g., testSimpleCase –If all tests pass, JUnit shows a green bar

JUnit Framework Classes Test Case. Collects a set of test methods. Name starts with test. Has no arguments. Test Suite. Collection of tests run at the same time. May be just a single test method. Test Runner. Utility used to run a test suite. In Eclipse, shows a graphical presentation. May also be a command-line version.

Setting up Eclipse projects JUnit tests are generally separate from application source code File > New > Source Folder test Put your classes that extend TestCase in the new source Folder (JUnit v3) Need to add junit.jar to build path

Directory Structure class related test class

Build Path Select Project > Properties On dialog, select Java Build Path, Add External Jar Browse to find junit.jar (normally under plugins) and press Add

Run as JUnit Test

JUnit v3 Execution All is well!

JUnit v4 New Java Feature: annotations Places a “marker” in code that is interpreted by another tool For JUnit, marker/annotation No need to extend TestCase

Need different Build Path

Slight Modification to Test class different annotation Assert

JUnit 4 Execution Same as version 3

Exercise Work with a partner Download CashRegister and the associated test classes from Blackboard Set up and run in Eclipse using both version 3 and version 4 of JUnit Write a program that uses JOptionPane dialogs to prompt the user for a temperature and wind speed, displays the wind chill, then asks whether the user wants to do more temperatures. The formula for wind chill is: – T V (**0.16) TV(**0.16) In the formula, V is in the wind speed in statute miles per hour, and T is the temperature in degrees Fahrenheit. Write a test class to accompany your wind chill calculator NOTE: See for important information