Programming in Java [7-1] Java Tool Packages (1) Lecture7.

70
Programming in Java [7-1] Java Tool Packages(1 ) Lecture7

Transcript of Programming in Java [7-1] Java Tool Packages (1) Lecture7.

Page 1: Programming in Java [7-1] Java Tool Packages (1) Lecture7.

Programming in Java [7-1]

Java Tool Packages(

1)

Lecture7

Page 2: Programming in Java [7-1] Java Tool Packages (1) Lecture7.

Programming in Java [7-2]

Objectives

• Java Array

• Java Tool PackagesJava.lang package

• Object 、 Wrapper Classes for Primitive Types 、 Math 、 String 、 System 、 Runtime 、 Thread 、 Class 、 Exception 、 Process

java.util package

• data-structure classes 、 Random 、 StringTokenizer 、 Observable

• Data Structure and Algorithm

Page 3: Programming in Java [7-1] Java Tool Packages (1) Lecture7.

Programming in Java [7-3]

• The Java language provides arrays Simple ordered collection

Elements of a particular array all have

the same type

Indexed (direct) access to elements

Size is fixed when the array is created

Java Arrays

Page 4: Programming in Java [7-1] Java Tool Packages (1) Lecture7.

Programming in Java [7-4]

Example

String[ ] friends; // declare friends to be of type String array

friends = new String[3]; // instantiate the array with size == 3

// Now, add elements to the array

friends[0] = “Greg”;

friends[1] = “Sam”;

friends[2] = “Elmo”;

Page 5: Programming in Java [7-1] Java Tool Packages (1) Lecture7.

Programming in Java [7-5]

• An array variable is declared by indicating the type of elements the array will contain, and a pair of square brackets to indicate an array is being formed:

<type>[ ] identifier or <type> identifier [ ]

• Example: int[ ] ages; int ages[ ]

Date dateArray[ ]; int name[50];

Array Declaration

X

Page 6: Programming in Java [7-1] Java Tool Packages (1) Lecture7.

Programming in Java [7-6]

Array Length

• No declaration(omit) • Determined and fixed by initialization• Obtained by <var>.length• Indexing: 0 - length-1,

<array_var>[< expression>]• IndexOutOfBoundsException

Page 7: Programming in Java [7-1] Java Tool Packages (1) Lecture7.

Programming in Java [7-7]

• An array is created using the new operator. It is at this time that the size of the array is specified:

arrayName = new type[arraysize];• Example: int[ ] ages; ages = new int[3]; Date dateArray = new Date[10];

Array Creation

Page 8: Programming in Java [7-1] Java Tool Packages (1) Lecture7.

Programming in Java [7-8]

• Reference type array must be initialized, and simple type array could be default

• Initialization by new– Allocate memory for the array

• Date dateArray[] = new Date[10];

– Allocate memory for the array element• Date[0] = new Date(paralist); …

• Date[9] = new Date (paralist);

• Initialization in Declaration or Assignment

type arrayName[] = {element1[, element2…]};

– Int myArray[ ] = {1,2,3,4} //no size of array

Array Initialization

Page 9: Programming in Java [7-1] Java Tool Packages (1) Lecture7.

Programming in Java [7-9]

• Access an array element using the array name and position

arrayName[position] • Position is any integer value or expression that i

s in the range from 0 to capacity – 1 • Position is often called the index or subscript • Example:

int[ ] primes = {2, 3, 5, 7, 11, 13, 19};

int x = primes[3];

int y = primes[4];

Array Element Access

Page 10: Programming in Java [7-1] Java Tool Packages (1) Lecture7.

Programming in Java [7-10]

• Copy reference of array– Example

int myArray[ ] = {1,2,3,4};

int another[ ] = myArray;

Arrays Copy

• Copy array– System.arraycopy(from, fromIndex, to, toInd

ex, count) – Example

int myArray[ ] = {1,2,3,4};

int another[ ] = new int[4];

Sysytem.arraycopy(myArray,0,another,0,4);

Page 11: Programming in Java [7-1] Java Tool Packages (1) Lecture7.

Programming in Java [7-11]

Returning an Array from a Method

Example

Public class ArrayReturn {

public int[ ] returnsArray(boolean flag) {

int[ ] array1 = {1,2,3,4,5,6};

int[ ] array2 = {10,20,30};

if (flag) { return array1; }

else { return array2; } }

public static void main(Sring[ ] args){

ArrayReturn x = new ArrayReturn();

System.out.println(x.returnsArray(true).length);}}

Page 12: Programming in Java [7-1] Java Tool Packages (1) Lecture7.

Programming in Java [7-12]

• Declaration: <type>[]*(Array of Array)

Example: float[][] mat = new float[4][4];

• Creation

arrayName = new type[arraylen1][arraylen2] ;

arrayName = new type[arraylen1];

arrayName[0] = new type[arraylen20];

arrayName[1] = new type[arraylen21];

arrayName[arraylen-1] = new type[arraylen2n];

Multi-Dimensional Arrays

Page 13: Programming in Java [7-1] Java Tool Packages (1) Lecture7.

Programming in Java [7-13]

• Initialization in Declaration or Assignment

int myArr[][] ={{1,2},{3,4,5},{6,7}};

double m[][]={ {0*0, 1*0}, {0*1, 1*1} };

Initialization

• initialization by new

The first dimension must be determined at first initialization

Example

strArray = new String[2][ ];

strArray = new String[2][3];

strArray = new String[ ][3]; X

Page 14: Programming in Java [7-1] Java Tool Packages (1) Lecture7.

Programming in Java [7-14]

Example(1)

• double m[][] = new double[2][2]; // 0 for all elements

m[0][0]=1; m[1][1]=1;

• double m[][] = new double[2][];

m[0]=new double[4]; // 4 elements

m[1]={ 0,1,2 }; // 3 elements

• float[][] m = new float[4][];

for ( int y = 0; y < m.length; y++)

m[y]=new float[4];

Page 15: Programming in Java [7-1] Java Tool Packages (1) Lecture7.

Programming in Java [7-15]

Example(2)

string stringArray[ ] [ ]; //Declaration

strArray = new String[2] [ ]; //Creation

strArray[0] = new String[3];

strArray[1] = new String[2];

strArray[0][0] new String(“How”); //Initialization

strArray[0][1] new String(“are”);

strArray[0][2] new String(“you”);

strArray[1][0] new String(“Good”);

strArray[1][1] new String(“Luck”);

Page 16: Programming in Java [7-1] Java Tool Packages (1) Lecture7.

Programming in Java [7-16]

Example for Initialization

class Weeble{ }

public class ArraySize{

public static void main(String[] args) {

Weeble[ ] a; // Null reference

Weeble[ ] b = new Weeble[5]; // Null references

Weeble[] c = new Weeble[4];

for (int i =0; i < c.length; i ++)

c[i] = new Weeble();

Weeble[] d = {new Weeble(), new Weeble(), new Weeble()};

a = d;

Page 17: Programming in Java [7-1] Java Tool Packages (1) Lecture7.

Programming in Java [7-17]

Example(1)

1 1 1

1 2 1

1 3 3 1

1 4 6 4 1

1 5 10 10 5 1

1 6 15 20 15 6 1

yanghui = new int[yhlevel][ ];

for (i = 0; i <yanghui.length; i++)

yanghui[i] = new int[i+1]

Page 18: Programming in Java [7-1] Java Tool Packages (1) Lecture7.

Programming in Java [7-18]

Example(2)

yanghui[0][0] =1;

for (i = 1; I<yanghui.length; i++)

{

yanghui[i][0] = 1;

for(j=1; j<yanghui[i-1][j-1] + yanghui[i-1][j]);

yanghui[i][j] = yanghui[i-1][j-1]+yanghui[i-1][j];

yanghui[i][yanghui[i].length-1] =1;

}

Page 19: Programming in Java [7-1] Java Tool Packages (1) Lecture7.

Programming in Java [7-19]

Object Class

Methods:

• Object clone():[return a new copy of this object]

• boolean equals(Object): [compares object]

• void finalize():[do nothing]

• final Class getClass(): [object contains run-time type informat

ion]

• int hashCode():[returns an integer suitable for determining the

hash code for an object]

• String toString():return a string (class name,@,a numb

er )

public boolean equals(Object obj){

return (this == obj);}

==:reference

Cylinder myC = new Cylinder(5.0,2.0);

System.out.println(myC.toString());

Cylinder@15037e5

Page 20: Programming in Java [7-1] Java Tool Packages (1) Lecture7.

Programming in Java [7-20]

Object Clone(1)

Day bday = new(1965,4,30);

Day d = bday;

Day bday = new(1965,4,30);

Day d = (Day)bday.clone();•clone

Day

day

month

year

30

4

1965

d

bday

copying

Day

day

month

year

30

4

1965

d

bday

cloning

Day

day

month

year

30

4

1965

Page 21: Programming in Java [7-1] Java Tool Packages (1) Lecture7.

Programming in Java [7-21]

Object Clone (2)

Employee

name

salary

hireday

James

10000

n007

a007

Employee

name

salary

hireday

James

10000

Day

day

month

year

30

4

1965

Page 22: Programming in Java [7-1] Java Tool Packages (1) Lecture7.

Programming in Java [7-22]

Object Clone (3)

• Day

implement cloneable interface

public class Day implements Cloneable

{ …

public Object clone()

{try { return super.clone(); //calls Object.clone()

} catch(CloneNotSupportedException

{ return null; } }

}

Page 23: Programming in Java [7-1] Java Tool Packages (1) Lecture7.

Programming in Java [7-23]

Object Clone (4)

•EmployeeCall clone() of Object, then insert a new object reference for the duplicate object

Public class Employee implements Cloneable

{ … public Object clone() {try { Employee e = (Employee)super.clone(); e.hireDay = (Day)hireDay.clone(); return e; } catch(CloneNotSupportedException e) { return null;} }}

Page 24: Programming in Java [7-1] Java Tool Packages (1) Lecture7.

Programming in Java [7-24]

Wrapper Classes for Primitive Types

• The type hierarchyObject

Float

Character Number Class

Integer Long

Boolean

Double• Constructor

Create an object with the value of the primitive types

Create an object by decode the string object

• Basic methods toString typeValue:Character.charValue equals hashCode

Page 25: Programming in Java [7-1] Java Tool Packages (1) Lecture7.

Programming in Java [7-25]

The Advantages of Type Classes

• Useful static methods for a particular type have a logical and consistent home

public static int floatToIntBits(float value)

• Descriptive methods and fields also have a logical home

• For primitive types, wrapper objects can be created to hold their values

if (value >= Float.MIN_VALUE && value <= Float.MAX_VALUE )

return fasterFloatCalc((float)value);

else

return slowerDoubleCalc(value);

Integer keyObj = new Integer(key);

map.put(keyObj,value);

Page 26: Programming in Java [7-1] Java Tool Packages (1) Lecture7.

Programming in Java [7-26]

(1)Constants

• MIN_VALUE=’\u0000’ MAX_VALUE=’\uffff’

• MIN/MAX_RADIX (2~36)

(2) Methods

• public static int digit(char ch , int radix)

• public static char forDigit(int digit , int radix)

• public static boolean isDefined(char ch)

• public static boolean isLowerCase(char ch)

• public static boolean isUpperCase(char ch)

Character(1)

Page 27: Programming in Java [7-1] Java Tool Packages (1) Lecture7.

Programming in Java [7-27]

• public static boolean isTitleCase(char ch)

• public static boolean isDigit(char ch)

• public static boolean isLetter(char ch)

• public static boolean isLetterOrDigit(char ch)

• public static boolean isJavaLetter(char ch)

• public static boolean isJavaLetterOrDigit(char ch)

• public static boolean isSpace(char ch)

• public static char toLowerCase(char ch)

• public static char toUpperCase(char ch)

• public static char toTitleCase(char ch)

Character(2)

Page 28: Programming in Java [7-1] Java Tool Packages (1) Lecture7.

Programming in Java [7-28]

(1) Abstracter Methods

• public int intValue()

• public long longValue()

• public float floatValue()

• public double doubleValue()

(2) Mehtods and Constructors

• toString(type)/valueOf(String)

• static final constants MIN_VALUE 和 MAX_VALUE

Number

Page 29: Programming in Java [7-1] Java Tool Packages (1) Lecture7.

Programming in Java [7-29]

• More methods

public static int parseInt(String str , int radix) throws NumberFormatException

public static int parseInt(String s) throws NumberFormatException

public static Integer valueOf(String s, int radix) throws NumberFormatException

public static String toString(int i , int radix)[10]

toHexString 、 toOctalString 、 toBinaryString

Integer/Long• No short or byte wrapper class

• Long same as Integer

Page 30: Programming in Java [7-1] Java Tool Packages (1) Lecture7.

Programming in Java [7-30]

Float/Double(1) Constants• public final static float POSITIVE_INFINITY:+ ∞

• public final static float NEGATIVE_INFINITY: -∞

• public final static float NaN

(2) Methods• public static boolean isNaN(float val)• public boolean isNaN()• public static boolean isInfinite(float val)• public boolean isInfinite()• public static int floatToIntBits(float value) • public static float intBitsToFloat(int bits) • public static long doubleToLongBits(double value) • public static double longBitsToDouble(long bits)

Page 31: Programming in Java [7-1] Java Tool Packages (1) Lecture7.

Programming in Java [7-31]

The Math class consists of static constants and methods for

common mathematical manipulations

Math class

• All operations are carried out in double

• Math.E represents the value e(2.7182818284590452354)

Math.PI represents the valueπ(3.14159265358979323846)

• In the methods, angles are in radians, and all parameters and return values are double

• Static method random() returns r (0.0 <= r < 1.0)

Page 32: Programming in Java [7-1] Java Tool Packages (1) Lecture7.

Programming in Java [7-32]

• A string is a series of characters treated as a single unit

• String literals /constants: anonymous string objects

• Declaration & assignment:

String color=”blue”;

int len = “blue”.length();

• Classes: extends java.lang.Object

String: for string constants

StringBuffer: for string variables(resizable)

Introduction to String

Page 33: Programming in Java [7-1] Java Tool Packages (1) Lecture7.

Programming in Java [7-33]

• public final class java.lang.String extends java.lang.Object

String ( 1 )

• Constructors(1) public String(): construct a null string “”

(3) public String(char chars[])

• Contains a copy of the characters in the array

• = String(chars, 0, chars.length)

(2) public String(char chars[], int offset, int count)

• Offset: the starting position from which characters in the array are copied

• Count: the number of characters to be copied

• StringIndexOutOfBoundsException

Page 34: Programming in Java [7-1] Java Tool Packages (1) Lecture7.

Programming in Java [7-34]

(5) public String(byte bytes[],int hibyte) (not useful)

= String(bytes, hibyte, 0, bytes.length)

(4) publicString(byte bytes[],int hibyte,int offset,int count)

• bytes[]: 8-bit ASCII codes, such as for Internet • hibyte: high byte of two-byte Unicode chars

* hibyte must be zero(0) for usual ASCII codes•StringIndexOutOfBoundsException (not useful)

(6) public String(String value) create a String object as a copy of value

(7) public String(StringBuffer buffer) contains a copy of the characters in buffer, a StringBuffer object, which is a dynamically resizable string

String ( 2 )

Page 35: Programming in Java [7-1] Java Tool Packages (1) Lecture7.

Programming in Java [7-35]

char chararray[]={‘b’,’i’,’r’,’t’,’h’, ’ ’, ’d’, ’a’, ’y’}; byte bytearray[]= {‘n’, ’e’, ’w’, ’ ’, ’y’ ,’e’ ,’a’ ,’r’}; StringBuffer buffer; String s, s1, s2, s3, s4, s5, s6, s7; public void init(){

s = new String(“hello”);buffer = new StringBuffer();buffer.append(“Welcome”);s1 = new String(“”); // a null strings2 = new String(s); // hellos3 = new String(chararray); //birth days4 = new String(chararray, 6, 3); //days5 = new String(bytearray, 0, 4, 4); // years6 = new String(bytearray, 0); // new years7 = new String(buffer); // welcome }

Example

Page 36: Programming in Java [7-1] Java Tool Packages (1) Lecture7.

Programming in Java [7-36]

(1) public int length()

• return the number of characters in the current string

• Example: s.length(); // not s.length

• Strings don’t have a length instance variable that specifies the number of elements in a string(different from array)

(2)public char charAt(int index)

• select and return the char at a specific position (index: 0..length-1) in the string

• StringIndexOutOfBoundsException

Basic Methods ( 1 )

•Example

for (int i = 0; i < str.length(); i++)

counts[str.charAt(i)]++;

Page 37: Programming in Java [7-1] Java Tool Packages (1) Lecture7.

Programming in Java [7-37]

(3) public String concat(String str) • s1.concat(s2) concatenates s1 and s2 as a new object to be returned, and s1 and s2 are not modified• If s2.length==0 then return the original s1;• “concat ” is similar to ‘+’

newS=oldS concat(“(not”) == newS=oldS+“not”

(4) public String replace(char oldChar, char newChar)

• s1.replace (c1,c2) generates a new string in which every occurrence in s1 of c1 is replaced by c2

• if there were no occurrences, then return the original s1

(5) public String toUpperCase()/toLowerCase

s.toLowerCase() generates a new string with uppercase/ lowercase letters where corresponding lowercase/ uppercase letters reside in s

Basic Methods ( 2 )

Page 38: Programming in Java [7-1] Java Tool Packages (1) Lecture7.

Programming in Java [7-38]

(6) public String trim()

• s.trim () generates a new string that removes all whitespace characters(such as spaces, newlines and tabs) that appear at the beginning or end of s

• If c<=’\u0020’ then c is a whitespace char in Unicode

(7) public String toString()

• toString is inherited from Object(classname+the object hashcode), or redefined

• toString is normally used to express the contents of an object as text

(8) public void getChars(int srcBegin, int srcEnd, char dst[], int dstBegin)

Basic Methods ( 3 )

• (9) public void getBytes(int srcBegin, int srcEnd, byte dst[], int dstBegin) •Copy the low-order byte of each character in a string into a byte array

Page 39: Programming in Java [7-1] Java Tool Packages (1) Lecture7.

Programming in Java [7-39]

(10) public char[] toCharArray() • s.toCharArray(); creates a new character array contain

ing a copy of the characters in s

Basic Methods ( 4 )

Public static String squeezeOut(String from, char toss) {

char []chars = from.toCharArray();

int len = chars.length;

for (int i = 0; i < len; i ++) {

if (chars[i] = = toss) {

- -len;

System.arraycopy(chars, i +1, chars, i, len-i);

- - i; } } return new String( chars, 0, len); }

• Example : remove all appearances of the character in the string

Page 40: Programming in Java [7-1] Java Tool Packages (1) Lecture7.

Programming in Java [7-40]

• Lexicographical comparison: the integer Unicode values that represent each character in each string are compared

Comparing Strings (1)

(1)equals

public boolean equals(Object anObject)

• s1.equals(s2) returns true IF s2 is a string and has the same length and the same Unicode characters as the current string(s1), otherwise returns false

• ‘==’ has different functionality for object reference and primitive data types: both primitive data type values are identical / both references refer to the same object in memory

Page 41: Programming in Java [7-1] Java Tool Packages (1) Lecture7.

Programming in Java [7-42]

(2) equalsIgnoreCase • public boolean equalsIgnoreCase(String aString) •If the case of letters is ignored, two characters(c1,c2) are equal only when: (a) c1==c2; OR

(b) c1.toUppercase()= c2.toUppercase(); OR

(c) c1.toLowercase()= c2.toLowercase();

Comparing Strings (2)

(3) compareTo • public int compareTo (String aString) • s1.compareTo(s2) returns

0 if s1=s2; a negative number if s1 is less than s2; a positive number if s1 is greater than s2

• The return value is the difference between the integer representations of the first different character. For example, h(104) -H(72) = 32

Page 42: Programming in Java [7-1] Java Tool Packages (1) Lecture7.

Programming in Java [7-43]

private String[] table; public int position(String key) { int lo = 0; int hi = table.length –1;

while (lo <= hi) { int mid = lo + (hi - lo)/2; int cmp = key.compareTo(table[mid]); if (cmp = =0) return mid; else if (cmp < 0) hi = mid –1; else lo = mid + 1; } return –1; }

二分查找法

Page 43: Programming in Java [7-1] Java Tool Packages (1) Lecture7.

Programming in Java [7-44]

(4) RegionMatches• public boolean regionMatches

(int start, String s2, int ostart, int len) OR

(boolean ignCase, int start, String s2, int ostart, int len)

Comparing Strings (3)

• s1.regionMatches(start,s2,ostart,len): compare portions of two strings(s1,s2) for equality, and return true only if the specified number of chars are lexicographically equal, where start/ostart is the starting index of s1/s2, and len is the number of characters to compare

• If start(ostart) is a negative number, or start(ostart)+len> s1(s2).length(), return FALSE.(no exception thrown)

• ignCase: if true, ignore the case of compared characters

Page 44: Programming in Java [7-1] Java Tool Packages (1) Lecture7.

Programming in Java [7-45]

String str = "Look, look!";

boolean b1, b2, b3;

b1 = str.regionMatches(6, "Look", 0, 4); // false

b2 = str.regionMatches(true, 6, "Look", 0, 4); //true

b3 = str.regionMatches(true, 6, "Look", 0, 5); //false

Comparing Strings (4)

(5) startsWith/endsWith • public boolean startsWith (String prefix, int toffset)

• public boolean startsWith (String prefix)

• s1.startsWith(prefix, toffset) returns true if prefix is a sub-string of s1 at the location of toffset

• s1.startsWith(prefix)=s1.startsWith(prefix,0), returns true if s1 starts with prefix

• s1.endsWith(suffix) returns true if s1 ends with suffix

Page 45: Programming in Java [7-1] Java Tool Packages (1) Lecture7.

Programming in Java [7-46]

• public int hashCode()

• The hash code is used to choose/lookup the locati

on

• hashCode is a method of Object, and is override

n in String

• Two strings with same contents have same hash

codes, but different string contents may also hav

e same hash codes

hashCode Method

Page 46: Programming in Java [7-1] Java Tool Packages (1) Lecture7.

Programming in Java [7-47]

(1) indexOf: search the first occurrence of a character/ substring in a string(s)

• public int indexOf(char ch)

** locate the first occurrence of ch in s, and return the index if found, otherwise return -1

** Example: letters.indexOf((int)’c’)

• public int indexOf(char ch, int fromIndex)

** locate the first occurrence of ch in s by starting index fromIndex, and return the index if found, otherwise -1

• public int indexOf(String str)

• public int indexOf(String str, int fromIndex)

Locating/Extracting Substrings (1)

Page 47: Programming in Java [7-1] Java Tool Packages (1) Lecture7.

Programming in Java [7-48]

(2) lastIndexOf: search the last occurrence of a character/ substring in a string(s) public int lastIndexOf(int ch)public int lastIndexOf(int ch, int fromIndex)public int lastIndexOf(String str)public int lastIndexOf(String str, int fromIndex)

(3) substring: enable to create a new string by coping part of an existing object(s)

• public String substring(int beginIndex): return a substring copy of the characters from beginIndex to the end

• public String substring(int beginIndex, int endIndex): return a substring copy of the characters from beginIndex to endIndex-1

•StringIndexOutOfBoundsException

Locating/Extracting Substrings (2)

Page 48: Programming in Java [7-1] Java Tool Packages (1) Lecture7.

Programming in Java [7-49]

Public static String quotedString(String frm,char start, char end) {

int startPos = from.indexOf(start);

int endPos = from.lastIndexOf(end);

if (startPos = = -1)

return null;

else if (endPos = = -1)

return from.substring(startPos);

else

return from.substring(startPos, endPos + 1);

}

从一个字符串中提取子串

Page 49: Programming in Java [7-1] Java Tool Packages (1) Lecture7.

Programming in Java [7-50]

(1)public static String valueOf(boolean b)

• Return “true” if b is true, otherwise “false”

(2) public static String valueOf(double d) • Convert a double to a string

• Return “NaN” ,”-Infinity”,”Infinity”,”-0.0”,”+0.0”,”0.0” if d=NaN, NEGATIVE-INFINITY, POSITIVE-INFINITY, -0.0, +0.0 respectively

(3) public static String valueOf(float f) • Convert a float to a string(similar to double)

(4) public static String valueOf(int i)

(5) public static String valueOf(long l)

Converting to Strings: static valueOf(1)

Page 50: Programming in Java [7-1] Java Tool Packages (1) Lecture7.

Programming in Java [7-51]

(6) public static String valueOf(Object obj)

• Return “null” if obj is empty, else return a string according to obj.toString()

(7) public static String valueOf(char c)

(8) public static String valueOf(char data[])

(9) public static String valueOf(char data[], int offset, int count)

(10) public static String copyValueOf(char data[])

(11) public static String copyValueOf(char data[], int offset, int count)

• String.copyValueOf(chars,0,len)=new String(chars, 0, len)

Converting to Strings: static valueOf(2)

Page 51: Programming in Java [7-1] Java Tool Packages (1) Lecture7.

Programming in Java [7-52]

• Introduction Objects of the String class: read-only

StringBuffer: modifiable,and used to implement + and +=

java.lang.StringBuffer extends java.lang.Object

• Constructors (1) public StringBuffer() • Create a null string(the initial capacity of chars is 16)

(2) public StringBuffer(int length)• Create a null buffer, where length is the capacity • NegativeArraySizeException, If length<0

(3) public StringBuffer(String str)

• Create a buffer containing the characters of str, and with an initial capacity which is str.length()+16

StringBuffer

Page 52: Programming in Java [7-1] Java Tool Packages (1) Lecture7.

Programming in Java [7-53]

(1) public int length()

• The number of characters currently in the buffer

(2) public int capacity() • The number of characters can be stored in the buffer

(3) public void setLength(int newLength) • increase/decrease the length of a buffer

• If newLength is less than the current number of characters in the buffer, the characters are truncated to the newlength (the characters after the newlength are discarded)

• If newLength is greater than the current number of characters in the buffer,null(‘\u0000’) chars are appended

Length and Capacity(1)

Page 53: Programming in Java [7-1] Java Tool Packages (1) Lecture7.

Programming in Java [7-54]

Class StringBufferDemo {

public static void main(String args[]) {

StringBuffer sb = new StringBuffer(“Hello”);

System.out.println(“length =” + sb.length());

System.out.println(“capacity =” + sb.capacity());

}

}

Example

Page 54: Programming in Java [7-1] Java Tool Packages (1) Lecture7.

Programming in Java [7-55]

(4) public void ensureCapacity(int minCapacity) • Ensure the capacity to a minimum of minCapacity characters

• If the original capacity is less than minCapacity, ensure a capacity that is the greater of minCapacity or twice the original capacity plus 2

• If the current capacity is more than minCapacity, the capacity remains unchanged

(5) Notes • String Buffers may be automatically extended when characters are appended. But it is not so efficient

• Capacity methods may be used to avoid extending string buffers for many times • For example, construct a string buffer(large enough)

Length and Capacity(2)

Page 55: Programming in Java [7-1] Java Tool Packages (1) Lecture7.

Programming in Java [7-56]

*10 overloaded append methods, allowing various data type values to be added to the end of a string buffer

(1) public StringBuffer append(boolean b)

(2) public StringBuffer append(double d)

(3) public StringBuffer append(float f)

(4) public StringBuffer append(int i)

(5) public StringBuffer append(long l)

(6) public StringBuffer append(Object Obj)

* For (1-6), String.valueOf() is invoked for converting the parameter into a string

(7) public StringBuffer append(char c)

* The buffer length is added by 1

Append(1)

Page 56: Programming in Java [7-1] Java Tool Packages (1) Lecture7.

Programming in Java [7-57]

(8) public StringBuffer append(char str[])

(9) public StringBuffer append (char str[], int offset, int len)(10) public StringBuffer append(String str) •For (8-10), the buffer length is added automatically

(11) Notes • Actually, StringBuffer and append are used by compiler to implement + and += for concatenating strings

• ”BC”+22 is performed as new StringBuffer().append (“BC”).append(22).toString()

• s+=”!” is performed as new StringBuffer().append(s). append(“!”).toString()

• “four:”+2+2--“four:22” ; “four:”+(2+2)--“four:4”

Append(2)

Page 57: Programming in Java [7-1] Java Tool Packages (1) Lecture7.

Programming in Java [7-58]

•9 overloaded insert methods, allowing various data type values to be inserted at any position in a string buffer

(1) public StringBuffer insert(int offset, boolean b)

(2) public StringBuffer insert(int offset, char c)

(3) public StringBuffer insert(int offset, char str[])

(4) public StringBuffer insert(int offset, double d)

(5) public StringBuffer insert(int offset, float f)

(6) public StringBuffer insert(int offset, int i)

(7) public StringBuffer insert(int offset, long l)

(8) public StringBuffer insert(int offset, Object obj)

(9)public StringBuffer insert(int offset, String str)

Insert(1)

Page 58: Programming in Java [7-1] Java Tool Packages (1) Lecture7.

Programming in Java [7-59]

• offset>=0 and offset<=s.length, otherwise a StringIndex O

utOfBoundsException is generated

Insert(2)

•Example

StringBuffer buf = new StringBuffer();

String now = new java.util.Date().toString();

buf.ensureCapacity(buf.length() + now.length() + 2);

buf.insert(0, now).insert(now.length(), ": ");

Page 59: Programming in Java [7-1] Java Tool Packages (1) Lecture7.

Programming in Java [7-60]

(1) public char charAt (int index)

• Return the char at the index

• index>=0 and index<s.length, otherwise a StringIndex OutOfBoundsException is generated

Char Operations

(2) public void setCharAt (int index, char ch)

• Set the character at the specified(index) position to ch

(3) public void getChars(int srcBegin, int srcEnd, char dst[], int dstBegin)

• Copy the characters of index srcBegin..srcEnd-1 in the buffer to a char array(dst)

Page 60: Programming in Java [7-1] Java Tool Packages (1) Lecture7.

Programming in Java [7-61]

Public static void replace(StringBuffer str, char from, char to) {

for (int i = 0; i < str.length(), i++)

if (str.charAt(i) = = from)

str.setCharAt(i, to);

}

替换字符串中某字符的出现

Page 61: Programming in Java [7-1] Java Tool Packages (1) Lecture7.

Programming in Java [7-62]

去掉缓冲区一部分字符

Public static StringBuffer remove(StringBuffer buf, int pos, int cnt) {

if (pos < 0 || cnt < 0 || pos + cnt > buf.length())

throw new IndexOutofBoundsException();

int leftover = = buf.length() – (pos + cnt) ;

if (leftover = = 0) { buf.setLength(pos) ; return buf; }

char[] chrs = new char[leftover];

buf.getChars(pos + cnt, buf.length(), chrs, 0);

buf.setLength(pos);

buf.append(chrs);

return buf; }

Page 62: Programming in Java [7-1] Java Tool Packages (1) Lecture7.

Programming in Java [7-63]

System & Runtime

• The System class provides static methods to

represent the state o the entire system. As a

convenience, several methods in System operate on

the current runtime

•The Runtime class represents the state of a Java

runtime. This object provides access to functionality

that is per-runtime,such as controlling the garbage

collector and exiting the runtime

• The Process class represents a running process

created with a Runtime.exec call

Page 63: Programming in Java [7-1] Java Tool Packages (1) Lecture7.

Programming in Java [7-64]

Standard I/O Stream• public static InputStream in• public static PrintStream out• public static PrintStream err

System Properties

(1) Properties

java.version 、 java.vendor 、 java.vendor.url

java.home 、 java.class.version 、 java.class.path

os.name 、 os.arch 、  os.version 、 file.separator

path.separator 、 line.separator 、   user.name

user.home 、 user.dir

System Class(1)

Page 64: Programming in Java [7-1] Java Tool Packages (1) Lecture7.

Programming in Java [7-65]

(2) Methods

• public static Properties getProperties()• public static void setProperties(Properties props)

• public static String getProperty(String key): System.getProperties().getProperty(key)

• public static String getProperty(String key,String defaultValue)

(3) Methods decode values in the standard Java formats• static boolean Boolean.getBoolean(String name)• static Integer Integer.getInteger(String name)• static Integer Integer.getInteger(String name,Integer def)• static Long Long.getLong(String nm)• static Long Long.getLong(String nm,Long def)

System Class(2)

Page 65: Programming in Java [7-1] Java Tool Packages (1) Lecture7.

Programming in Java [7-66]

(4) Example

public static File personal(String fileName){

String home = System.getProperty("user.home"); if (home == null) return null; else return new File(home,fileName); }

System Class(3)

Miscellaneous• public static long currentTimeMillis()

• public static void arraycopy(Object src,int srcPos,Object dst,int dstPos, int count)

Page 66: Programming in Java [7-1] Java Tool Packages (1) Lecture7.

Programming in Java [7-67]

1. Runtime

• Objects of the Runtime class represent the state of the runtime system and operations that it can perform

• A Runtime object that represents the current runtime can be obtained by invoking the static method Runtime.getRuntime

2. Memory Management(1) Methods• public long freeMemory()

• public long totalMemory()• void gc()• void runFinalization()

Runtime Class(1)

Page 67: Programming in Java [7-1] Java Tool Packages (1) Lecture7.

Programming in Java [7-68]

(2) Example

public static void fullGC(){

Runtime rt = Runtime.getRuntime();

long isFree = rt.freeMemory();

long wasFree;

do{ wasFree = isFree;

rt.gc();

isFree = rt.freeMemory();

}while(isFree > wasFree);

rt.runFinalization();

}

Runtime Class(2)

Page 68: Programming in Java [7-1] Java Tool Packages (1) Lecture7.

Programming in Java [7-69]

• Each class and interface in the system has a Class object that represents it. This object can be used for basic queries about the class or interface, and to create new objects of a class

Class

• The Class class provides a tool to manipulate classes, primarily for creating objects of types specified in strings, and for loading classes using specialized techniques, such as across the network

• Two ways for getting a Class object

getClass()Class.forName (s); s is a string

Page 69: Programming in Java [7-1] Java Tool Packages (1) Lecture7.

Programming in Java [7-70]

• static Class forName(String className) throws ClassNotFoundException

• ClassLoader getClassLoader ()

• Class[] getInterfaces()

• String getName()• Class getSuperclass() • boolean isInterface()• Object newInstance() throws InstantiationException, IllegalAccessException• String toString()

Example1: This class prints the type hierarchy of the type represented by a particular Class object

• Example2: Choosing the sorting algorithm dynamically

Methods

Page 70: Programming in Java [7-1] Java Tool Packages (1) Lecture7.

Programming in Java [7-75]

Assignment

1 、用多维数组编一个程序实现以下操作:对给定的两名学生的各三门成绩,输出所有成绩中的最高分和最低分,并输出每个学生的平均分

2 、编写一个方法把一个表示十进制的字符转转换为以接受参数指定的分割符号(如逗号)来分割的字符串,从右面开始,分割字符之间的数字的数目也由参数指定(如每隔 5个分割)