Post on 01-Jan-2016
transcript
Big JavaBig JavaChapter 7-8Chapter 7-8
(ArrayList / Class Design)(ArrayList / Class Design)
2009.OOP.r12009.OOP.r1
Chapter 7Arrays and ArrayLists
Array BasicsArray 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 lengthfor (int i=0; i < data.length; ++i)
System.out.println(data[i]);
Array InitializationArray Initialization
• Common to forget to allocate spacedouble[] 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}
ArrayListsArrayLists• 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<BankAccount> accounts = new
ArrayList<BankAccount>();accounts.add(new BankAccount(1001));accounts.add(new BankAccount(2010));BankAccount anAccount = accounts.get(1); int count = accounts.size(); // 0 to size-1 are validBankAccount account2 = new BankAccount(3000);accounts.set(1, account2); // overwritesaccounts.add(0, new BankAccount(1200)); // index < sizeaccounts.remove(1);for (int i=0; i<accounts.size(); ++i)
System.out.println(accounts.get(i).getBalance());
ArrayList (continued)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-boxingWrappers 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
Primitive Wrapper
byte Byte
boolean Boolean
char Character
double Double
float Float
int Integer
long Long
short Short
Wrappers and Auto-boxing (continued)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<Double> data = new ArrayList<Double>();data.add(32.14);double x = data.get(0);
Efficiency NoteEfficiency 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 loopEnhanced 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<BankAccount> accounts; . . . add, create sumfor (BankAccount a : accounts){sum += a.getBalance();
}
2D Arrays2D Arrays
• Similar to C++, but must always allocate memoryfinal int ROWS = 3;
final int COLS = 3;
String[][] board = new String[ROWS][COLS];
More on Arrays etc.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 ClassesChoosing 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)Choosing Classes (continued)
• Which of the following are good classes?– ComputePaycheck– PaycheckProgram– Paycheck– ChessBoard– MoveChessPiece
• A class should represent a single concept
Cohesion and CouplingCohesion 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 RelationshipUML Dependency Relationship
CashRegister
Coin
Unified Modeling LanguageBooch, Jacobson, RumbaughIn a class diagram,
dependency is a dashed line with a shaped open arrow that points to dependent class. (i.e., CashRegister depends on Coin)
CouplingCoupling
low coupling high coupling
Static MethodsStatic 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 FieldsStatic 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 InitializationStatic Field Initialization
• 3 options1. 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;
}
PackagesPackages• A java package is a set of related classes (similar
to C++ namespace)• Common packages:
Package Purpose Sample Class
java.lang Language support Math
java.util utilities Random
java.io input/output PrintStream
java.awt AbstractWindowing Toolkit
Color
java.applet Applets Applet
java.net Networking Socket
java.sql Database access ResultSet
Create your own PackageCreate 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 FrameworksUnit 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.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
JUnit Framework ClassesJUnit 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 projectsSetting 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 StructureDirectory Structure
class
related test class
Build PathBuild PathSelect Project > PropertiesOn dialog, select Java Build Path, Add External JarBrowse to find junit.jar (normally under plugins) and press Add
Run as JUnit TestRun as JUnit Test
JUnit v3 ExecutionJUnit v3 Execution
All is well!
JUnit v4JUnit 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
Need different Build PathNeed different Build Path
Slight Modification to Test classSlight Modification to Test class
different import
@Test annotation
Assert
JUnit 4 ExecutionJUnit 4 Execution
Same as version 3
ExerciseExercise• 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 for important information