Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Big Java Chapter 7-8 (ArrayList / Class Design) 2009.OOP.r1."— Presentation transcript:

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

2 Chapter 7 Arrays and ArrayLists

3 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]);

4 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}

5 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());

6 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)

7 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

8 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);

9 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

10 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(); }

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

12 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)

13 On to Chapter 8 Designing Classes

14 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)

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

16 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

17 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)

18 Coupling low coupling high coupling

19 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);

20 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;

21 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; }

22 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

23 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.

24 Unit Test Frameworks Good to create a test suite Goal: relieve human from task of comparing expected and actual values JUnit framework available from http://junit.orghttp://junit.org 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

25 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.

26 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

27 Directory Structure class related test class

28 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

29 Run as JUnit Test

30 JUnit v3 Execution All is well!

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

32 Need different Build Path

33 Slight Modification to Test class different import @Test annotation Assert

34 JUnit 4 Execution Same as version 3

35 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: –35.74 + 0.6215T - 35.75V (**0.16) + 0.4275TV(**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 http://www.weatherimages.org/data/windchill.html http://www.weatherimages.org/data/windchill.html for important information


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

Similar presentations


Ads by Google