Class Object - PowerPoint PPT Presentation

1 / 38
About This Presentation
Title:

Class Object

Description:

try { ObjectOutputStream out = new ObjectOutputStream( new FileOutputStream(Filename) ... { try { ObjectInputStream in = new ObjectInputStream( new ... – PowerPoint PPT presentation

Number of Views:76
Avg rating:3.0/5.0
Slides: 39
Provided by: michael742
Category:
Tags: class | object | try

less

Transcript and Presenter's Notes

Title: Class Object


1
Class Object
  • Common parent (base class)
  • Minimal functionality
  • Classes may override to provide specific
    behaviour
  • public boolean equals(Object other)
  • public int hashCode()
  • public String toString()
  • public Class getClass()
  • public Object clone()

2
Serialization
  • Serialization is the process of transforming an
    object into a stream of bytes.
  • Deserialization is the reverse process.
  • public interface Serializable
  • Making an object serializable requires almost no
    effort (the interface Serializable is empty).
  • More complex operations may be necessary if, for
    instance, just a portion of an objects state is
    to be saved on the output stream.

3
Serialization (cont.)
  • import java.io.
  • public class IntPair implements Serializable
  • int x
  • int y
  • public IntPair(int x, int y)
  • this.x x
  • this.y y
  • public String toString()
  • return (" x "," y ")"

4
Serialization (cont.)
  • import java.io.
  • public class inout
  • public static void main(String args)
  • IntPair p new IntPair(2,3)
  • try
  • ObjectOutputStream out new
    ObjectOutputStream(
  • new FileOutputStream(Filename))
  • out.writeObject(p)
  • out.close()
  • catch(IOException e)
  • e.printStackTrace()

5
Serialization (cont.)
  • import java.io.
  • public class inout
  • public static void main(String args)
  • try
  • ObjectInputStream in new
    ObjectInputStream(
  • new FileInputStream(Filename))
  • IntPair p (IntPair) in.readObject()
  • System.out.println(p)
  • catch(Exception e)
  • e.printStackTrace()

6
Some useful interfaces
  • interface Serializable
  • interface Cloneable
  • this interface does not include the clone method.
  • a class implements the Cloneable interface to
    indicate to the Object.clone() method that it is
    legal for that method to make a field-for-field
    copy of instances of that class.
  • interface ComparableltTgt
  • public int compareTo(T o)
  • this interface imposes a total ordering on the
    objects of each class that implements it.
  • compareTo(T o) returns a negative integer, zero,
    or a positive integer as this object is less
    than, equal to, or greater than the specified
    object.
  • interface ComparatorltTgt
  • public int compare(T o1, T o2)

7
Utility Classes
  • The Java library provides a number of small
    utility classes, including
  • Point
  • Dimension
  • Date, Calendar
  • Math
  • Random
  • Toolkit
  • System
  • String and related classes

8
Points
x
Points represent locations in a two-dimensional
space.
y
  • class Point implements Cloneable, Serializable
  • public Point(int x, int y) //constructor
  • public int x //public accessible data
  • public int y //fields
  • public void move(int x, int y) //move to a
    given location
  • public void translate(int x, int y) //change by
    offset
  • public boolean equals(Object p) //compare two
    points
  • public String toString() //convert to string

9
Dimension
  • A dimension is used to represent a rectangular
    size. Dimensions are
  • characterized by a width and a height.
  • class Dimension implements Cloneable,
    Serializable
  • public Dimension() //constructors
  • public Dimension(int w, int h)
  • public Dimension(Dimension d) //make a copy
    (clone ?!?!)
  • public int width //public accessible data
    fields
  • public int height
  • public String toString() //operations

10
Date, Calendar
  • The class Date is used to represent both data and
    time values.
  • class Date implements Cloneable, Comparable,
    Serializable
  • public Date() //constructors
  • public Date(int year, int month, int
    day) //deprecated,
  • public Date(int year, int month, int day,
    //replaced by
  • int hours, int minutes) //Calendar and
  • public Date(int year, int month, int day, //the
    set method int hours, int minutes, int seconds)
  • public int getDate() //field access methods
  • public int getDay() //deprecated, replaced by
    Calendar and the
  • public int getHours() //get method
  • public int getMinutes()
  • public int getMonth()
  • public int getSeconds()
  • public int getYear()
  • public int getTimezoneOffset()

11
  • //epoch methods
  • public long getTime() //returns milliseconds
    since epoch
  • public void setTime(long lval) //set time from
    epoch
  • //field setting methods
  • public void setDate(int date) //deprecated,
    replaced by
  • public void setHours(int hour) //Calendar and
    the get method
  • public void setMinutes(int minutes)
  • public void setMonth(int month)
  • public void setSeconds(int seconds)
  • public void setYear(int year)
  • //comparison methods
  • public boolean after(Date when)
  • public boolean before(Date when)
  • public boolean equals(Object when)
  • //output
  • public String toString()

12
Date - Example
  • Date start new Date()
  • int j 0
  • for (int i 0 i lt 100000 i)
  • j j 1
  • Date end new Date()
  • System.out.println(That took
  • (end.getTime() start.getTime())
  • milliseconds. )

13
Math
  • The class Math provides a number of constants, as
    well as useful
  • mathematical functions.
  • final class Math
  • //constants
  • public static final double E //2.71828
  • public static final double PI //3.14159
  • //trigonometric operations, angles in radians
  • public static double sin(double num)
  • public static double cos(double num)
  • public static double tan(double num)
  • public static double asin(double num)
  • public static double acos(double num)
  • public static double atan(double num)
  • public static double atan(double s, double c)

14
  • //rounding operations
  • public static double ceil(double num)
  • public static double floor(double num)
  • public static double rint(double num)
  • public static int round(float num)
  • public static long round(double num)
  • //exponential and powers
  • public static double exp(double y)
  • public static double pow(double x, double y)
  • public static double log(double x)
  • public static double sqrt(double x)

15
  • //other operations
  • public static int abs(int num)
  • public static long abs(long num)
  • public static float abs(float num)
  • public static double abs(double num)
  • public static int max(int x, int y)
  • public static long max(long x, long y)
  • public static float max(float x, float y)
  • public static double max(double x, double y)
  • public static int min(int x, int y)
  • public static long min(long x, long y)
  • public static float min(float x, float y)
  • public static double min(double x, double y)
  • public static double random()

16
Random
  • The class Random provides more general facilities
    for random numbers.
  • class Random implements Serializable
  • //constructors
  • Random()
  • Random(long seed)
  • //operations
  • public void setSeed(long seed)
  • public double nextDouble()
  • public float nextFloat()
  • public int nextInt()
  • public int nextInt(int n)
  • public long nextLong()
  • //alternative distribution
  • public double nextGaussian()

17
Random - Example
  • static public int weightedDistribution(int
    weights)
  • int sum 0
  • for(int i 0 i lt weights.length i)
  • sum weightsi
  • int val (int) Math.floor(Math.random()sum
    1)
  • for(int i 0 i lt weights.length i)
  • val - weightsi
  • if (val lt 0) return i
  • return 0

18
Toolkit
  • This class is the abstract superclass of all
    actual implementations of the Abstract Window
    Toolkit (AWT).
  • Useful methods
  • getFontList() returns an array of string values,
    containing the names of the fonts available on
    the current system.
  • getImage() takes as a parameter either a string
    (a file name) or a URL returns an image as a
    value of type Image.
  • getScreenSize() returns the number of pixels
    (type Dimension) in the screen.
  • getScreenResolution() returns the number of dots
    per inch.
  • The Toolkit class is an example of the Abstract
    Factory design pattern .

19
System
  • The class System gives access to several
    system-wide resources.
  • System.in standard input
  • System.out standard output
  • System.err error output
  • Useful methods
  • exit(int) immediately halts the current running
    program, yielding to the operating system the
    integer status given in the argument.
  • currentTimeMillis() returns the current time in
    milliseconds since epoch.

20
String
  • In Java a string is an immutable object it
    cannot be changed.
  • implements CharSequence, Comparable, Serializable
  • String name John Smith
  • The addition operator, , is overloaded
  • System.out.println(The answer is answer)
  • addition operator groups left to right, i.e.,
  • System.out.println(Catch- 2 2)
  • yields Catch-22,
  • System.out.println(2 2 warned)
  • yields 4warned
  • use equals(Object obj) or equalsIgnoreCase(String
    str) to compare strings

21
String (cont.)
  • final class String
  • ?
  • public static String valueOf(Object obj)
  • if (obj null)
  • return null
  • else
  • return obj.toString()
  • ?
  • If obj is a string valueOf returns a reference to
    the original, not a copy!

22
StringBuffer
  • String as an array of character symbol similar
    to C.
  • The methods append, insert, and reverse change
    the current string buffer and return a reference
    to the updated string buffer.
  • String str1 Hello
  • String str2 str1 str1
  • StringBuffer strbuf1 new StringBuffer(Hello
    )
  • StringBuffer strbuf2 strbuf1.append(strbuf1)

23
Collections
  • containers, data structures
  • kinds
  • bags (multiset)
  • unordered with duplicates
  • Collection
  • set
  • unordered without duplicates
  • also sorted or ordered sets
  • Set and SortedSet
  • list (sequence)
  • ordered with duplicates
  • indexing by position
  • List
  • map (dictionary, associative array)
  • unordered (key,value) pairs
  • no duplicate keys
  • map from key to value
  • also sorted or ordered map (by key)
  • Map and SortedMap

24
Interfaces
  • design guideline Maximize the Uniformity of
    Common Aspects of Related Classes/Interfaces

E
Iterable
E
K,V
Collection
Map
E
E
K,V
Set
List
SortedMap
E
SortedSet
25
Interfaces
  • Iterable
  • iterator
  • Collection
  • common interface for non-map collections
  • equals
  • Set
  • modifies semantics no duplicates
  • SortedSet
  • List
  • modified semantics ordered
  • Map
  • not Collection involves keys, no duplicate keys
  • views
  • entry set (key-value pairs)
  • key set
  • value collection
  • keys
  • equals
  • SortedMap

26
CollectionltEgt interface
27
SetltEgt interface
28
ListltEgt interface
29
ListltEgt interface (cont.)
30
SortedSetltEgt interface
31
MapltK,Vgt interface
32
SortedMapltK,Vgt interface
33
Concrete Classes
  • Important issues
  • bounded versus unbounded
  • time and space complexity of various operations
  • interchangeability
  • concrete collection classes in Java
  • all unbounded

34
SetltEgt
  • HashSetltEgt
  • hash table (efficient in insertion and membership
    checking)
  • unpredictable iteration order
  • requires equals and hashCode
  • LinkedHashSetltEgt (similar to HashSet)
  • hash table with linked elements
  • predictable iteration order (usually insertion
    order)
  • requires equals and hashCode
  • TreeSetltEgt
  • red-black tree (a form of balanced binary trees)
  • SortedSet
  • requires ordering (Comparable or Comparator)
  • iteration by natural order
  • less efficient in insertion and membership
    checking
  • Use HashSet unless a sorted set or a predictable
    iteration order is required.

35
ListltEgt
  • ArrayListltEgt
  • array extended when necessary
  • large enough to hold predicted number of elements
  • often, a large portion of the array is unused
  • large cost to increase size (copying)
  • more efficient access
  • VectorltEgt
  • same implementation as the ArrayList
  • supports additional legacy methods
  • thread-safe
  • significant overhead in performance
  • LinkedListltEgt
  • doubly-linked list
  • no additional penalty as list grows
  • less efficient access
  • LinkedList for volatile lists, ArrayList for
    stable lists

36
MapltK,Vgt
  • HashMapltK,Vgt
  • hash table (efficient in insertion and membership
    checking)
  • unpredictable iteration order
  • requires equals and hashCode
  • HashtableltK,Vgt
  • same implementation as the HashMap
  • supports additional legacy methods
  • thread-safe
  • significant overhead in performance
  • LinkedHashMapltK,Vgt
  • hash table with linked elements
  • predictable iteration order (usually insertion
    order)
  • requires equals and hashCode

37
  • IdentityHashMapltK,Vgt (similar to HashMap)
  • key equality based on (identity)
  • requires hashCode
  • TreeMapltK,Vgt
  • red-black tree
  • SortedMap
  • iteration order by key
  • requires ordering for keys (Comparable or
    Comparator)
  • less efficient in insertion and membership
    checking
  • Use TreeMap if a sorted map is required otherwise
    use HashMap or IdentityHashMap.

38
Abstract Collection Classes
  • for building new collections
  • AbstractCollectionltEgt
  • bag
  • must implement iterator and size
  • AbstractSetltEgt
  • must implement add
  • AbstractListltEgt
  • optimized for random access
  • must implement get and size
  • AbstractSequentialListltEgt
  • optimized for sequential access
  • must implement listIterator and size
  • AbstractMapltK,Vgt
  • must implement entries
Write a Comment
User Comments (0)
About PowerShow.com