Title: Big Java
1Big Java
2- Chapter 7
- Arrays and ArrayLists
3Array Basics
- Similar to C, but always allocated
- double data new double10
- Can also have arrays of objects
- BankAccount accounts new BankAccountMAX
- Access is similar to C, but if code goes beyond
array bounds an exception is thrown - for (int i0 ilt10 i)
- System.out.println(datai)
- // ArrayIndexOutOfBoundsException on data10
- Arrays have built-in field named length
- for (int i0 i lt data.length i)
- System.out.println(datai)
4Array Initialization
- Common to forget to allocate space
- double data
- data0 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
5ArrayLists
- 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 - ArrayListltBankAccountgt accounts new
ArrayListltBankAccountgt() - 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
lt size - accounts.remove(1)
- for (int i0 iltaccounts.size() i)
- System.out.println(accounts.get(i).getBalance())
6ArrayList (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)
7Wrappers and Auto-boxing
- Not in C (C evolved from C, Java designed
from scratch as OO) - Numbers are not objects, cant place directly in
ArrayLists - All primitive types have wrapper classes
- Wrapper contains one value of corresponding
primitive type - Also have useful static methods
8Wrappers 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
- ArrayListltDoublegt data new ArrayListltDoublegt()
- data.add(32.14)
- double x data.get(0)
9Efficiency Note
- Even though you dont 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
10Enhanced 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
- ArrayListltBankAccountgt accounts
- . . . add, create sum
- for (BankAccount a accounts)
-
- sum a.getBalance()
-
112D Arrays
- Similar to C, but must always allocate memory
- final int ROWS 3
- final int COLS 3
- String board new StringROWSCOLS
12More 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 double10
- . . .
- double prices (double ) data.clone()
- Or use System.arraycopy if not copying the entire
array (see book or API for details)
13Reading Assignment 1
- Random Fact 7.1 An Early Internet Worm, page 318
- Random Fact 7.2 The Therac-25 Incidents, page 322
- Be ready to discuss in class.
14Reading Assignment 2
- Read 7.8 Regression Testing
- Questions
- What is a test suite?
- What is regression testing?
- What is cycling?
- Continued in Chapter 8
15- On to Chapter 8
- Designing Classes
16Choosing 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)
17Choosing Classes (continued)
- Which of the following are good classes?
- ComputePaycheck
- PaycheckProgram
- Paycheck
- ChessBoard
- MoveChessPiece
- A class should represent a single concept
18Cohesion 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
19UML Dependency Relationship
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)
CashRegister
Coin
20Coupling
low coupling
high coupling
21Static 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 percent of(double p, double
a) -
- return (p/100) a
-
-
- double tax Financial.percentOf(taxRate, total)
22Static 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
23Static Field Initialization
- 3 options
- Do nothing. Get default values.
- Use explicit initializer (like example).
Initialization executed when class is loaded. - Use static initialization block (rarely used)
- public class BankAccount
- . . .
- private static int lastAssignedNumber
- static
-
- lastAssignedNumber 1000
24Reading Assignment
- Quality Tips 8.2 and 8.3 page 345
- Advanced Topic 8.1 (Call by Value and Call by
Reference) page 346 - 8.5 Preconditions and Postconditions, page 347
- Advanced Topic 8.2 (Class Invariants)
- Read self-check question 15
25Packages
- A java package is a set of related classes
(similar to C namespace) - Common packages
26Create 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.
27Unit 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
28JUnit 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.
29Setting up Eclipse projects
- JUnit tests are generally separate from
application source code - File gt New gt Source Folder test
- Put your classes that extend TestCase in the new
source Folder (JUnit v3) - Need to add junit.jar to build path
30Directory Structure
class
related test class
31Build Path
Select Project gt Properties On dialog, select
Java Build Path, Add External Jar Browse to find
junit.jar (normally under plugins) and press Add
32Run as JUnit Test
33JUnit v3 Execution
All is well!
34JUnit v4
- New Java Feature annotations
- Places a marker in code that is interpreted by
another tool - For JUnit, marker/annotation is _at_Test
- No need to extend TestCase
35Need different Build Path
36Slight Modification to Test class
different import
_at_Test annotation
Assert
37JUnit 4 Execution
Same as version 3
38Exercise
- 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/windch
ill.html - for important information