Essential Java Classes - PowerPoint PPT Presentation

1 / 58
About This Presentation
Title:

Essential Java Classes

Description:

Title: Lecture 4. Essential java Classes Author: bruce Last modified by: chengchia Created Date: 11/4/2000 2:11:43 PM Document presentation format – PowerPoint PPT presentation

Number of Views:207
Avg rating:3.0/5.0
Slides: 59
Provided by: bruc1179
Category:

less

Transcript and Presenter's Notes

Title: Essential Java Classes


1
Essential Java Classes
  • Cheng-Chia Chen

2
Contents
  1. Java.lang.
  2. Wrapper classes for primitive types
  3. String, StringBuffer, StringBuilder
  4. Math
  5. Thread
  6. System
  7. Process
  8. Runtime
  9. Java.util.
  10. java collection classes
  11. other classes

3
The java.lang package
4
The java.lang package
  • loc http//java.sun.com/j2se/1.5/docs/api/java/la
    ng/package-summary.html
  • contains classes and interfaces that are
    essential to the Java language.
  • String processing String, StringBuffer,
    StringBuilder
  • Classes that encapsulate the primitive data types
    in Java.
  • Boolean, Character, Void
  • Number ? Byte, Short, Integer, Long, Float,
    Double
  • Mathematical operations Math, StrictMath
  • Thread supports
  • Thread, ThreadGroup, ThreadLocal?InheritableThread
    Local
  • 4 interfaces
  • Clonable, Runnable, Comparable, CharSequence

5
The java.lang package (continued)
  • Platform or OS-related classes
  • Runtime, Process, System
  • Classes that represent objects, classes,
    packages,
  • Object, Class, Package, Compiler, ClassLoader
  • Security-related classes
  • SecurityManager, RuntimePermission
  • Errors and Exceptions Throwable ?
  • Error ? ThreadDeath
  • ?VirtualMachineError ?
  • ? LinkageError ?
  • Exception ? RuntimeException (? ),
    ClassNotFoundException, CloneNotSupportedException
    , IllegalAccessException,InstantiationException,
    InterruptedException,NoSuchFieldException,NoSuchMe
    thodException

6
The String and StringBuffer classes
  • Differences String instances are immutable
    (i.e., cannot be modified in place) while
    StringBuffer instances are not.
  • The String class
  • public final , implements Serializable,
    Comparable, CharSequence.
  • Constructors (non-strings to strings)
  • public String() // empty stirng
  • // byte array ? string
  • public String(byte ,int offset, int length
    ,String charsetName )
  • // charsetName given by the
    file.encoding property
  • // charsetName MS950 or
    Big5 for zh_TW
  • public String(char , offset, length ) //
    char array ? string
  • public String(String) // create a new copy
  • public String(StringBuffer) //
    StringBuffer2String

7
The java.lang.String class
  • Class Methods Converting values of other types
    to strings
  • // new String(char, offset, count )
  • public static String copyValueOf(char , int
    offset, int count )
  • // copyValueOf(char offset, count )
  • public static String valueOf(char , int
    offset,int count )
  • public static String valueOf(Type x)
  • // where Type is boolean, char, int, long, float,
    double or Object.
  • // ex String.valueOf(false) return false
  • // String.valueOf(null) return null
  • // String.valueOf(Object obj) returns
    obj.toString()

8
The java.lang.String class
  • Instance methods
  • // Comparisons
  • public int compareTo(String Object)
  • public boolean equals(Object)
  • public boolean equalsIgnoreCase(String)
  • public boolean startsWith(String ,int from )
  • public boolean endsWith(String suffix)
  • public boolean regionMatches(boolean
    ignoreCase,
  • int toffset, String
    other, int ooffset, int len)
  • // return false if substring (tooffset, len )
    or (ooffset, len)
  • // does not exist.

9
The java.lang.String class
  • // find substring
  • public char charAt(int index) // impl. of
    CharSequence
  • public CharSequence subsequence(int beginIndex ,
    int endIndex )
  • public String substring(int beginIndex , int
    endIndex )
  • // String ? byte/char array
  • public byte getBytes(String charsetName)
  • public void getChars(int srcBegin, int srcEnd,
    char dst, int dstBegin)
  • public char toCharArray()
  • // find position of substring/char
  • public int indexOf(int ch , int from)
  • public int indexOf(String str ,int from)
  • public int lastIndexOf(int ch ,int from)
  • // searching backward starting at the
    specified index
  • public int lastIndexOf(String str , int
    fromIndex)

10
The java.lang.String class
  • Immutable String modification
  • public String concat(String str), replace(char
    oldChar, char newChar)
  • public String toLowerCase(java.util.Locale)
  • public String toUpperCase(Locale) // def is
    Locale.getDefault()
  • Auxiliary methods
  • public int hashCode() // if s s0 s1
    sn-1 gt returns
  • // s0x
    31n-1 s1x 31n-2 sn-1
  • public native String intern() // if there is an
    instance s in the system string pool equal to
    this gt return s, o/w put this to the pool and
    return this.
  • public int length() // impl. of
    CharSequence
  • public String toString() // return this note
    s.toString() s
  • public String trim() // remove all whitespaces
    (as well as all control char lt ( \u0021)) from
    both ends

11
The java.lang.String class
  • public String split(String regex , int limit)
  • since jdk 1.4
  • Pattern.compile(regex).split(this, limit)
  • See the package java.util.regex for details
  • Ex1
  • this "booooandfoo", gt
  • this.split(, 2) yields boooo, and
  • this.split(, 5) yields boooo, and, foo,
  • Meaning of limit
  • negative gt return all splits
  • 0 (default)gt tailing empty string not returned
  • positive gt only the first nth splits return
  • Ex2 this "booooandfoo
  • gt this.split(oo, 0 ) yields b,, andf

12
The java.lang.StringBuffer and StrignBuilder class
  • public final class StringBuffer, StringBuilder
    implements Serializable, CharSequence
  • Description
  • implements a mutable sequence of characters.
  • like a String, but can be modified length and
    content can be changed through method calls.
  • thread safe (methods are synchronized) ?
    StrignBuffer
  • Save but less efficient
  • not thread-safe (mothods not synchronized) ?
    StringBuilder
  • Efficient but danger
  • used by the compiler to implement the binary
    string concatenation operator .
  • x "a" 4 "c is compiled to the
    equivalent of
  • x new StringBuffer().append("a").append(4).app
    end("c").toString()
  • main (overloaded) methods insert(), append()
  • has an internal buffer overflow gt automatically
    made larger (twice)

13
The java.lang.StringBuffer class
  • // Constructors
  • public StringBuffer() // initial buffer size
    this.capacity() 16
  • public StringBuffer(int length)
  • public StringBuffer(String str)
  • // Instance Methods
  • public int length()
  • public int capacity() // return buffer size
  • public synchronized void ensureCapacity(int
    minCap)
  • // if buffer size lt minCap gt
  • // change buffer size to max(minCapacity,
    2 x this.capacity())
  • public synchronized StringBuffer
    append(ltTypegt)
  • // where ltTypegt can be any primitive type ,
    String or Object
  • public synchronized StringBuffer append(char
    str, int offset, int len)
  • public synchronized StringBuffer insert(int
    offset, ltTypegt)

14
The java.lang.StringBuffer class
  • // instance methods
  • public synchronized char charAt(int index)
  • public synchronized void getChars(int srcBegin,
    int srcEnd,
  • char dst, int
    dstBegin)
  • public synchronized StringBuffer reverse()
  • public synchronized void setCharAt(int index,
    char ch)
  • public synchronized void setLength(int
    newLength)
  • // newLength lt this.length() gt truncate
  • // newLength gt this.length() gt append null
    chars \u0000.
  • public String toString()

15
The java.util.StringTokenizer class
  • provides support for parsing a string into a
    sequence of words, or tokens, that are separated
    by some set of delimiter characters.
  • can use java.util.Scanner as well, which is more
    powerful and handy and can fetch primitive data
    as well as String from the input.
  • Example
  • StringTokenizer s new StringTokenizer("This
    is it")
  • while (s.hasMoreTokens())
  • System.out.println(s.nextToken())
  • Default delimiters are whitespaces space, tab
    ('\t'), carriage return ('\r'), and newline
    ('\n').
  • StringTokenizer s new StringTokenizer(fruits
    apple, banana.",
  • ,. ) // output gt fruits apple banana

16
Scanner Examples
  • Ex1
  • String input "1 fish 2 fish red fish blue
    fish"
  • Scanner s new Scanner(input).useDelimiter("\\sf
    ish\\s")
  • out.println(s.nextInt()) // 1
  • out.println(s.nextInt()) // 2
  • out.println(s.next()) // red
  • out.println(s.next()) // blue
  • s.close()
  • Ex2 // white space is the default delimiter
  • Scanner sc new Scanner(new File("myNumbers"))
  • while (sc.hasNextLong()) long aLong
    sc.nextLong()

17
Wrapper classes for primitive types
  • Number ? Byte, Short, Integer, Long, Float,
    Double
  • Boolean, Character, Void
  • Descriptions
  • are wrapper classes for byte, short, int, long,
    float, double, boolean, char and void,
    respectively.
  • each class contains a single field storing a
    value of the wrapped type. useful when we must or
    want to treat a value of primitive type as an
    object.
  • provides methods for conversion between each type
    and String.
  • provides useful methods and related constants for
    each type.
  • eg MAX_VALUE, MIN_VALUE, TYPE, etc.

18
The java.lang.Number class
  • public abstract class java.lang.Number
  • implements
    java.io.Serializable
  • // Instance Methods
  • this ? value of various primitive numeric types
  • byte byteValue() return (byte)
    this.intValue()
  • short shortValue() return (short)
    this.intValue()
  • // implemeted by subclasses
  • abstract int intValue()
  • abstract long longValue()
  • abstract float floatValue()
  • abstract double doubleValue()

19
naming conventions
  • Let ltTypegt be a wrapper class of primitive type
    lttypegt
  • Then the following static methods are provided in
    class ltTypegt
  • String ? ltTypegt
  • ltTypegt decode(String s) // radix info in s
    0x12 1218022
  • ltTypegt valueOf(String s ,int radix) // radix
    info not in s.
  • String ? lttypegt
  • lttypegt parselttypegt(String s ,int) // s ? a
    value of type lttypegt
  • lttypegt ? String String toString(lttypegt , int
    radix) // r in 2,36
  • ltTypegt ? String (instance method)
    toString() //decimal assumed
  • Ex if ltTypegt Integer gt lttypegt int, and
    provided classes methods include
  • Integer decode(String) Integer
    valueOf(String, int)
  • int parseInt(String, int) String
    toString(int ,int radix)

20
Summary of conversion methods among primitive
types, String and their Wrapper classes
----- class methods ----- instance method
----- constructor
toString() String.valueOf(.)
Type1.decode(String) Type1.valueOf(s
,radix) new Type1(s ,radix)
String
t2
Type1
t2Value()
new Type1(t1)
Type1.parseT1(s ,r)
t1
  • Note
  • t1 int gt
  • Type1 Integer
  • T1 Int

Type1.toString(t1 , r) Type1.toBinaryString() Ty
pe1.toOctalString() Type1.toHexString()
For integer types only
21
Converting methods among int, String and Integer
----- class methods ----- instance method
----- constructor
toString() String.valueOf(.)
Integer.decode(String) Integer.valueOf(s
,radix) new Integer(s ,radix)
long
Integer
String
longValue()
intValue()
new Integer(int)
Integer.parseInteger(s ,r)
int
  • Note
  • t1 int gt
  • Type1 Integer
  • T1 Int

Integer.toString(t1 , r) Integer.toBinaryString(
) Integer.toOctalString() Integer.toHexString()
For non-floating types only
22
The java.lang.Integer class
  • public final class Integer extends Number

  • implementsComparable
  • Description
  • wrap an int value into an object.
  • An object of type Integer contains a single field
    whose type is int.
  • provides several methods for int ?String and
    String ?int,
  • as well as other constants and methods useful
    when dealing with an int.

23
Integer class summary
  • // Constants
  • public static final int MAX_VALUE, MIN_VALUE
  • public final static Class TYPE // representing
    primitive int
  • // Constructors Integer(int),
    Integer(String)
  • // Class Methods
  • String?int parseInt(String s ,int radix)
  • String?Integer
  • decode(String nm) // decode(-0x12) ? -18
  • valueOf(String s , int radix) // equ. to
    new Integer(parseInt(s, radix))
  • String ?Integer via system property
  • getInteger(String nm , (int Integer ) val
    ) // val is the default.
  • // decode(System.getProperty(nm
    ,val))
  • int ? String toBinaryString(int),toHexString(in
    t), toOctalString(int),
  • toString(int i , int radix )
  • // cf Integer.toHexString(-10) fffffff6
    toString(-10,16) -a

24
The java.lang.Integer class
  • // Instance Methods
  • // implements Number methods
  • this ? value of primitive types
  • pubic byte byteValue() public short
    shortValue()
  • public int intValue() public long
    longValue()
  • public float floatValue() public
    double doubleValue()
  • // implements or overrides Object methods
  • this? String toString() //
    Integer.toString(this.intValue())
  • comparison
  • boolean equals(Object obj) // true iff
    obj.intvalue() this.intValue())
  • int compareTo(Object Integer)
  • hash int hashCode() //
    this.intvalue()

25
the java.lang.Long class summary
  • // Constants
  • public static final int MAX_VALUE, MIN_VALUE
  • public final static Class TYPE
  • // Constructors
  • Long(long), Long(String)
  • // Class Methods // parseLong(12, 16) ?18
  • String?long parseLong(String s ,int radix)
    //parseLong(0x12) ?err
  • String?Long decode(String nm) //
    decode(-0x12) ? -18
  • valueOf(String s , int radix) // equ. to
    new Long(parseLong(s, radix))
  • String ?Long via system property getLong(String
    nm , (int Long ) val ) // System
    property named nm val is the default.
  • // Long.decode(System.getPro
    perty(nm, val))
  • long? String toBinaryString(long),
    toHexString(long),
  • toOctalString(long),
    toString(long ,int)

26
The java.lang.Long class
  • // Instance Methods
  • // implements Number methods
  • this ? value of various numeric primitive types
  • pubic byte byteValue() public short
    shortValue()
  • public int intValue() public long
    longValue()
  • public float floatValue() public
    double doubleValue()
  • // implements or overrides Object methods
  • this? String toString() //
    Long.toString(this.intValue())
  • comparison
  • boolean equals(Object obj) // true iff
    obj.intvalue() this.intValue())
  • int compareTo(Object Long)
  • hash int hashCode() //
    this.intvalue()

27
The java.lang.Byte class
  • public final class java.lang.Byte extends
    java.lang.Number
  • // Constants
  • public static final byte MAX_VALUE 127,
    MIN_VALUE -128
  • public static final Class TYPE
  • Constructors public Byte(byte) public
    Byte(String)
  • // Class Methods String?Byte, byte byte
    ?String
  • public static Byte decode(String nm)
  • public static Byte valueOf(String s , int
    radix) // valueOf(0x12) ?err
  • public static byte parseByte(String s , int
    radix)
  • public static String toString(byte b) // radix
    is 10
  • // Instance Methods same as Integer.
  • // implements Number methods omitted here
  • // implemetns or override Object methods
  • boolean equals(Object obj) public int
    hashCode()
  • String toString()
    compareTo(Byte Object)

28
The java.lang.Short class
  • public final class java.lang.Byte extends
    java.lang.Number
  • // Constants
  • public static final short MAX_VALUE 32767,
    MIN_VALUE -32768
  • public static final Class TYPE
  • Constructors public Short(short) public
    Short(String)
  • // Class Methods String?Short, short short
    ?String
  • public static Short decode(String nm)
  • public static Short valueOf(String s , int
    radix) // valueOf(0x12) ?err
  • public static short parseByte(String s , int
    radix)
  • public static String toString(short b) // radix
    is 10
  • // Instance Methods same as Integer.
  • // implements Number methods omitted here
  • // implemetns or override Object methods
  • boolean equals(Object obj) public int
    hashCode()
  • String toString()
    compareTo(Short Object)

29
the java.lang.Float class
  • // Constants
  • public static final int MAX_VALUE, MIN_VALUE,
    NEGATIVE_INFINITY, POSITIVE_INFINITY, NaN
  • public final static Class TYPE
  • // Constructors
  • Float( float double String)
  • // Class Methods
  • String?float parseFloat(String)
  • String?Float valueOf(String)
  • float? String toString(float)
  • float ? int floatToIntBits(float),
    floatToRawIntBits(float)
  • int ?float intBitsToFloat (int)
  • isNan(float)
  • isInfinity(float)

30
The java.lang.Float class
  • // Instance Methods
  • isNan(), isInfinity()
  • // implements Number methods
  • this ? value of various numeric primitive types
  • pubic byte byteValue() public short
    shortValue()
  • public int intValue() public long
    longValue()
  • public float floatValue() public
    double doubleValue()
  • // implements or overrides Object methods
  • this? String toString() //
    Long.toString(this.intValue())
  • comparison
  • boolean equals(Object obj) // true iff
    obj.intvalue() this.intValue())
  • int compareTo(Object Float)
  • hash int hashCode() //
    this.intvalue()

31
IEEE 754 float-point single precision layout
  • 0x7f800000 gt positive infinity.
  • 0xff800000 gt negative infinity.
  • 0x7f800001 0x7fffffff or 0xff8000010xffffffff
    gt NaN.
  • Java use 0x7fc00000 as the canonical value of
    NaN.
  • Distinct values of NaN are only accessible by
    use of the Float.floatToRawIntBits(float)
  • In all other cases, let s, e, and m be three
    values that can be computed from the argument
  • int s ((bits gtgt 31) 0) ? 1 -1
  • int e ((bits gtgt 23) 0xff) // s bit is
    ignored by mask of 0xff
  • int m (e 0) ? (bits 0x7fffff) ltlt 1
    (bits 0x7fffff) 0x800000
  • the floating-point result is s m 2 e-150.

32
IEEE 754 float-point single precision layout
  • value is determined as follows
  • 0. s (b31 0 ? 1 -1)
  • 255gt e gt 0 gt value s x (1.m)2 x 2 e 127 s
    x (1m) x 2 e - 150
  • e 0 gt value s x (b22.b21---b00)2 x 2 e-127
    s x (m 0)2 x 2 e - 127-23
  • e255 m 0 gt value ( s 0 ? Infinity
    -Infinity)
  • e 255 m ! 0 gt value NaN canonical NaN
    0181022

33
the java.lang.Double class
  • // Constants
  • public static final double MAX_VALUE, MIN_VALUE,
    NEGATIVE_INFINITY, POSITIVE_INFINITY, NaN
  • public final static Class TYPE
  • // Constructors
  • Double( double String)
  • // Class Methods
  • String?double parseDouble(String)
  • String?Double valueOf(String)
  • double? String toString(double)
  • double ? long doubleToLongBits(double),
  • doubleToRawLongBits(
    double)
  • long ?double longBitsToDouble (long)
  • isNan(long) isInfinity(long)

34
The java.lang.Float class
  • // Instance Methods
  • isNan(), isInfinity()
  • // implements Number methods
  • this ? value of various numeric primitive types
  • pubic byte byteValue() public short
    shortValue()
  • public int intValue() public long
    longValue()
  • public float floatValue() public
    double doubleValue()
  • // implements or overrides Object methods
  • this? String toString() //
    Long.toString(this.intValue())
  • comparison
  • boolean equals(Object obj) // true iff
    obj.intvalue() this.intValue())
  • int compareTo(Object Double)
  • hash int hashCode() //
    this.intvalue()

35
IEEE 754 float-point double precision layout
  • 0x7ff0000000000000L gt positive infinity.
  • 0xfff0000000000000L gt negative infinity.
  • 0x7ff0000000000001L 0x7fffffffffffffffLor
    0xfff0000000000001L
  • 0xffffffffffffffffLgt NaN.
  • Java use 0x7ff8000000000000L as the canonical
    value of NaN.
  • Distinct values of NaN are only accessible by
    use of the Double.doubleToRawLongBits(doubl
    e)
  • In all other cases, let s, e, and m be three
    values that can be computed from the argument
  • int s ((bits gtgt 63) 0) ? 1 -1
  • int e ((bits gtgt 52) 0xff)
  • int m (e 0) ? (bits 0xfffffffffffffL) ltlt
    1 (bits 0xfffffffffffffL)
    0x10000000000000L
  • the floating-point result is s m 2 e-1075.

36
The java.lang.Character class
  • public final class java.lang.Character implements
    java.io.Serializable
  • // Constants
  • // byte constants Names for various UNICODE
    character categories
  • COMBINING_SPACING_MARK, CONNECTOR_PUNCTUATION
    CONTROL CURRENCY_SYMBOL
    DASH_PUNCTUATION DECIMAL_DIGIT_NUMBE
    R ENCLOSING_MARK
    END_PUNCTUATION FORMAT
    LETTER_NUMBER LINE_SEPARATOR
    LOWERCASE_LETTER MATH_SYMBOL
    MODIFIER_LETTER MODIFIER_SYMBOL
    NON_SPACING_MARK OTHER_LETTER
    OTHER_NUMBER
    OTHER_PUNCTUATION OTHER_SYMBOL
    PARAGRAPH_SEPARATOR PRIVATE_USE
    SPACE_SEPARATOR
    START_PUNCTUATION SURROGATE
    TITLECASE_LETTER UNASSIGNED
    UPPERCASE_LETTER
  • public final static Class TYPE
  • public final static int MAX_RADIX
  • public final static int MIN_RADIX
  • public final static char MAX_VALUE
  • public final static char MIN_VALUE

37
The java.lang.Character class
  • Constructors public Character(char value)
  • Class Methods
  • int digit(char ch, int radix)
    char forDigit(int digit, int radix)
  • // digit(a, 16) 10 // forDigit(11, 16)
    b
  • int getNumericValue(char ch) char
    toLowerCase(char ch)
  • char toTitleCase(char ch) char
    toUpperCase(char ch)
  • // Character category checking
  • public static int getType(char ch) // return
    category ch belongs to
  • isDefined(char ch) isDigit(char ch)
    isIdentifierIgnorable(char ch)
  • isISOControl(char ch) isJavaIdentifierPar
    t(char ch)
  • isJavaIdentifierStart(char ch)
  • isLetter(char ch) isLetterOrDigit(char ch)
  • isLowerCase(char ch) isSpaceChar(char ch)
  • isTitleCase(char ch) isUnicodeIdentifierPart(char
    ch) // New in 1.1
  • isUnicodeIdentifierStart(char ch)
    isUpperCase(char ch) isWhitespace(char ch)
  • // Instance Methods
  • public char charValue() equals(Object obj)
    hashCode() String toString()

38
The java.lang.Math classes
  • public final class java.lang.Math
  • // Constants
  • public static final double E, PI
  • // Class Methods
  • abs(int long float double ) ceil(double
    a) floor(double a)
  • double sqrt(double a) int round(float a)
    long round(double a)
  • max(lttypegt,lttypegt) min(lttypegt,lttypegt) //
    lttypegt int, long, float or double
  • // double trigonometric functions
  • asin(double) acos(double) atan(double )
    atan2(double a, double b)
  • sin(double a) cos(double) tan(double)
  • // exponential functions
  • pow(double a, double b) exp(double)
    log(double a) // base e
  • IEEEremainder(double f1, double f2)
  • double random() // 0.0 1.0
  • double rint(double a) // math integer closest
    to a

39
Some java collection classes
  • utility classes that help you to manage a
    collection of objects.
  • java.util.Vector
  • represents a dynamic array of objects.
  • java.util.Stack
  • represents a dynamic stack of objects.
  • java.util.Dictionary
  • abstract class that manages a collection of
    objects by associating a key with each object.
  • java.util.Hashtable
  • a subclass of java.util.Dictionary that
    implements a specific algorithm to associate
    keys with objects.
  • java.util.Properties
  • a subclass of Hashtable where all keys and values
    are String objects.
  • java.util.Enumeration (deprecated)
  • interface supporting sequential access to a set
    of elements.

40
The java.util.Vector class
  • implements a variable-length array that can hold
    any kind of object.
  • Constructors
  • Vector( int initCapacity , int
    incrCapacity) // default 10, 0(double)
  • Ex Vector v new Vector(100)
  • VectorltPersongt gv new VectorltPersongt()
  • append elements
  • v.addElement("abc") v.addElement( new int2
    1,2 )
  • v.addElement(123) // error since 123 is not an
    Object instance
  • // fine after
    jdk 1.5 due to autoboxing
  • insert element but gv.add(abc) (x),
    gv.add(new Person()) (0).
  • v.insertElementAt(123, 2) or v.add(2, 123
    ).
  • vector size v.size()
  • Retrieve elements
  • firstElement() lastElement(), elementAt(int),
    get(int) // all return Object
  • Enumeration elements() Iterator iterator()

41
  • set/remove element
  • Object setElementAt(Object, int), Object
    set(int, Object)
  • void removeElementAt(int), remove(int)
  • // removes the first element in the Vector that
    refers to the given
  • boolean removeElement(Object) , remove (Object)
  • removeRange(int from,int to)
  • removeAllElements().
  • Vector to array
  • toArray( Object a ) // return an array
    whose component type is that of a.
  • check if an object is in the vector
  • boolean contains(Object),
  • int indexOf(Object), int lastIndexOf(Object) //
    return 1 if not found

42
The java.util.Stack class
  • a subclass of Vector implementing a
    last-in-first-out (LIFO) object stack.
  • Constructor
  • Stack() // create an empty stack
  • instance methods
  • boolean empty() // returns true if and only if
    the stack is empty.
  • Object push(Object) // same as
    addElement(Object)
  • Object pop() throws EmptyStackException.
  • Object peek() throws EmptyStackException.
  • // throws an EmptyStackException if empty()

43
The Hashtable and Dictionary classes in java.util
  • Dictionary ( implements Map )
  • an abstract class that defines methods for
    associating key objects with value objects.
  • Given a key, an instance of Dictionary is able to
    return its associated value.
  • Hashtable
  • a concrete subclass of Dictionary that uses a
    data structure called a hashtable and a technique
    called chained hashing to allow values associated
    with keys to be fetched with minimal searching.

44
The Dictionary Class
  • constructor Dictionary()
  • // Instance Methods
  • public abstract Enumeration elements() //
    return values
  • public abstract Enumeration keys() // return
    keys
  • public abstract Object get(Object key)
  • public abstract Object put(Object key, Object
    value)
  • public abstract Object remove(Object key)
  • public abstract int size()
  • public abstract boolean isEmpty()

key value
Java SUN

C MOSFT
45
The hashtable class
  • public class java.util.Hashtable extends
    java.util.Dictionary implements
    java.lang.Cloneable, java.io.Serializable
  • Constructors
  • public Hashtable( int initialCapacity ,
    float loadFactor )
  • // Instance Methods 1. Dictionary
    implementation
  • get(Object) put(key, value) keys()
    elements()
  • isEmpty() size() remove(Object)
  • // 2. special synchronized methods
  • void clear() Object clone()
  • boolean contains(Object value)
    containsKey(Object key)
  • String toString()
  • // Protected Instance Methods
  • protected void rehash()

46
The java.util.Properties class
  • Special hashtable whose key and value must be
    strings and support persistence.
  • public class java.util.Properties extends
    java.util.Hashtable
  • // Variables
  • protected Properties defaults // parent
    properties
  • // Constructors
  • public Properties( Properties defaults )
  • // Instance Methods
  • public String getProperty(String key , String
    defaultValue )
  • pubilc String setProperty(String key, String
    val)
  • public Enumeration propertyNames()
  • public void list( PrintStream PrintWriter)
    // list this to out
  • public synchronized void load(InputStream in)
    // load from in
  • public synchronized void store(OutputStream out,
    String header)

47
Accessing the Environment
  • java.lang.System and java.lang.Runtime classes
  • provide a variety of methods that allow a Java
    program to access information and resources for
    the environment in which it is running.
  • This environment includes the Java virtual
    machine (Runtime) and the native operating
    system (System).
  • System
  • interface to OS
  • contains several useful class fields and methods.
  • standard input, standard output, and error
    output streams
  • access to externally defined "properties"
  • a means of loading files and libraries and
  • a utility method for quickly copying a portion
    of an array.

48
The System class
  • public final class java.lang.System extends
    java.lang.Object
  • // Constants
  • public static final PrintStream err, out //
    system error and system output
  • public static final InputSteram in // system
    input
  • // Class Methods
  • void setOut(PrintStream) setIn(InputStream)
    setErr(PrintStream)
  • // note setOut(out1) is not the same as
    System.out out1 (illegal operation!)
  • Properties getProperties()
  • void setProperties(Properties props)
    // set system properties
  • String getProperty(String key , String
    default)
  • arraycopy(Object src, int srcOffset, Object dst,
    int dstOffset, int length)
  • long currentTimeMillis()
  • void exit(int status) void gc()
  • public static void load(String filename) //
    same purpose as loadLibrary
  • public static void loadLibrary(String libname)

49
Some Standard system properties
  • file.encoding, file.encoding.pkg
  • The character encoding for the default locale
  • The package that contains the converters that
    handle converting between local encodings and
    Unicode
  • file.separator, line.separator,
    path.separator
  • The platform-dependent file separator (e.g., "/"
    on UNIX, "\" for Windows)
  • The platform-dependent line separator (e.g., "\n"
    on UNIX, "\r\n" for Windows)
  • The platform-dependent path separator (e.g., ""
    on UNIX, " for Windows)
  • java.class.path
  • The value of the CLASSPATH environment variable
  • java.class.version
  • The version of the Java API
  • java.compiler
  • The just-in-time compiler to use, if any.
  • java.home
  • The directory in which Java is installed

50
Some Standard system properties
  • java.version, java.vendor, java.vendor.url
  • The version of the Java interpreter
  • vendor-specific string
  • vendor URL
  • os.name, os.arch, os.version
  • The name, architecture and version of the
    operating system
  • user.dir, user.home, user.name
  • The current working directory when the properties
    were initialized
  • The home directory of the current user
  • The username of the current user
  • user.language, user.region, user.timezone
  • The two-letter language code of the default
    locale zh
  • The two-letter country code of the default locale
    TW
  • The default time zone empty

51
The Runtime class
  • public class java.lang.Runtime extends
    java.lang.Object
  • // Class Methods interface to JVM
  • public static Runtime getRuntime()
  • // Instance Methods
  • public Process exec(String command , String
    envp ,File workingdir)
  • public Process exec(String cmdarray , String
    envp ,File workingdir)
  • public native long freeMemory() // in the
    system
  • public native long totalMemory() // in JVM
  • public native void gc()
  • public void exit(int status)
  • public synchronized void load(String filename)
    // load non-class code file
  • public synchronized void loadLibrary(String
    libname) //load system code
  • public native void runFinalization()
  • public native void traceInstructions(boolean on)
    // enable/diable trace
  • public native void traceMethodCalls(boolean on)

52
The java.lang.Process class
  • public abstract class Process extends Object
  • returned by Runtime.exec()
  • Method Summary
  • abstract void destroy()
  • Kills the subprocess. Process p
    Runtime.getRuntime().exec(test.exe)
    p.destroy()
  • abstract int exitValue()
  • Returns the exit value for the subprocess.
  • abstract InputStream getErrorStream()
  • Gets the error stream of the subprocess.
  • abstract InputStream getInputStream()
  • Gets the output stream of the subprocess as an
    input stream of the current process.
  • abstract OutputStream getOutputStream()
  • Gets the input stream of the subprocess as my
    outputStream.
  • abstract int waitFor() // wait until
    termination
  • causes the current thread to wait, if necessary,
    until the process represented by this
    Process object has terminated.

53
The java.lang.Class class
  • Instances represent classes and interfaces in a
    running Java application. including
  • Every array All arrays with the same element
    type and number of dimensions share a same Class
    instance.
  • The primitive Java types (boolean, byte, char,
    short, int, long, float, and double), and the
    keyword void are also represented as Class
    objects.
  • Different ways to get a Class object for a
    particular data type
  • o.getClass() // o is any Object instance
  • t.class // t is any type
  • ex Class s String.class Class i
    int.class
  • Class v java.util.Vector.class
  • Class v Class.forName("java.util.Vector")

54
The java.lang.Class class
  • public final class Class extends Object
    implements java.io.Serializable
  • // Class Methods
  • public static native Class forName(String
    className)
  • // Instance Methods
  • Package getPackage()
  • Class getDeclaringClass() // return the class
    of which this is a member
  • String getName() // class name
  • int getModifiers()
  • Class getSuperclass() Class
    getInterfaces()
  • Object newInstance()
  • ClassLoader getClassLoader()
  • URL getResource(String name)
  • InputStream getResourceAsStream(String name)
  • boolean isInstance(Object obj)
  • boolean isArray() isInterface()
    isPrimitive() String toString()

55
The java.lang.Class class
  • public Constructor getConstructors(),
    getDeclaredConstructors()
  • public Constructor getConstructor(Class
    parameterTypes)
  • public Constructor getDeclaredConstructor(Class
    parameterTypes)
  • Class getClasses() // return all public
    even inherited member classes
  • // all non-inherited (even privated)
    members classes
  • Class getDeclaredClasses()
  • Class getComponentType() // return component
    class of this array
  • Field getFields(), getDeclaredFields()
  • Field getField(String name) getDeclaredField(Str
    ing name)
  • Method getMethods()
    getDeclaredMethods()
  • Method getMethod(String name, Class
    parameterTypes)
  • Method getDeclaredMethod(String, Class)
  • Object getSigners() boolean
    isAssignableFrom(Class cls)

56
The java.lang.Package class
  • contain version information about the
    implementation and specification of a Java
    package.
  • information is retrieved and made available by
    the classloader that loaded the class(es).
  • Typically, it is stored in the manifest that is
    distributed with the classes.
  • may contain the specification title, version
    number, and vendor strings if the package
    implement a particular specification.
  • An application can ask if the package is
    compatible with a particular version.

57
The java.lang.Package Method Summary
  • String getImplementationTitle()
  • Return the title of this package.
  • String getImplementationVendor()
  • Returns the name of the organization, vendor or
    company that provided this
    implementation.
  • String getImplementationVersion()
  • Return the version of this implementation.
  • String getName()
  • Return the name of this package.
  • static Package getPackage(String name)
  • Find a package by name in the callers
    classloader.
  • static Package getPackages()
  • Get all the packages currently known for the
    caller's class loader.
  • String getSpecificationTitle()
  • Return the title of the specification that this
    package implements.

58
The java.lang.Package Method Summary
  • String getSpecificationVendor()
  • Return the name of the organization, vendor,
    or company that owns and maintains
    the specification of the classes that implement
    this package.
  • String getSpecificationVersion()
  • Returns the version number of the specification
    that this package implements.
  • int hashCode()
  • Return the hashcode computed from the
    package name.
  • boolean isCompatibleWith(String desired)
  • Compare this package's specification
    version with a desired version.
  • boolean isSealed()
  • Returns true if this package is
    sealed.
  • boolean isSealed(URL url)
  • Returns true if this package is sealed with
    respect to the specified code
    source url.
  • String toString()
  • Returns the string representation of this
    Package.
Write a Comment
User Comments (0)
About PowerShow.com