Download java.util.LinkedList

Document related concepts

Java ConcurrentMap wikipedia , lookup

Transcript
http://www.csie.nctu.edu.tw/~tsaiwn/oop/
Programming in Java
Java Collections Framework (JCF)
java.util.* -- Vector, Stack, HashTable…,
String and String Parser
蔡文能
交通大學資訊工程學系
[email protected]
交通大學資訊工程學系
Java
Java Collection Framework
Agenda
Java Collections Framework (JCF)
java.util.StringTokenizer
java.util.Random
java.util.Arrays
java.util.List
java.util.ArrayList, java.util.LinkedList
Generic Programming <T>
Legacy collection classes (Containers)
交通大學資訊工程學系 蔡文能
6-第2頁
Java
Java Collection Framework
Package java.util (1/3)
Contains the collections framework, legacy
collection classes, event model, date and time
facilities, internationalization, and miscellaneous
utility classes (a string tokenizer, a randomnumber generator, and a bit array).
A collection — sometimes called a container —
is simply an object that groups multiple elements
into a single unit. Collections are used to store,
retrieve, manipulate, and communicate
aggregate data.
交通大學資訊工程學系 蔡文能
6-第3頁
Java
Java Collection Framework
Package java.util (2/3)
A collections framework is a unified architecture for
representing and manipulating collections. All collections
frameworks contain:
 Interfaces
 Implementations
 Algorithms --- polymorphic methods: the same method can be
used on many different implementations of the appropriate
collection interface. In essence, algorithms are reusable
functionality
Collection implementations in earlier (pre-1.2) versions of
the Java platform included Vector, Hashtable, and array.
Those earlier versions, however, did not contain a
collections framework.
交通大學資訊工程學系 蔡文能
6-第4頁
Java
Java Collection Framework
Package java.util (3/3)
Benefits of the Java Collections Framework
(JCF)







Separate interface from implementation
Reduces programming effort
Increases program speed and quality
Allows interoperability among unrelated APIs
Reduces effort to learn and to use new APIs
Reduces effort to design and to implement new APIs
Fosters software reuse (促進軟體再利用)
http://java.sun.com/docs/books/tutorial/collections/intro/index.html
交通大學資訊工程學系 蔡文能
6-第5頁
Java
交通大學資訊工程學系 蔡文能
Java Collection Framework
6-第6頁
Java
交通大學資訊工程學系 蔡文能
Java Collection Framework
6-第7頁
Java
Java Collection Framework
The Goals of JCF
Small API
 Number of interfaces
 Number of methods per interface
 Low "conceptual weight"
Builds on existing Java collections (Vector,
Hashtable)
Interconvertible with Java arrays
Ships with JDK 1.2 by the end of 1998
交通大學資訊工程學系 蔡文能
6-第8頁
Java
Java Collection Framework
core collection interfaces (1/3)
the core collection interfaces form a hierarchy: a
Set is a special kind of Collection, a SortedSet is a
special kind of Set, and so forth. Note also that the
hierarchy consists of two distinct trees: a Map is
not a true Collection.
Deque
交通大學資訊工程學系 蔡文能
6-第9頁
Java
Java Collection Framework
core collection interfaces (2/3)
Collection: The root of the collection hierarchy. A
collection represents a group of objects, known as its
elements.
Set: A collection that cannot contain duplicate elements.
List: An ordered collection (sometimes called a sequence).
Lists can contain duplicate elements.
Queue: A collection used to hold multiple elements prior to
processing. Besides basic Collection operations, queues
provide additional insertion, extraction, and inspection
operations.
Queues typically, but do not necessarily, order elements in
a FIFO (First-In-First-Out) manner.
交通大學資訊工程學系 蔡文能
6-第10頁
Java
Java Collection Framework
core collection interfaces (3/3)
Map: An object that maps keys to values. Maps cannot
contain duplicate keys: Each key can map to at most one
value. (Note that Map is NOT a true Collection)
 If you've used Hashtable, you're already familiar with the general
flavor of Map.
SortedSet: A Set that maintains its elements in ascending
order. Several additional operations are provided to take
advantage of the ordering.
SortedMap: A Map that maintains its mappings in
ascending key order. This is the Map analog of SortedSet.
 Sorted maps are used for naturally ordered collections of
key/value pairs, such as dictionaries and telephone directories.
交通大學資訊工程學系 蔡文能
6-第11頁
Java
Java Collection Framework
interface Collection
public interface Collection<E> extends Iterable<E> {
// Basic Operations
int size( ); boolean isEmpty( );
boolean contains(Object element);
boolean add(E element); // Optional
boolean remove(Object element); // Optional
Iterator iterator();
// Bulk Operations
boolean containsAll(Collection<?> c);
boolean addAll(Collection<? extends E> c); // Optional
boolean removeAll(Collection<?> c); // Optional
boolean retainAll(Collection<?> c); // Optional
void clear(); // Optional
// Array Operations
Object[ ] toArray();
<T> T[ ] toArray(T[ ] a);
}
交通大學資訊工程學系 蔡文能
6-第12頁
Java
Java Collection Framework
Java Utilities
Utility Interfaces
 Comparator
 Iterator
Utility Classes
 java.util.Collections
Goody: Collections.reverseOrder( )




java.util.Arrays
StringTokenizer, Random, Timer, TimerTask
Vector, Stack
Hashtable, Properties, …
交通大學資訊工程學系
蔡文能
Copyright ?1998 Purple Technology, Inc.
1.0t
6-第13頁
13
Java
Java Collection Framework
interface Iterator (1/2)
Represents a loop
Created by Collection.iterator( )
Similar to Enumeration
 Improved method names
 Allows a remove( ) operation on the current item
Methods
 boolean hasNext( )
Returns true if the iteration has more elements
 Object next( )
Returns next element in the iteration
 void remove( )
Removes the current element from the underlying Collection
交通大學資訊工程學系
蔡文能
Copyright ?1998 Purple Technology, Inc.
1.0t
6-第14頁
14
Java
Java Collection Framework
interface Iterator (2/2)
An Iterator is an object that enables you to traverse
through a collection, and to remove elements from the
collection selectively, if desired.
public interface Iterator<E> {
Example of using the Iterator :
boolean hasNext();
E next();
void remove(); // Optional
}
static void filter(Collection c) {
for (Iterator i = c.iterator();
i.hasNext();
)
if ( !cond(i.next() ) )
i.remove();
} // filter
交通大學資訊工程學系 蔡文能
6-第15頁
Java
Java Collection Framework
java.util.Random (1/3)
Benchmarks uses the java.util.Random class — a more controlled
way to generate random numbers.
Constructors:
Default “seed”:
System.currentTimeMillis( )
If we set the same “seed,” we get the same “random” sequence.
Random generator = new Random( );
Random generator2 = new Random(seed);
交通大學資訊工程學系 蔡文能
long seed;
6-第16頁
Java
Java Collection Framework
java.util.Random (2/3)
Random generator = new Random( );
Methods:
int k = generator.nextInt ( );
All 232 possible int
values are produced
with (approximately)
equal probability
int k = generator.nextInt (n);
0k<n
double x = generator.nextDouble ( );
0x<1
交通大學資訊工程學系 蔡文能
6-第17頁
Java
Java Collection Framework
java.util.Random (3/3)
synchronized public void setSeed(long seed) {
this.seed = (seed ^ 0x5DEECE66DL) & ((1L << 48) - 1);
haveNextNextGaussian = false;
}
synchronized public double nextGaussian( ) {
if (haveNextNextGaussian) {
haveNextNextGaussian = false;
return nextNextGaussian;
} else {
double v1, v2, s;
do {
v1 = 2 * nextDouble( ) - 1;
// between -1.0 and 1.0
v2 = 2 * nextDouble( ) - 1;
// between -1.0 and 1.0
s = v1 * v1 + v2 * v2;
} while (s >= 1);
double norm = Math.sqrt(-2 * Math.log(s)/s);
nextNextGaussian = v2 * norm;
haveNextNextGaussian = true;
return v1 * norm;
}
}
交通大學資訊工程學系 蔡文能
6-第18頁
Java
Java Collection Framework
Gaussian distributions
The Gaussian distribution is a normal curve with mean (average) of
0.0 and standard deviation of 1.0
It looks like this:
34%
34%
16%
Random random=new Random( );
-1.0
16%
0.0
1.0
Most real “natural” data—shoe sizes, quiz scores, amount of rainfall, length of
life, etc.—fit a normal curve
To generate realistic data, the Gaussian may be what you want:
r = desiredStandardDeviation * random.nextGaussian( ) + desiredMean;
“Unnatural data,” such as income or taxes, may or may not be well described
by a normal curve
交通大學資訊工程學系 蔡文能
6-第19頁
Java
Java Collection Framework
68-95-99.7 Rule
68.26%
68.26% within 1 stdev value
of the mean
34.13 % above the mean
34.13% below the mean
95.44%
99.74%
Gaussian distribution
交通大學資訊工程學系 蔡文能
=
Normal Distribution
6-第20頁
Java
Java Collection Framework
java.util.Timer
A facility for threads to schedule tasks for future execution in a
background thread. Tasks may be scheduled for one-time
execution, or for repeated execution at regular intervals.
Corresponding to each Timer object is a single background thread
that is used to execute all of the timer's tasks, sequentially. Timer
tasks should complete quickly. If a timer task takes excessive
time to complete, it "hogs" the timer's task execution thread.
If the timer's task execution thread terminates unexpectedly, for
example, because its stop method is invoked, any further attempt
to schedule a task on the timer will result in an
IllegalStateException, as if the timer's cancel method had been
invoked.
You Can schedule a TimerTask using a Timer object.
交通大學資訊工程學系 蔡文能
6-第21頁
Java
Java Collection Framework
Consider how to read a number?
In C Language:
 scanf with %d format (%f for float, %lf for double)
May cause program down due to strange input
May forget to pass address of variable to scanf
 Better way
Read it into program as a string ( how ? )
 gets(buf); /* not good enough */
 fgets(buf, sizeof(buf), stdin); /* buf is a char array */
Then, use sscanf to scan that string; or use the following utility
functions:
 atol, atof, strtol, strtod, strtok, strsep
What about in Java ?
交通大學資訊工程學系 蔡文能
6-第22頁
Java
Java Collection Framework
String in Java is not char array
String is not a char array in Java
String is different from StringBuffer
Elements in String/StringBuffer can be accessed
via using the charAt( position ) method.
The content of a String can not be modified
substring ?
capacity of a StringBuffer ? Size of a String
Buffer ?
 size <= capacity
交通大學資訊工程學系 蔡文能
6-第23頁
Java
Java Collection Framework
Characters
In Java single characters are represented using the data type
char. ( do NOT confuse with the wrapper Character class)
 char is one of the 8 primitive data types.
 Character constants are written as symbols enclosed in single quotes,
for example, 'a', 'X', and '5'. ( ' : apostrophe, " : quote )
To represent characters in computer, U. S. computer
manufacturers devised several coding schemes.
One coding scheme widely used today is ASCII (American
Standard Code for Information Interchange).
To accommodate the character symbols of non-English
languages, the Unicode Consortium established the Unicode
Worldwide Character Standard, commonly known as Unicode
=> http://www.unicode.org/
交通大學資訊工程學系 蔡文能
6-第24頁
Java
Java Collection Framework
Strings
Not String
Features:




Strings are objects and java.lang.String is the class.
Use 16 bit UNICODE
All objects (java.lang.Object) have methods toString();
Special treatment of the + operator
"Object" + obj + "will call toString( ) function"

new StringBuffer("Object").append(obj.toString())
.append("will call toString( ) function").toString()
Example:
System.out.println("Hello World");
String hey = "Hello";
String you = "World";
System.out.println(hey + " " + you);
int len = hey.length();
Notice the performance.
交通大學資訊工程學系 蔡文能
6-第25頁
Java
Java Collection Framework
StringBuffer
For the StringBuffer Class
 StringBuffer provides length and charAt accessor
methods, as well as the String class.
 capacity method
Returning the amount of space currently allocated for the
StringBuffer, rather than the amount of space used.
For example, in reverseIt method (next page) :
 dest.capacity() will never change.
 dest.length() will increase for each iteration.
 Initializing a StringBuffer's capacity to a reasonable first
guess.
Minimizing the number of times memory must be allocated for it.
交通大學資訊工程學系 蔡文能
6-第26頁
Java
Java Collection Framework
String vs. StringBuffer
Use the String class when you are working with strings
that cannot change.
StringBuffer is used when you want to manipulate the
contents of the string on the fly.
public class ReverseString {
public static String reverseIt(String source) {
int i, len = source.length();
StringBuffer dest = new StringBuffer(len);
for (i = (len - 1); i >= 0; i--)
dest.append(source.charAt(i));
return dest.toString();
}
}
交通大學資訊工程學系 蔡文能
6-第27頁
Java
Java Collection Framework
Creating Strings and StringBuffers
Creating a String
 String a = "Gobbledy gook.”;
 new String("Gobbledy gook.");
Creating a StringBuffer
 StringBuffer dest = new StringBuffer(len);
 StringBuffer's default constructor may leaves the buffer's
length undetermined.
 It's more efficient to specify the length of the buffer.
交通大學資訊工程學系 蔡文能
6-第28頁
Java
交通大學資訊工程學系 蔡文能
Java Collection Framework
6-第29頁
Java
Java Collection Framework
String and StringBuffer are Objects
String is a class in the java.lang package.
Because String is a class, we need to create an instance of String in Java for
string processing. Like any other objects,
we need a declaration and object creation for the instances of the String class.
For example,
String name1;
name1 = new String( "Latte" );
But we normally use a shorthand, instead, treating
String objects much like primitive data. For example,
These two
statements
are
equivalent.
String name1;
name1 = "Latte";
交通大學資訊工程學系 蔡文能
6-第30頁
Java
Java Collection Framework
Accessing char Elements in a String
Individual characters in a String accessed with the charAt method.
char charAt(int index)
 Returns the character at the
specified index.
 An index ranges from 0 to length( ) - 1.
 The first character of the sequence
is at index 0, the next at index 1,
and so on, as for array indexing.
不可以直接使用 s[n] 而要改用 s.charAt(n)
交通大學資訊工程學系 蔡文能
6-第31頁
Java
Java Collection Framework
Accessing char Elements in a String (cont.)
String name = "Example";
0
1
2
3
4
5
6
E
x
a
m
p
l
e
name
This variable refers to the
whole string.
交通大學資訊工程學系 蔡文能
name.charAt( 3 )
The method returns the
character at position # 3.
6-第32頁
Java
Java Collection Framework
substring in a String/StringBuffer
substring in a String accessed with the substring method.
String substring(int beginIndex)
 Returns a new string that is a substring of this
string. The substring begins with the character
at the specified beginIndex and extends to the end
of this string.
Examples: "unhappy".
 substring(2) returns "happy"
 substring(3) returns “appy"
String substring(int beginIndex, int endIndex)
 Returns a new string that is a substring of this
string. The substring begins at the specified
beginIndex and extends to the character at index
endIndex - 1. Thus the length of the substring is
endIndex-beginIndex.
Examples: "hamburger".
 substring(4, 8) returns "urge"
"smiles".
 substring(1, 5) returns "mile"
交通大學資訊工程學系 蔡文能
6-第33頁
Java
Java Collection Framework
Determining the String Size
We determine the number of characters in a String with the length
method.
String name = “Sumatra”,
str1 = “one”,
str2 = “”,
str3;
name.length( );
7
Error because
no object is
created for str3,
so it is a null.
str1.length( );
3
str2.length( );
0
str3.length( );
Error!
交通大學資訊工程學系 蔡文能
6-第34頁
Java
Java Collection Framework
Example using length( ) , charAt(int i)
Reverse a string
public class ReverseString {
public static String reverseIt(String source) {
int i, len = source.length();
StringBuffer dest = new StringBuffer(len);
for (i = (len - 1); i >= 0; i--)
dest.append(source.charAt(i));
return dest.toString();
}
}
交通大學資訊工程學系 蔡文能
6-第35頁
Java
Java Collection Framework
More String/StringBuffer Methods
int indexOf(int character)
int lastIndexOf(int character)
 Return the index of the first (last) occurrence of the specified
character.
int indexOf(int character, int from)
int lastIndexOf(int character, int from)
 Return the index of the first (last) occurrence of the specified
character, searching forward (backward) from the specified
index.
void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
 Copies characters from this string into the destination character array.
boolean equals(Object anObject)
 Compares this string to the specified object.
Object clone() throws CloneNotSupportedException
 Creates and returns a copy of this object.
交通大學資訊工程學系 蔡文能
6-第36頁
Java
Java Collection Framework
String Concatenation
Concatenation and the + Operator
 In Java, you can use + to concatenate String:
String cat = "cat";
System.out.println("con" + cat + "enation");
 But the compiler uses StringBuffer to implement
concatenation behind the scenes.
String cat = "cat";
System.out.println(new StringBuffer().append("con").
append(cat).append("enation").toString());
交通大學資訊工程學系 蔡文能
6-第37頁
Java
Java Collection Framework
Converting Objects to Strings
The toString Method
public class ReverseString {
public static String reverseIt(String source) {
int i, len = source.length();
StringBuffer dest = new StringBuffer(len);
for (i = (len - 1); i >= 0; i--)
dest.append(source.charAt(i));
return dest.toString();
}
}
All classes inherit toString from the Object class.
 Many classes in the java.lang package override this method to provide
an implementation that is meaningful to that class.
The valueOf Method
 You can use valueOf to convert variables of different types to String.
System.out.println(String.valueOf(Math.PI));
交通大學資訊工程學系 蔡文能
6-第38頁
Java
Java Collection Framework
Converting Strings to Numbers
The "type wrapper" classes (Integer, Long, Float,
and Double) provide a class method named valueOf
that converts a String to an object of that type.
String piStr = "3.14159";
Float pi = Float.valueOf(piStr); /*物件*/
float pi2 = Float.parseFLOAT(piStr); /*值*/
Object
class method = static method
交通大學資訊工程學系 蔡文能
6-第39頁
Java
Java Collection Framework
Strings and the Java Compiler
Literal Strings
 You can use literal strings anywhere you would use a String object.
System.out.println("Hello World!");
 You can also use String methods directly from a literal string.
int len = "Goodbye Cruel World".length();
 These two constructs are equivalent.
String s = "Hala Hala";
String s = new String("Hala Hala");
But first one which is more efficient than the second.
The second end up creating two String objects instead of one.
交通大學資訊工程學系 蔡文能
6-第40頁
Java
Java Collection Framework
More about I/O : C
Read an Integer
C
static char buf[999];
fgets(buf, sizeof(buf), stdin); /* read one line first */
static char buf[999];
file * fp; int haha;
fp = fopen("myinput.dat", "rt");
fgets(buf, sizeof(buf), fp); /* read one line first */
haha = atol(buf);
交通大學資訊工程學系 蔡文能
6-第41頁
Java
Java Collection Framework
More about I/O : C++
Read an Integer
C++
static char buf[999];
cin.getline(buf, sizeof(buf) ); /* read one line first */
static char buf[999];
fstream fs; int haha;
fs.open( "myinput.dat", ios::in);
fs.getline(buf, sizeof(buf) ); /* read one line first */
int haha = atol(buf);
交通大學資訊工程學系 蔡文能
6-第42頁
Java
Java Collection Framework
More about I/O : Java
Read an Integer
Java
Use BufferedReader
 Stream 要先轉為 Reader: InputStreamReader
 把Reader 丟給BufferedReader 包起來
Use readLine( ) in BufferedReader
Use ???.parse??? ( Double.parseDouble( yourString ) );
 i.e., methods in class wrapper
Use StringTokenizer
 To parse string contains several tokens
交通大學資訊工程學系 蔡文能
6-第43頁
Java
Java Collection Framework
Example: using BufferedReader
InputStreamReader isr = new InputStreamReader(System.in);
/* 鍵盤是以 byte 為單位的 Stream */
BufferedReader br = new BufferedReader(isr);
/* BufferedReader 的 constructor 只接受 Reader */
/* 所以不能直接把 System.in 丟給它 */
String stmp = br.readLine( ); /* 讀入一整列 */
long x = Long.parseLong(stmp); /* if it is a long */
/* 使用 class wrapper */
double x = Double.parseDouble(stmp); /* if double */
一列有多項輸入則可使用 StringTokenizer
交通大學資訊工程學系 蔡文能
6-第44頁
Java
Java Collection Framework
StringTokenizer (1/3)
交通大學資訊工程學系 蔡文能
6-第45頁
Java
Java Collection Framework
StringTokenizer (2/3)
import java.io.*;
import java.util.*;
public class Test {
InputStreamReader isr= new InputStreamReader(System.in);
BufferedReader b = new BufferedReader(isr);
public static void main ( String p[ ] ) throws Exception { new Test( ); }
Test( ) throws Exception {
System.out.print("In: "); String x = b.readLine();
System.out.println("Got "+ x);
StringTokenizer s = new StringTokenizer(x, " ,\t" );
while(s.hasMoreTokens( ) ){
System.out.println(s.nextToken( ));
}
System.out.println("======");
}
}
交通大學資訊工程學系 蔡文能
6-第46頁
Java
StringTokenizer (3/3)
Java Collection Framework
System.out.print("\r\nYour 三圍, 空白或逗號隔開: ");
String tmps = b.readLine();
StringTokenizer s = new StringTokenizer(tmps, " ,\t");
int kk=0; round[2] = round[1] = round[0] =0;
try{ while(s.hasMoreTokens () ) {
round[ kk++ ] = Double.parseDouble( s.nextToken() );
if(kk > 3 ) break;
}
} catch (Exception e)
{ System.out.println("Missing "+ (4-kk) + " round"); kk=3;}
if(kk < 3 ) { System.out.println("Missing "+ (3-kk) + " round");}
System.out.println("===Thank you!===");
PrintStream myoo = System.out;
myoo.println("\r\n=== Your Name is " + name);
myoo.println("Height = " + height + " \t" + "Weight = " + wet);
myoo.print("Three circle(三圍)== "); DecimalFormat dd = new
DecimalFormat("####0.00"); myoo.print( dd.format( round[0] ) );
myoo.print( " , " + dd.format( round[1] ) +" , "+ dd.format(round[2]) );
myoo.println("\r\n====== ====== ======");
交通大學資訊工程學系 蔡文能
6-第47頁
Java
Java Collection Framework
java.util.Arrays (1/2)
A utility class that provides static methods for dealing with arrays.
Works for arrays of numbers, Strings, (and “comparable” Objects)
Static methods that act on Java arrays:





sort
binarySearch
equals
fill
asList - returns an ArrayList composed of this array's
contents
交通大學資訊工程學系 蔡文能
6-第48頁
Java
Java Collection Framework
java.util.Arrays (2/2)
Example of using Arrays:
int pos = Arrays.binarySearch (arr, target);
Arrays.sort (arr);
Arrays.sort (arr, from, to);
Arrays.fill (arr, value); // fills arr with a given value
Arrays.fill (arr, from, to, value);
交通大學資訊工程學系 蔡文能
6-第49頁
站在巨人肩牓上
Java
Java Collection Framework
Java 的 java.util.Arrays.sort( )
Sort array of any Objects
 可透過該物件的 compareTo( ), 當然該 class 須 implements
java.lang.Comparable
 也可透過傳給 sort 一個 Comparator 物件, 就是某個有 implement
java.util.Comparator 之 class 的實體物件; 注意 Java 沒辦法把函數
當作參數傳!!!; 可善用 Collections.reverseOrder( )
Sort array of primitive types
 只能 sort 成自然序 (Ascending order)! 那要 Descending order 怎辦?
Java 不可以把函數當作參數!
java.util.Arrays.sort( ) 要傳 Comparator 物件?
不傳則會用要被 sort 之 array 的物件內的 compareTo( )
不論是 compareTo( ), 還是Comparator 內的 compare( ) 都是類似
C 的 qsort 用的比較函數, int, 要傳回 -1, 0, 1
注意 C++ STL 的是須傳回 true 與 false ( seeprevious slide)
交通大學資訊工程學系 蔡文能
6-第50頁
Java
Java Collection Framework
Sort utilities in C, C++, Java (1/2)
qsort( ) in C Library
 A compare function with 2 pointers as parameters is required for qsort( )
 The compare function has to return -1, 0, 1 to indicate that the first param
less than, equale to, greater than 2nd param
sort( ) in C++ STL
 default compare function bool operator<(first, second)
 Can use other compare function bool comp(first, second)
 Can use a comparator with bool operator(Obj a, Obj b)
java.util.Arrays.sort( )
 Can use compareTo( ) if implements java.lang.Comparable
 Can use a Comparator with compare( ) if NOT array of primitives
 int compareTo( ), int compare( ) ALL have to return -1, 0, 1 to indicate
that the first param less than, equale to, greater than 2nd param
交通大學資訊工程學系 蔡文能
6-第51頁
Java
Java Collection Framework
Sort utilities in C, C++, Java (2/2)
Stable sort ?
 Stable means that if two object resolve to the same value,
their relative orders in the list are guaranteed to be the same
as they were sorted before.
qsort( ) in C Library is NOT stable
 Quick sort is NOT stable, but it can be implemented as a
stable sort. While merge sort is stable.
sort( ) in C++ STL is NOT stable; However,
stable_sort( ) is a stable sort.
java.util.Arrays.sort( ) is a stable sort
交通大學資訊工程學系 蔡文能
6-第52頁
Java
Java Collection Framework
C++ STL <algorithm>
站在巨人肩牓上
#include <algorithm>
using namespace std;
int x[ ] = { 38, 49, 15, 158, 25, 58, 88,66 }; // array of primitive data
#define n (sizeof(x)/sizeof(x[0]))
//…
sort(x, x+n); // ascending order
// what if we want to sort into descending order
sort(x, x+n, sortfun); // with compare function
sort(y, y+k, sortComparatorObject); // with Comparator Object
Comparison function? Default: bool operator<(first, second)
C++ Comparison function 為bool
須傳回 true 代表 第一參數 < 第二參數 : ascending
Comparator 內要有 bool operator( ) (Obj a, Obj b) { /*…*/ }
http://www.cplusplus.com/reference/algorithm/sort/
交通大學資訊工程學系 蔡文能
6-第53頁
Java
qsort( ) is NOT Stable
Java Collection Framework
qsort( ) in C Library
There is a library function for quick sort in C Language:
qsort( ). (unstable)
站在巨人肩牓上
#include <stdlib.h>
void qsort(void *base, size_t num, size_t size,
int (*comp_func)(const void *, const void *) )
void * base --- a pointer to the array to be sorted
size_t num --- the number of elements
size_t size --- the element size
int (*cf) (…) --- is a pointer to a function used to compare
int comp_func( ) 必須傳回 -1, 0, 1 代表 <, ==, >
交通大學資訊工程學系 蔡文能
6-第54頁
Java
Java Collection Framework
java.util.Collections
public class Collections extends Object
This class consists exclusively of static methods that
operate on or return collections. It contains polymorphic
algorithms that operate on collections, "wrappers", which
return a new collection backed by a specified collection,
and a few other odds and ends.
The methods of this class all throw a NullPointerException
if the collections or class objects provided to them are null.
The documentation for the polymorphic algorithms
contained in this class generally includes a brief
description of the implementation.
交通大學資訊工程學系 蔡文能
6-第55頁
站在巨人的肩膀上
Java
Java Collection Framework
Java 的 java.util.Collections.sort( )
可sort 任何有implements java.util.Collection 的 container,當然該 class 須
implements java.lang.Comparable; 順序由該container 之元素的
compareTo( )決定
且可以配合 Comparator 以及 Collections.reverseOrder( )和
Collections.reverseOrder(Comparator)
請注意 java.util.Collections 是class, 但 java.util.Collection則是一個
interface, 幾乎所有的 Container class 都是 Collection, 細節請看
java.sun.com 的 JCF
java.util.Arrays 和 java.util.Collections 的 sort( ) function 都
是使用 Merge sort, 所以都是 Stable sort
C++ STL 的 sort( ) 採用 quick sort, 與 C 的 qsort( )都不是 stable
C++ STL 中另有其它是 Stable 的排序函數, 請參看C++ STL手冊
http://www.cplusplus.com/
交通大學資訊工程學系 蔡文能
6-第56頁
站在巨人的肩膀上
Java
Java Collection Framework
關於 List
C++
 C++ STL 的 <list> 是一個 double linked list, 不可以用
<algorithm> 內的 sort( ), 但 <list> 自己有實作一個 sort( ), 例如
list<int> gg; /*… */ 則之後可以用 gg.sort( ); 請看
www.cplusplus.com
Java
 Java 的 List 是一個 interface, 且它有 implements
java.util.Collection, 所以任何有 implements List 的container 都
可用 Collections.sort( )
 有 implement List 的主要 classes:
ArrayList, LinkedList, Vector
 Java 的 Stack 是 Vector, 所以 Stack 和 Vector 都是 List
交通大學資訊工程學系 蔡文能
6-第57頁
Java
Java Collection Framework
java.util.List Interface
The List library interface describes a list of objects in
abstract terms
In a list, objects are arranged in sequence
obj0, obj1, ..., objn-1
In Java, a list holds references to objects
A list can contain duplicate objects
(both obj1.equals(obj2) and obj1 == obj2 )
交通大學資訊工程學系 蔡文能
6-第58頁
Java
Java Collection Framework
List Methods (a Subset)
int size();
boolean isEmpty ();
boolean add (Object obj);
returns true
void add (int i, Object obj);
inserts obj as the
i-th value; i must
be from 0 to size()
Object set(int i, Object obj);
Object get(int i);
Object remove(int i);
boolean contains(Object obj);
int indexOf(Object obj);
交通大學資訊工程學系 蔡文能
i must be from 0 to
size() -1
use equals to
compare objects
6-第59頁
Java
Java Collection Framework
List Implementations
ArrayList
 a resizable-array implementation like Vector
unsynchronized, and without legacy methods
LinkedList
 a doubly-linked list implementation
 May provide better performance than ArrayList
if elements frequently inserted/deleted within the List
 For queues and double-ended queues (deques)
Vector
 a synchronized resizable-array implementation of a List
with additional "legacy" methods.
交通大學資訊工程學系
蔡文能
Copyright ?1998 Purple Technology, Inc.
1.0t
6-第60頁
60
Java
Java Collection Framework
java.util.ArrayList (1/6)
Implements List using an array
Keeps track of the list capacity (the length of the
allocated array) and list size (the number of
elements currently in the list)
capacity
size
"Cat" "Hat" "Bat"
交通大學資訊工程學系 蔡文能
6-第61頁
Java
Java Collection Framework
ArrayList (2/6)
Automatically increases (doubles) the capacity
when the list runs out of space; allocates a
bigger array and copies all the values into it
get(i) and set(i, obj) are efficient because an
array provides random access to its elements
Throws IndexOutOfBoundsException when
i < 0 or i  size()
交通大學資訊工程學系 蔡文能
6-第62頁
Java
Java Collection Framework
ArrayList (3/6)
ArrayList holds objects (of any type)
If you need to put ints or doubles into a list, use
a standard Java array or convert them into
Integer or Double objects
You have to remember what types of objects
your put into the list and may need to cast a
retrieved object back into its type
交通大學資訊工程學系 蔡文能
6-第63頁
Java
Java Collection Framework
ArrayList (4/6)
From Java API Docs:
JDK1.5: ArrayList(Collection<? extends E> c)
Constructs a list containing the elements of the
specified collection, in the order they are returned by
the collection's iterator.
交通大學資訊工程學系 蔡文能
6-第64頁
Java
Java Collection Framework
ArrayList (5/6)
Example 1
ArrayList list = new ArrayList ( );
list.add (new Integer(1));
list.add (new Integer(2));
list.add (new Integer(3));
int sum = 0;
for (int i = 0; i < list.size( ); i++)
sum += ((Integer) list.get(i)) . intValue();
Need a cast to Integer
in order to call intValue
交通大學資訊工程學系 蔡文能
6-第65頁
Java
Java Collection Framework
ArrayList (6/6)
Example 2
ArrayList words = new ArrayList (4);
words.add ("One");
words.add ("Fish");
words.add ("Two");
words.add ("Fish");
int i = 0;
while (i < words.size() )
{
if ( ”Fish".equals (words.get(i)) )
words.remove(i);
else
i++;
}
交通大學資訊工程學系 蔡文能
Shifts all the values
after the i-th to the left
and decrements the
size
6-第66頁
Java
Java Collection Framework
java.util.LinkedList (1/2)
• Easy access to first and last elements with methods.
void addFirst(Object obj)
Inserts the object obj at the
beginning of this list.
void addLast(Object obj)
Appends the object obj to the end of
this list.
Object getFirst()
Returns the first element in the list.
Object getLast()
Returns the first element in the list.
Object removeFirst()
Removes and returns the first element
from this list.
Object removeLast ()
Removes and returns the last element
from this list.
交通大學資訊工程學系 蔡文能
6-第67頁
Java
Java Collection Framework
java.util.LinkedList (2/2)
Linked list implementation of the List interface.
Implements all optional List operations, and permits all
elements (including null).
In addition to implementing the List interface, the
LinkedList class provides uniformly named methods to
get, remove and insert an element at the beginning and end
of the list. These operations allow linked lists to be used
as a stack, queue, or double-ended queue (deque).
Note that this implementation is not synchronized. If
multiple threads access a list concurrently, and at least one
of the threads modifies the list structurally, it must be
synchronized externally.
交通大學資訊工程學系 蔡文能
6-第68頁
Java
Java Collection Framework
java.util.LinkedList
交通大學資訊工程學系 蔡文能
6-第69頁
Java
交通大學資訊工程學系 蔡文能
Java Collection Framework
6-第70頁
Java
Java Collection Framework
java.util.AbstractList
交通大學資訊工程學系 蔡文能
6-第71頁
Java
Java Collection Framework
LinkedList vs. ArrayList
There is no difference in using ArrayList and LinkedList
They differ in the internal structure they use to implement the interface.
 The ArrayList class uses an array to manage data.
(搜尋速度較快)
 The LinkedList class uses a technique called linked-node representation.
(新增/刪除 element 較快)
To use the List interface, we declare the variable as List and assign an
instance of the class that implements the List interface to it:
List myList;
// . . .
myList = new ArrayList( );
// see example in next slides
交通大學資訊工程學系 蔡文能
6-第72頁
Java
Java Collection Framework
Example of using List (1/2)
import java.util.*;
//import java.util.ArrayList;
//import java.util.LinkedList;
//import java.util.Iterator;
public class ListTest
{
public static void main(String[] args)
{
ArrayList staff = new ArrayList();
// List staff = new LinkedList();
staff.add("Dick");
staff.add("Harry");
staff.add("Romeo");
staff.add("Tom");
printList(staff);
System.out.println(staff.get(2));
staff.set(2, "Karen");
printList(staff);
} // main(
交通大學資訊工程學系 蔡文能
// exclusive ..
// try this also
6-第73頁
Java
Java Collection Framework
Example of using List (2/2)
public static void printList(List staff)
{
System.out.println();
Iterator iter = staff.iterator();
while (iter.hasNext())
System.out.println(iter.next());
}// printList(
} // class
交通大學資訊工程學系 蔡文能
6-第74頁
Java
Java Collection Framework
Polymorphism (1/3)
Animal
Cat
Dog
Polymorphism? 剛才的
List例子已經用了!
Fox
Animal pet = new
newDog();
Dog();
Dog(
);
pet.cry( );
交通大學資訊工程學系 蔡文能
6-第75頁
Java
Java Collection Framework
Polymorphism (2/3)
Animal[] myPets
myPets[0] = new
myPets[1] = new
// …
myPets[3] = new
= new Animal[5];
Cat();
You can put any
Cat();
subclass of Animal in the
Animal array!
Dog();
for (int i = 0; i < myPets.length; i++) {
myPets[i].cry();
}
交通大學資訊工程學系 蔡文能
6-第76頁
Java
Java Collection Framework
Polymorphism (3/3)
List staff;
staff = new LinkedList();
staff.add(“Dick”); //add() in LinkedList
//…
//…
staff = new ArrayList();
staff.add("Harry"); //which add( ) ?
//...
交通大學資訊工程學系 蔡文能
6-第77頁
Java
Java Collection Framework
Generic Programming
Define software components with type parameters
 A sorting algorithm has the same structure, regardless of the types
being sorted
 Stack primitives have the same semantics, regardless of the
 objects stored on the stack.
Compile time parameters
Implementation
 Same code used for different parameter values
 Different code generated for different values
C++ model: template class
Java JDK1.5: type inference
交通大學資訊工程學系 蔡文能
6-第78頁
Generics
Java
Java Collection Framework
java.util.ArrayList in JDK1.5
public class ArrayList<E>
extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable,
java.io.Serializable
{
private transient E[] elementData;
private int size;
public ArrayList(Collection<? extends E> c) {
size = c.size();
// Allow 10% room for growth
elementData = (E[])new Object[
(int)Math.min((size*110L)/100,
Integer.MAX_VALUE)];
c.toArray(elementData);
}
//...
交通大學資訊工程學系 蔡文能
6-第79頁
Generics
Java
Java Collection Framework
java.util.ArrayList in JDK1.4
public class ArrayList
extends AbstractList
implements List, RandomAccess, Cloneable,
java.io.Serializable
{
private transient Object elementData[];
private int size;
public ArrayList(Collection c) {
size = c.size();
// Allow 10% room for growth
elementData = new Object[
(int)Math.min((size*110L)/100,
Integer.MAX_VALUE)];
c.toArray(elementData);
}
...
交通大學資訊工程學系 蔡文能
6-第80頁
Java
Java Collection Framework
JDK 1.5
交通大學資訊工程學系 蔡文能
6-第81頁
Java
Java Collection Framework
JDK 1.5
交通大學資訊工程學系 蔡文能
6-第82頁
Java
Java Collection Framework
LinkedList in JDK1.5 vs. JDK1.4
JDK1.4
public class LinkedList
extends AbstractSequentialList
implements List, Cloneable, Serializable
JDK1.5 (支援 Generic programming)
public class LinkedList<E>
extends AbstractSequentialList<E>
implements List<E>, Queue<E>, Cloneable, Serializable
交通大學資訊工程學系 蔡文能
6-第83頁
Java
Java Collection Framework
JDK 1.5
交通大學資訊工程學系 蔡文能
6-第84頁
Java
Java Collection Framework
JDK 1.4
交通大學資訊工程學系 蔡文能
6-第85頁
Java
Java Collection Framework
Interface Queue
JDK 1.5
java.util
public interface Queue <E> extends Collection <E>
Type Parameters:
 E - the type of elements held in this collection
All Known Implementing Classes:
AbstractQueue, ArrayBlockingQueue,
ConcurrentLinkedQueue, DelayQueue,
LinkedBlockingQueue, LinkedList,
PriorityBlockingQueue, PriorityQueue,
SynchronousQueue
Since:
 JDK 1.5
交通大學資訊工程學系 蔡文能
6-第86頁
Java
Java Collection Framework
Methods in Queue <E>
JDK 1.5
E element( )
Retrieves, but does not remove, the head of this queue.
boolean offer(E o)
Inserts the specified element into this queue, if possible.
E peek( )
Retrieves, but does not remove, the head of this queue,
returning null if this queue is empty.
E poll( )
Retrieves and removes the head of this queue, or null if
this queue is empty.
E remove ()
Retrieves and removes the head of this queue.
交通大學資訊工程學系 蔡文能
6-第87頁
Java
Java Collection Framework
JDK 1.5
交通大學資訊工程學系 蔡文能
6-第88頁
Java
Java Collection Framework
Set
interface Set extends Collection
An unordered collection of objects
No duplicate elements allowed
Same methods as Collection
 Semantics are different, so different interface needed for
design
Implemented by:
 HashSet, TreeSet
交通大學資訊工程學系
蔡文能
Copyright ?1998 Purple Technology, Inc.
1.0t
6-第89頁
89
Java
Java Collection Framework
Set Implementations
HashSet
 a Set backed by a hash table
TreeSet
 A balanced binary tree implementation
 Imposes an ordering on its elements
交通大學資訊工程學系
蔡文能
Copyright ?1998 Purple Technology, Inc.
1.0t
6-第90頁
90
Java
Java Collection Framework
Map
interface Map (does Not extend Collection)
An object that maps keys to values
Each key can have at most one value
Replaces java.util.Dictionary interface
Ordering may be provided by implementation class, but not
guaranteed
交通大學資訊工程學系
蔡文能
Copyright ?1998 Purple Technology, Inc.
1.0t
6-第91頁
91
Java
Java Collection Framework
Map Implementations
HashMap
 A hash table implementation of Map
 Like Hashtable, but supports null keys & values
TreeMap
 A balanced binary tree implementation
 Imposes an ordering on its elements
Hashtable
 Synchronized hash table implementation of Map
interface, with additional "legacy" methods.
交通大學資訊工程學系
蔡文能
Copyright ?1998 Purple Technology, Inc.
1.0t
6-第92頁
92
Java
Java Collection Framework
Legacy Containers
java.util.Vector
// 會長大的 array
java.util.Stack
// 堆疊, 先進後出的儲存區
Java.util.Dictionary // see below, from Reference
java.util.Hashtable // maps keys to values 的 table
java.util.Properties // a persistent set of properties
The Dictionary class is the abstract parent
of any class which maps keys to values.
交通大學資訊工程學系 蔡文能
6-第93頁
Java
Java Collection Framework
Vectors (1/5)
This class is in the java.util package
You make it available to your program with
import statement “import java.util.Vector” or
“import java.util.*” at the top of your program.
Intended for dynamic sizes of elements.
 Lets you add arbitrary objects to a list of objects
 E.g., addElement(x);
Reallocate the internal array when grows doubly
(or a constant factor).
交通大學資訊工程學系 蔡文能
6-第94頁
Java
Java Collection Framework
Vectors (2/5)
Performance: flexible and efficient
 Access time complexity: O(1)
 Time complexity for addElement(x):
Amortized for access: O(1)
Times of calling malloc(): O((log n)/n)
 Memory complexity: No more than 2 or constant times more.
 But,
Not efficient for removeElement().
Not so efficient because it uses synchronized.
 Sun internally uses a class named FastVector, without
synchronized.
Similarly, for StringBuffer and Hashtable.
 Note: for String, don’t concatenate strings in a loop!
交通大學資訊工程學系 蔡文能
6-第95頁
Java
Java Collection Framework
Vectors (3/5)
交通大學資訊工程學系 蔡文能
6-第96頁
Java
交通大學資訊工程學系 蔡文能
Java Collection Framework
Vectors (4/5)
6-第97頁
Java
Java Collection Framework
Vectors (5/5)
java.util.Vector
java.lang.Object
|
+ - - java.util.AbstractCollection
|
練習:
+ - - java.util.AbstractList
自己用 Vector 做出
|
Stack, 再用
+ - - java.util.Vector
LinkedList 做 Stack,
也用 array of Object
Direct Known Subclasses:
直接做 Stack 並試著
Stack
比較它們的特性
交通大學資訊工程學系 蔡文能
6-第98頁
Java
Java Collection Framework
Vector in JDK1.5 vs. JDK1.4
JDK1.4
public class Vector
extends AbstractList
implements List, RandomAccess, Cloneable, Serializable
JDK1.5 (support Generic type)
public class Vector<E>
extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, Serializable
交通大學資訊工程學系 蔡文能
6-第99頁
Java
Java Collection Framework
Stack
交通大學資訊工程學系 蔡文能
6-第100頁
Java
Java Collection Framework
javap java.util.Stack
交通大學資訊工程學系 蔡文能
6-第101頁
Java
Java Collection Framework
Stack in JDK1.5 vs. JDK1.4
JDK1.4
public class Stack
extends Vector
JDK1.5
public class Stack<E>
extends Vector<E>
交通大學資訊工程學系 蔡文能
6-第102頁
Java
Java Collection Framework
JDK 1.5
交通大學資訊工程學系 蔡文能
6-第103頁
Java
Java Collection Framework
java.util.Dictionary
public abstract class Dictionary {
abstract public int size();
abstract public boolean isEmpty();
abstract public Object get(Object key)
throws NullPointerException;
abstract public Object put(Object key, Object element)
throws NullPointerException;
abstract public Object remove(Object key)
throws NullPointerException;
abstract public Enumeration keys();
abstract public Enumeration elements();
}
交通大學資訊工程學系 蔡文能
6-第104頁
Java
Java Collection Framework
Hashtable (1/4)
Implements a hashtable in Java
Hashtable has keys and values
Key
“Joe”
“Fred”
“Heather”
Value
employee object
employee object
employee object
參考所給的聊天室範例程式中如何使用 Hashtable
交通大學資訊工程學系 蔡文能
6-第105頁
Java
Java Collection Framework
Hashtable (2/4)
交通大學資訊工程學系 蔡文能
6-第106頁
Java
Java Collection Framework
Hashtable (3/4)
A Hashtable can be used to quickly look up an
object associated with a key.
The key uses the hashcode( ) method for fast
access
get( ) and put( ) are used to add and remove
objects from the Hashtable
elements( ) returns an Enumeration object that
lets you cycle through the Hashtable
參考所給的聊天室範例程式中如何使用 Hashtable
交通大學資訊工程學系 蔡文能
6-第107頁
Java
Java Collection Framework
Hashtable (4/4)
HashMap 是另一種 Hash table
交通大學資訊工程學系 蔡文能
6-第108頁
Java
Java Collection Framework
Properties
Properties 是特殊 HashTable
交通大學資訊工程學系 蔡文能
6-第109頁
Java
Java Collection Framework
Properties
The Properties class itself provides methods for the following:





Loading key/value pairs into a Property object from a stream
Retrieving a value from its key
Listing the keys and their values
Enumerating over the keys
Saving the properties to a stream
Properties extends the Hashtable class:







Testing to see if a particular key or value is in the Properties object.
Getting the current number of key/value pairs.
Removing a key and its value.
Adding a key/value pair to the Properties list.
Enumerating over the values or the keys.
Retrieving a value by its key.
Finding out if the Properties object is empty.
Important to be used as something like configuration files or *.ini files.
交通大學資訊工程學系 蔡文能
6-第110頁
Java
Java Collection Framework
The Life Cycle of Program's Properties
交通大學資訊工程學系 蔡文能
6-第111頁
Java
Java Collection Framework
Loading from FileInputStream
Setting Up Your Properties Object
 loading the default properties and loading the remembered
properties:
. . .
// create and load default properties
Properties defaultProps = new Properties();
FileInputStream in = new
FileInputStream("defaultProperties");
defaultProps.load(in);
in.close();
// create program properties with default
Properties applicationProps = new Properties(defaultProps);
// now load properties from last invocation
in = new FileInputStream("appProperties");
applicationProps.load(in);
in.close();
. . .
交通大學資訊工程學系 蔡文能
6-第112頁
Java
Java Collection Framework
Saving properties to FileOutputStream
 The following example writes out the
application properties from the previous
example using Properties's save method. The
default properties don't need to be saved each
time because they never change.
FileOutputStream out =
new FileOutputStream("appProperties");
applicationProps.save(out, "---No Comment---");
out.close();
交通大學資訊工程學系 蔡文能
6-第113頁
Java
Java Collection Framework
Properties Methods (1/2)
 getProperty(String key)
 getProperty(String key,String default)
Returns the value for the specified property. The second version allows you to
provide a default value. If the key is not found, the default is returned.
 list(PrintStream s)
 list(PrintWriter w)
Writes all of the properties to the specified stream or writer. This is useful for
debugging.
 elements()
 keys()
 propertyNames()
Returns an Enumeration containing the keys or values (as indicated by the
method name) contained in the Properties object.
 size()
Returns the current number of key/value pairs.
交通大學資訊工程學系 蔡文能
6-第114頁
Java
Java Collection Framework
Properties Methods (2/2)
 contains(Object value)
 containsKey(Object key)
Returns true if the value or the key is in the Properties object.
Properties inherits these methods from Hashtable. Thus they
accept Object arguments. You should pass in Strings.
 put(Object key, Object value)
Puts the key/value pair in the Properties object.
 remove(Object key)
Removes the key/value pair associated with key.
Both put and remove come from Hashtable and thus take
Objects.
交通大學資訊工程學系 蔡文能
6-第115頁
Java
Java Collection Framework
Properties File Format
Each of the following lines specifies:
 Key: "Truth"; Value: "Beauty".
Truth = Beauty
Truth:Beauty
Truth
:Beauty
The following three lines specify a single property:
fruits
apple, banana, pear, \
cantaloupe, watermelon, \
kiwi, mango
The empty string:
cheese
交通大學資訊工程學系 蔡文能
6-第116頁
Java
Java Collection Framework
Using Properties to Manage
Program Attributes
An attribute has two parts: a name and a value.
For example
 "os.name" is the name for one of the Java platform's system
attributes.
 Its value contains the name of the current operating system, such as
“Linux".
Many subsystems use properties files to set default
properties. E.g.,





System
Resource bundling
Security manager
Servlet
JSP
交通大學資訊工程學系 蔡文能
6-第117頁
Java
Java Collection Framework
System Properties
Key
"file.separator"
"java.class.path"
"java.class.version"
"java.home"
"java.vendor"
"java.vendor.url"
"java.version"
"line.separator"
"os.arch"
"os.name"
"os.version"
"path.separator"
"user.dir"
"user.home"
"user.name"
交通大學資訊工程學系 蔡文能
Meaning
File separator (for example, "/")
Java classpath
Java class version number
Java installation directory
Java vendor-specific string
Java vendor URL
Java version number
Line separator
Operating system architecture
Operating system name
Operating system version
Path separator (for example, ":")
User's current working directory
User home directory
User account name
6-第118頁
Java
Java Collection Framework
Reading System Properties
Reading System Properties
 The System class has two methods to read the system
properties: getProperty and getProperties.
The simpler version of getProperty :
System.getProperty("path.separator");
Another version requires two String arguments:
 First argument is the key to look up.
 The second argument is a default value to return if the key cannot be
found or if it has no value.
System.getProperty("subliminal.message", "Buy Java Now!");
The getProperties method returns a Properties object.
 Use the various Properties class methods to query the
Properties objects for specific values or to list the entire set
of properties.
交通大學資訊工程學系 蔡文能
6-第119頁
Java
Java Collection Framework
Writing System Properties
Writing System Properties
 System's setProperties method takes a Properties
object that has been initialized to contain the key/value pairs for
the properties that you want to set.
 Example:
myProperties.txt :
subliminal.message=Buy Java Now!
 Changing the system properties within an application will not
effect future invocations of the Java interpreter for this or any other
application.
java.vendor=Acme Software Company
交通大學資訊工程學系 蔡文能
6-第120頁
Java
Java Collection Framework
// PropertiesTest.java
import java.io.FileInputStream;
import java.util.Properties;
public class PropertiesTest {
public static void main(String[] args) throws Exception {
// set up new properties object
// from file "myProperties.txt”
FileInputStream propFile =
new FileInputStream("myProperties.txt");
Properties p = new Properties(System.getProperties());
p.load(propFile);
// set the system properties
System.setProperties(p);
// display new properties
System.getProperties().list(System.out); //to screen
}
}
交通大學資訊工程學系 蔡文能
6-第121頁
Java
Java Collection Framework
Timers
A Timer will internally launch a new thread, but
handle most of the work for you.
A Timer will call a method when its interval expires.
Timers should be performing quick tasks, such as
updating simple state. Otherwise its next interval may expire
before it finishes, and the timer will become backlogged (bad)!
Common Uses for Timers
 Timed events or scheduled updates
 Delay events for a specified time
 Animation
Java has two Timer classes :
java.util.Timer and javax.swing.Timer
交通大學資訊工程學系 蔡文能
6-第122頁
Java
Java Collection Framework
Using Timer
Important timer methods:
 Constructor
public Timer(int ms_delay, ActionListener al)
 To start the Timer: public void start( )
 To stop the Timer: public void stop( )
 To schedule: public void schedule(TimerTask, long, long);
How it works?
 Once a timer has started, it will call the
ActionListener’s ActionPerformed( ) method
each time its interval expires.
交通大學資訊工程學系 蔡文能
6-第123頁
Java
Java Collection Framework
Using TimerTask and Timer
import java.util.*;
public class TestGGYY {
static class GG extends TimerTask {
public void run( ){System.out.println("Ggg ");}
}
static class YY extends TimerTask {
public void run( ){System.out.println("Yyy ");}
}
public static void main(String[ ] xxx){
GG haha=new GG( );
YY heee=new YY( );
Timer t=new Timer( );
t.scheduleAtFixedRate(haha, 0, 333);
t.scheduleAtFixedRate(heee, 800, 1000);
}
} // class
交通大學資訊工程學系 蔡文能
6-第124頁
Java
Java Collection Framework
java.util.*
謝謝捧場
http://www.csie.nctu.edu.tw/~tsaiwn/oop/
蔡文能
交通大學資訊工程學系 蔡文能
6-第125頁