Advanced Review - PowerPoint PPT Presentation

1 / 75
About This Presentation
Title:

Advanced Review

Description:

Intermediate Review - Columbia University ... Advanced Review – PowerPoint PPT presentation

Number of Views:125
Avg rating:3.0/5.0
Slides: 76
Provided by: shl82
Category:

less

Transcript and Presenter's Notes

Title: Advanced Review


1
Advanced Review
2
Advanced Review
  • Time classes
  • Date Classes
  • File input/output
  • Packages

3
Multiple dimensions
  • No reason cant create 4,5,6 dimension arrays
  • Gets hard to manage
  • Better idea
  • Think about another way of representing the data
  • Often creating an object is a better approach

4
Arrays further
  • Need to explicitly copy contents of arrays when
    resizing arrays with temp one
  • Better solution
  • ArrayList
  • Vector
  • Full object versions of arrays
  • Capacity can grow over time
  • Useful methods bundles with them

5
code
  • Create a new class with a main called VectorTest
  • Create a vector
  • Put in some stuff
  • Print them out
  • Replace something in the middle
  • Print it out
  • Clear the vector
  • Print it out

6
Default values
  • Should be aware if you forget to set values
  • Might mess up your logic
  • Think of multiplying a bunch of numbers and not
    setting one of them
  • Compiler/IDE will let you know if you forgot to
    set values (warning)

7
Time
  • Next lets discuss how time is handled in Java
  • Java.util.Date is the way java represents a point
    in time
  • It is measured in milliseconds
  • Time 0 what does that mean?

8
Date
  • Time 0 first millisecond in 1970
  • Historical reasons for this
  • long is the type it uses
  • Range to 9,223,372,036,854,775,807
  • Dont memorize that
  • Lets look at the API
  • What is a deprecated method ??
  • Example getDay() ??

9
Why Date
  • Why are we wrapping the time long number?
  • "I'll see you on 996,321,998,346." doesnt really
    work
  • Also allows you to easily order and compare
    different points in time.meaningfully

10
Change over time (no pun)
  • Nothing you program should be set in stone
  • Sometimes your design changes
  • Need to go back and change your code
  • Deprecated methods are those which have been
    replacedbut left in place so your old stuff
    shouldnt crash if you try to recompile with
    latest jdk

11
Back to time
  • System.currentTimeMillis()
  • Returns the current time on the system
  • As a Date Object

12
Ideas
  • Although would like to represent a point in time,
    usually time is associated with other
    measurements
  • Month
  • Year

13
The GregorianCalendar Class
  • The Date class doesn't measure months, weekdays,
    etc.
  • That's the job of a calendar
  • A calendar assigns a name to a point in time
  • Many calendars in use
  • Gregorian
  • Contemporary Hebrew, Arabic, Chinese
  • Historical French Revolutionary, Mayan

14
Relationships
15
Next step
  • Lets design a new class to represent a day
  • Today is Tuesday
  • Day today new Day()
  • Today.add(1) //should give us Wednesday

16
Goal of Day Class
  • Answer questions such as
  • How many days are there between now and the end
    of the year?
  • What day is 100 days from now?
  • How many days till my birthday (Ive always
    wanted a _____________)

17
Designing the class
  • Lets have a method
  • daysFrom it computes number of days between two
    days
  • int n today.daysFrom(birthday)
  • addDays computes a day that is some days away
    from a given day
  • Day later today.addDays(999)
  • Mathematical relationship
  • d.addDays(n).daysFrom(d) n
  • d1.addDays(d2.daysFrom(d1)) d2

18
  • Constructor Date(int year, int month, int date)
  • Will need the following methods
  • getYear
  • getMonth
  • getDate

19
Implementation
  • Straightforward which member will need
  • private int year
  • private int month
  • private int date
  • addDays/daysBetween tedious to implement
  • April, June, September, November have 30 days
  • February has 28 days, except in leap years it has
    29 days
  • All other months have 31 days
  • Leap years are divisible by 4, except after 1582,
    years divisible by 100 but not 400 are not leap
    years
  • There is no year 0 year 1 is preceded by year -1
  • In the switchover to the Gregorian calendar, ten
    days were dropped October 15, 1582 is preceded
    by October 4

20
Day Code
  • public Day(int aYear, int aMonth, int aDate)
  • year aYear
  • month aMonth
  • date aDate
  • private int year
  • private int month
  • private int date
  • private static final int DAYS_PER_MONTH
  • 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30,
    31
  • private static final int GREGORIAN_START_YEAR
    1582
  • private static final int GREGORIAN_START_MONTH
    10
  • private static final int GREGORIAN_START_DAY
    15
  • private static final int JULIAN_END_DAY 4

21
Day Code
  • private Day nextDay()
  • 112
  • 113 int y year
  • 114 int m month
  • 115 int d date
  • 116
  • 117 if (y GREGORIAN_START_YEAR
  • 118 m GREGORIAN_START_MONTH
  • 119 d JULIAN_END_DAY)
  • 120 d GREGORIAN_START_DAY
  • 121 else if (d lt daysPerMonth(y, m))
  • 122 d
  • 123 else
  • 124
  • 125 d 1
  • 126 m
  • 127 if (m gt DECEMBER)
  • 128
  • 129 m JANUARY

22
  • private static int daysPerMonth(int y, int m)
  • int days DAYS_PER_MONTHm - 1
  • if (m FEBRUARY isLeapYear(y))
  • days
  • return days
  • private static boolean isLeapYear(int y)
  • if (y 4 ! 0) return false
  • if (y lt GREGORIAN_START_YEAR) return true
  • return (y 100 ! 0) (y 400 0)

23
Tester
  • 01 public class DayTester
  • 02
  • 03 public static void main(String args)
  • 04
  • 05 Day today new Day(2001, 2,
    3)//February 3, 2001
  • 06 Day later today.addDays(999)
  • 07 System.out.println(later.getYear()
  • 08 "-" later.getMonth()
  • 09 "-" later.getDate())
  • 10 System.out.println(later.daysFrom(today)
    )// Prints 999
  • 11
  • 12

24
Notice
  • Private helper methods
  • Notice all the work to increment a day

25
Another idea
  • This is for illustration, dont need to code
  • For greater efficiency, we can use Julian day
    number
  • Used in astronomy
  • Number of days since Jan. 1, 4713 BCE
  • May 23, 1968 Julian Day 2,440,000
  • Greatly simplifies date arithmetic

26
Code
  • public Day(int aYear, int aMonth, int aDate)
  • //notice we are calling a private
  • //helper function
  • julian toJulian(aYear, aMonth, aDate)
  • //thats all we need
  • private int julian

27
Helper function
  • private static int toJulian(int year, int month,
    int date)
  • int jy year
  • if (year lt 0) jy
  • int jm month
  • if (month gt 2) jm
  • else
  • jy--
  • jm 13
  • int jul (int) (java.lang.Math.floor(365.25
    jy)
  • java.lang.Math.floor(30.6001 jm) date
    1720995.0)
  • int IGREG 15 31 (10 12 1582)
  • // Gregorian Calendar adopted Oct. 15, 1582
  • if (date 31 (month 12 year) gt IGREG)
  • // Change over to Gregorian calendar
  • int ja (int) (0.01 jy)
  • jul 2 - ja (int) (0.25 ja)

28
Any other ideas?
  • So you see that using the class doesnt change
    even though we totally changed how the inside
    works
  • Called encapsulation
  • So its easy to move up or down the calendar
  • Add subtract
  • Where would it cost us ??

29
Switch gears
  • Lets talk about how to use files
  • Your program starts in main, computes, then maybe
    prints out something before closing up
  • Would be great if can save results somewhere
  • Hey lets use files ?

30
File manipulations
  • Working with files
  • Reading files
  • Writing files

31
Please note
  • One of the great things about file manipulation
    on java is that it is the same on
  • Windows
  • Linux
  • Mac
  • If done right

32
File
  • Basic object is called File
  • File data new File(test.txt)
  • It will look in the same directory the java file
    is sitting in for the test file
  • Calling data.getAbsolutePath()
  • Will print out the local version of the full path
    to the file

33
Directories
  • If your File object is a directory
  • The list method returns an array of String file
    names,
  • listFiles returns an array of File objects

34
limitations
  • The File object has a limited number of useful
    methods
  • None which can actually write something to it
  • Need to use higher level class to work with file
    contents

35
Dealing with text
  • When dealing with text output/input can use
  • PrintWriter to write to a file

36
code
  • PrintWriter pw new PrintWriter(new
    FileWriter(new File("Test.txt")))
  • What is FileWriter ?
  • Lets pull up the API

37
  • Helper class to help make sure things are written
    efficiently
  • Dont forget to close the file handle when done
  • And flush if using a buffered handle

38
  • Ok lets write some code
  • Main program
  • Will write a 3 line poem (yes you need to write
    one now) to a test.txt file
  • Notice how your have to add try catch to handle
    certain declared exceptions ??

39
Run code
  • Confirm that the file has been created
  • Now write another class to read the file

40
  • How would you adopt the reader to find something
    in the file ??

41
  • For each line read
  • Look for something
  • See String API for helper methods
  • Now write the code ?

42
Next up
  • Interfaces
  • Inheritance
  • Abstract Classes
  • Polymorphism
  • Generics

43
Two dimensions
  • You can also initialize the inner array as a
    separate call.
  • Doesnt have to be congruous memory locations
  • int example new int5
  • for (int i0ilt5i)
  • examplei new inti1

44
Interface
  • An interface is a special class that defines the
    behavior of other classes
  • Example
  • How many mp3 players are on the market ?

45
Mp3 players
  • No matter what type of mp3 player you buy you
    expect certain behavior
  • Play
  • Forward(next song)
  • Rewind(last song)
  • Random
  • Think of your own

46
  • If I want to program a bunch of mp3 players and
    want to force all of them to have some minimum
    behavior I would encode that as an interface
  • Here is an example

47
code
  • public interface mp3player
  • public boolean play()
  • public boolean rewind()
  • public boolean forward()
  • public int getSongCount()
  • public boolean deleteAll()

48
analysis
  • Basically am defining ideas
  • Would add comments to each what they are supposed
    to be doing (expected behavior
  • Then any class which wants to be nice, would
    agree to behave this way

49
Code IpodMP3
  • Say we want to create a really cool mapple ipod
    player
  • Want to stick to the mp3 behavior
  • public class Ipodmp3 implements mp3player ..
  • This means that we need to define those methods
    for this specific class

50
Note
  • Can implement as many interfaces as you like
  • Will notice them in the api when you look at the
    standard libraries
  • Compiler will check and complain if you dont
    implement all the methods you are promising in
    the interface you impliment
  • Nothing actually checks that you are doing the
    correct thing.that is up to the programmer

51
GASP!
  • Question so what does Ipodmp3 player1 new
    Ipodmp3 ()player1.play()actually do ??
  • Answer Maybe erase your hard drivelook at the
    source code ?

52
Iterators
  • Many of the classes in Java represent a
    collection of items
  • Some have order
  • Some dont have order
  • All the students in one room
  • Alphabetical list
  • Bag of names (raffle)

53
Two types
  • Here is a general Iterator idea
  • Get the iterator object from the class
  • Can ask the iterator object if it has any more
    stuff
  • Get the next thing

54
Inheritance
  • You have a really useful class
  • Want to specialize it in more than one way
  • Can either copy paste a bunch of time and tweak
    each copy
  • Problem if we find a bug, will need to run to all
    copies and fix everything

55
Easier way
  • Look at all the classes that are related, what
    ideas do they all share
  • Example what is common between all kinds of cars
  • Make that idea the base class, and each
    specialization a sub class
  • Known as inheritance!

56
Inheritance
  • Use the extends keyword
  • Allows you to reuse objects
  • Some issues
  • When do you extend?
  • When do you implement an interface?

57
Example
  • Geneal idea of an Animal
  • Can code it as class Animal
  • Then have specific code
  • class Horse extends Animal
  • class Whale extends Animal
  • What ever methods are the same in both would be
    coded in the Animal class, specific methods
    (numberLegs() would be defined in the specific
    subclass)

58
Super constructors
  • When refering to parent class (Animal)
  • Use super keyword in subclass constructor
  • public Horse(String aName)
  • super(aName) // calls superclass constructor
  • //rest of your stuff here
  • Call to super must be first statement in subclass
    constructor
  • If subclass constructor doesn't call super,
    superclass must have constructor without
    parameters

59
Polymorphism
  • This is just fancy word that tells you java will
    figure out the following code
  • Animal A new Horse(tom)
  • So although A is really a horse, it can be
    refered to by parent handle.
  • This would be illigal
  • Horse A new Whale()
  • Why ?

60
Next
  • Imagine you have a class which has variable
    members of a specific type
  • Example
  • Have a list of numbers, say a list of zip codes
    which you have sent packages in the last X months
  • What if you want to change zip codes to Strings
    because you are now sending packages to canada

61
2 solutions
  • Copy paste code and replace all ints with Strings
  • Debug like crazy
  • .or use Generics

62
Basic idea
  • Tell java you are dealing with some type without
    know what it is
  • Can set some rules on it
  • When you create an instance of the object you
    will tell java what you want

63
Code
  • public class shoppingListltTgt
  • private ArrayListltTgt theList
  • shoppingList()
  • theList new ArrayListltTgt()
  • public void addItem(T item)
  • theList.add(item)
  • public int getNumberOnList()
  • return theList.size()
  • public T getItemAt(int location)
  • return theList.get(location)

64
Code 1
  • //once you get previous screen running at the
    following method
  • public void showType()
  • System.out.println("Type of T is "
  • ob.getClass().getName())

65
Usage
  • shoppingListltIntegergt e1
  • e1 new shoppingListltIntegergt
  • e1.add(15)
  • int v e1.getItemAt(0)
  • Write a main to test the idea of generics

66
Example2
  • class Example2ltT, Vgt
  • T ob1
  • V ob2
  • Example2(T o1, V o2)
  • ob1 o1
  • ob2 o2
  • T getob1()
  • return ob1
  • V getob2()
  • return ob2

67
Example 3
  • class Example3ltQ extends Numbergt
  • Q nums // array of Number or subclass
  • Stats(Q o)
  • nums o
  • double sum()
  • double sum 0.0
  • for(int i0 i lt nums.length i)
  • sum numsi.doubleValue()
  • return sum

68
Usage
  • Double dnums 1.1, 2.2, 3.3, 4.4, 5.5
  • Example3ltDoublegt dob new Example3ltDoublegt(dnums)
  • double w dob.sum()
  • System.out.println("dob sum is " w)

69
Example4
  • class TwoD
  • int x, y
  • TwoD(int a, int b)
  • x a
  • y b
  • class ThreeD extends TwoD
  • int z
  • ThreeD(int a, int b, int c)
  • super(a, b)
  • z c
  • class FourD extends ThreeD
  • int t
  • FourD(int a, int b, int c, int d)

70
  • class CoordsltT extends TwoDgt
  • T coords
  • Coords(T o) coords o

71
  • static void showXY(Coordslt?gt c)
  • System.out.println("X Y Coordinates")
  • for(int i0 i lt c.coords.length i)
  • System.out.println(c.coordsi.x " "
  • c.coordsi.y)
  • System.out.println()

72
  • static void showXYZ(Coordslt? extends ThreeDgt c)
  • System.out.println("X Y Z Coordinates")
  • for(int i0 i lt c.coords.length i)
  • System.out.println(c.coordsi.x " "
  • c.coordsi.y " "
  • c.coordsi.z)
  • System.out.println()

73
  • static void showAll(Coordslt? extends FourDgt c)
  • System.out.println("X Y Z T Coordinates")
  • for(int i0 i lt c.coords.length i)
  • System.out.println(c.coordsi.x " "
  • c.coordsi.y " "
  • c.coordsi.z " "
  • c.coordsi.t)
  • System.out.println()

74
Using in methods
  • Just learn how to read the following
  • static ltT, V extends Tgt boolean isIn(T x, V y)
  • for(int i0 i lt y.length i)
  • if(x.equals(yi)) return true
  • return false

75
  • Hope you had fun learning this!
Write a Comment
User Comments (0)
About PowerShow.com