Presentation is loading. Please wait.

Presentation is loading. Please wait.

Java.util Nam Sedong May 12, 1997.

Similar presentations


Presentation on theme: "Java.util Nam Sedong May 12, 1997."— Presentation transcript:

1 java.util Nam Sedong May 12, 1997

2 package java.util( jdk ). Interface. Enumeration. EventListener. Observer. Class Index. BitSet. Calendar. Date. Dictionary. EventObject. GregorianCalendar. Hashtable. ListResourceBundle. Locale. Observable. Properties. PropertyResourceBundle. Random. ResourceBundle. SimpleTimeZone. Stack. StringTokenizer. TimeZone. Vector. Exception Index. EmptyStackException. MissingResourceException. NoSuchElementException. TooManyListenersException

3 Hierarchy( jdk 1.0 ) Object interface Enumeration BitSet Date Dictionary Hashtable Properties Observable Interaface Observer Random StringTokenizer Vector Stack Throwable Exception RuntimeException EmptyStackException NoSuchElementException

4 Interface Enumeration 1/2 public interface Enumeration { public boolean hasMoreElements(); public Object nextElement() throws NoSuchElementException; }

5 Interface Enumeration 2/2 import java.lang.Integer; import java.util.Enumeration; import java.util.Vector; class Vector1 { public static void main( String args[] ) { Vector v = new Vector( 10, 10 ); for( int i = 0; i < 20; i ++ ) v.addElement( new Integer( i ) ); System.out.println( "Vector in original order using an Enumeration" ); for( Enumeration e = v.elements( ); e.hasMoreElements( ); ) System.out.print( e.nextElement( ) + " " ); System.out.println( ); System.out.println( "Vector in original order using an Enumeration" ); for( int i = 0; i < v.size( ); i++ ) System.out.print( v.elementAt( i ) + " " ); System.out.println( ); System.out.println("Vector as a String"); System.out.println( v.toString( ) ); }

6 class BitSet 1/5 public final class BitSet implements Cloneable { public BitSet(); public BitSet(int nbits); public String toString(); public boolean equals(Object obj) public int hashCode(); public Object clone(); public boolean get(int bitIndex); public void set(int bitIndex); public void clear(int bitIndex); public void and(BitSet set); public void or(BitSet set); public void xor(BitSet set); public int size(); } clone(), equals(), toString() and hashCode() overrides the methods of java.lang.Object all bits initially false grows dynamically

7 class BitSet 2/5 import java.io.DataInputStream; import java.util.BitSet; class BitSet1 { public static void main( String args[ ] ) throws java.io.IOException { DataInputStream dis = new DataInputStream( System.in ); String bitstring; BitSet set1, set2, set3; set1 = new BitSet( ); set2 = new BitSet( ); // Get the first bit sequence and store it System.out.println( "Bit sequence #1: " ); bitstring = dis.readLine( ); for ( short i = 0; i < bitstring.length( ); i ++ ) { if ( bitstring.charAt( i ) == '1' ) set1.set( i ); else set1.clear( i ); } // Get the second bit sequence and store it System.out.println( "Bit sequence #2: " ); bitstring = dis.readLine( ); for ( short i = 0; i < bitstring.length( ); i ++ ) { if ( bitstring.charAt( i ) == '1' ) set2.set( i ); else set2.clear( i ); }

8 class BitSet 3/5 System.out.println( "BitSet #1: " + set1 ); System.out.println( "BitSet #2: " + set2 ); // Test the AND operation set3 = ( BitSet) set1.clone(); set3.and( set2 ); System.out.println( "set1 AND set2: " + set3 ); // Test the OR operation set3 = ( BitSet) set1.clone(); set3.or( set2 ); System.out.println( "set1 OR set2: " + set3 ); // Test the AND operation set3 = ( BitSet) set1.clone(); set3.xor( set2 ); System.out.println( "set1 XOR set2: " + set3 ); }

9 class BitSet 4/5 gura:~/Java/Java_Language/Unleashed/19> java BitSet1 Bit sequence #1: Bit sequence #2: BitSet #1: {0, 3, 5} BitSet #2: {0, 1, 2, 4, 5} set1 AND set2: {0, 5} set1 OR set2: {0, 1, 2, 3, 4, 5} set1 XOR set2: {1, 2, 3, 4} gura:~/Java/Seminar> java BitSetSize set1 : {} size of set1 64 Bit sequence #1: set1 : {0, 2, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 69, 70, 71, 72, 74} size of set1 128 Size grow as 64, 128, 256,... for my experience. And it’s true in HashTable class.

10 class BitSet 5/5 - etc How these work? System.out.println( "BitSet #1: " + set1 ); System.out.println( "BitSet #2: " + set2 ); toString() method. System.out.print(int i) The string printed is the same as that returned by the toString method of the Double class when invoked on the given double value.. System.out.print(Object o) The string printed is the same as that returned by the given object's toString method.. System.out.print(String s). public String toString() It is recommendedthat all subclasses override this method.

11 class Random 1/4 public class Random { protected long seed; protected double nextNextGaussian; protected boolean haveNextNextGaussian = false; public Random(); public Random(long seed); public void setSeed(long seed); protected int next(int bits); public int nextInt(); public long nextLong(); public float nextFloat(); public double nextDouble(); public double nextGaussian(); }

12 class Random 2/4. two Random Objects created with the same seed.. machine independancy. methods public Random() { this(System.currentTimeMillis()); } public Random(long seed) { setSeed(seed); } synchronized public void setSeed(long seed) { this.seed = (seed ^ 0x5DEECE66DL) & ((1L << 48) - 1); haveNextNextGaussian = false; } synchronized protected int next(int bits) { seed = (seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1); return (int)(seed >>> (48 - bits)); } public int nextInt() { return next(32); } public long nextLong() { return ((long)next(32) << 32) + next(32); } public float nextFloat() { return next(24) / ((float)(1 << 24)); }

13 class Random 3/4 public double nextDouble() { return (((long)next(26) << 27) + next(27)) / (double)(1L << 53); } 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; }

14 class Random 4/4 import java.lang.Math; import java.util.Date; import java.util.Random; class Random1 { public static void main( String args[ ] ) { Random rand = new Random( ); System.out.println( "Uniform Random Integers" ); for ( int i = 0; i < count; i ++ ) System.out.print( rand.nextInt( ) + " " ); System.out.println( ); } gura:~/Java/Seminar/java.lang.util> java Random gura:~/Java/Seminar/java.lang.util> java Random

15 class StringTokenizer 1/5 public class StringTokenizer implements Enumeration { public StringTokenizer(String str, String delim, boolean returnTokens); public StringTokenizer(String str, String delim); public StringTokenizer(String str); public boolean hasMoreTokens(); public String nextToken(); public String nextToken(String delim); public boolean hasMoreElements(); public Object nextElement(); public int countTokens(); } much simpler than java.io.StreamTokenizer

16 class StringTokenizer 2/5 import java.io.DataInputStream; import java.util.StringTokenizer; class StringTokenizer1 { public static void main( String args[] ) throws java.io.IOException { DataInputStream dis = new DataInputStream( System.in ); System.out.println( "Enter a sentence: " ); String s = dis.readLine( ); StringTokenizer st = new StringTokenizer( s ); while( st.hasMoreTokens( ) ) System.out.println( st.nextToken( ) ); } gura:~/Java/Seminar/java.lang.util> java StringTokenizer1 Enter a sentence: Write Once, Run Anywhere Write Once, Run Anywhere

17 class StringTokenizer 3/5 import java.io.DataInputStream;... class StringTokenizer2 {... StringTokenizer st = new StringTokenizer( s, "," );... gura:~/Java/Seminar/java.lang.util> java StringTokenizer2 Enter a sentence: Write Once, Run Anywhere Write Once Run Anywhere gura:~/Java/Seminar/java.lang.util> java StringTokenizer2 Enter a sentence: Write Once,,,,,,, Run Anywhere Write Once Run Anywhere

18 class StringTokenizer 4/5 gura:~/Java/Seminar/java.lang.util> javac StringTokenizer3.java StringTokenizer3.java:10: No constructor matching StringTokenizer(java.lang.String, java.lang.String, int) found in class java.util.StringTokenizer. StringTokenizer st = new StringTokenizer( s, ",", 1 ); ^ 1 error Why error occured? gura:~/Java/Seminar/java.lang.util> java StringTokenizer3 Enter a sentence: Write Once,,,,,,, Run Anywhere Write Once, Run Anywhere

19 class StringTokenizer 5/5. countTokens( ) tokens in the String after the current position.. nextElement( ) exactly the same behavior as nextToken( ). hasMoreElement( ) exactly the same behavior as hasMoreToken( )

20 class Vector 1/4 public class Vector implements Cloneable { protected Object[] elementData; protected int elementCount; protected int capacityIncrement; public Vector(int initialCapacity, int capacityIncrement); public Vector(int initialCapacity); public Vector(); public final String toString(); public Object clone(); public final Object elementAt(int index) throws IndexOutOfBoundsException; public final void setElementAt(Object obj, int index) throws IndexOutOfBoundsException; public final Object firstElement() throws NoSuchElementException; public final Object lastElement() throws NoSuchElementException; public final void addElement(Object obj); public final void insertElementAt(Object obj, int index) throws IndexOutOfBoundsException; public final boolean removeElement(Object obj); public final void removeElementAt(int index) throws IndexOutOfBoundsException; public final void removeAllElements(); public final boolean isEmpty(); public final int size(); public final void setSize(int newSize); public final int capacity(); public final void ensureCapacity(int minCapacity);

21 class Vector 2/4 public final void trimToSize(); public final void copyInto(Object anArray[]) throws IndexOutOfBoundsException; public final Enumeration elements(); public final boolean contains(Object elem); public final int indexOf(Object elem); public final int indexOf(Object elem, int index) throws IndexOutOfBoundsException; public final int lastIndexOf(Object elem); public final int lastIndexOf(Object elem, int index) throws IndexOutOfBoundsException; }

22 class Vector 3/4 import java.lang.Integer; import java.util.Enumeration; import java.util.Vector; class Vector1 { public static void main( String args[] ) { Vector v = new Vector( 10, 10 ); for( int i = 0; i < 20; i ++ ) v.addElement( new Integer( i ) ); System.out.println( "Vector in original order using an Enumeration" ); for( Enumeration e = v.elements( ); e.hasMoreElements( ); ) System.out.print( e.nextElement( ) + " " ); System.out.println( ); System.out.println( "Vector in original order using an Enumeration" ); for( int i = 0; i < v.size( ); i++ ) System.out.print( v.elementAt( i ) + " " ); System.out.println( ); System.out.println("Vector as a String"); System.out.println( v.toString( ) ); } Vector in original order using an Enumeration Vector in original order using an Enumeration Vector as a String [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

23 class Vector 4/4 gura:~/Java/Seminar/java.util> java Vector2 [] [5] [5, true, 10, false, def, true, ghi] 9 [5, true, 10, false, true, ghi] 6 8 [5, true, 10, false, true, ghi, false, false] 8

24 class Stack 1/3 public class Stack extends Vector { public Object push(Object item); public Object pop() throws EmptyStackException; public Object peek() throws EmptyStackException; public boolean empty(); public int search(Object o); }

25 class Stack 2/3 import java.io.DataInputStream; import java.util.Stack; import java.util.StringTokenizer; class Stack1 { public static void main( String args[ ] ) throws java.io.IOException { DataInputStream dis = new DataInputStream( System.in ); System.out.println( "Enter a sentence: " ); String s = dis.readLine( ); StringTokenizer st = new StringTokenizer( s ); Stack stack = new Stack( ); while( st.hasMoreTokens( ) ) stack.push( st.nextToken( ) ); // modified System.out.println( stack.peek( ) ); System.out.println( stack.firstElement( ) ); while( ! stack.empty( ) ) System.out.print( ( String ) stack.pop( ) + " " ); System.out.println( ); }

26 class Stack 3/3 gura:~/Java/Seminar/java.util> java Stack1 Enter a sentence: I am dgtgrade dgtgrade I dgtgrade am I

27 class Observable 1/5 public interface Observer { public void update(Observable o, Object arg); } public class Observable { public void addObserver(Observer o); public void deleteObserver(Observer o); public void deleteObservers(); public int countObservers(); public void notifyObservers(); public void notifyObservers(Object arg); protected void setChanged(); protected void clearChanged(); public boolean hasChanged(); } one Observalble objects with mutiple Observer Smalltalk Model-View-Controller

28 class Observable 2/5 notifyObservers() if ( hasChanged() ) equivalent to notifyObservers( null ) clearChanged()

29 class Observable 3/5 import java.awt.*; import java.util.*; // ObservableInt - an integer Observable // This class implements the Observable mechanism for a simple int variable. // You can set the value with setValue( int ) and int getValue( ) returns the // current value. public class ObservableInt extends Observable { int value; // The value everyone wants to observe public ObservableInt( ) { value = 0; // By default, let value be 0 } public ObservableInt( int newValue ) { value = newValue; // Allow value to be set when created } public synchronized void setvalue( int newValue ) { // Check to see that this call is REALLY changing the value if ( newValue != value ) { value = newValue; setChanged( ); // Mark this class as "changed" notifyObservers( ); // Tell the observers about it }

30 class Observable 4/5 } public synchronized int getValue( ) { return value; }

31 class Observable 5/5 import java.awt.*; import java.util.*; // // IntLabel - a Label that displays the value of an ObservableInt. public class IntLabel extends Label implements Observer { private ObservableInt intValue; // The value we're observing public IntLabel( ObservableInt theInt ) { intValue = theInt; // Tell intValue we're interested in it intValue.addObserver( this ); // Initialize the label to the current value of intValue setText( "" + intValue.getValue( ) ); } // Update will be called whenever intValue is changed, so just update the // label text. public void update( Observable obs, Object arg ) { setText( "" + intValue.getValue( ) ); }

32 Class Date 1/4 public class Date { public Date(); public Date(long time);... Date : + 3 Classes public Date(String s) throws IllegalArgumentException; public String toString(); public boolean equals(Object obj); public int hashCode(); public int getYear(); public void setYear(int year); public int getMonth(); public void setMonth(int month); public int getDate(); public void setDate(int date); public int getDay(); public int getHours(); public void setHours(int hours); public int getMinutes(); public void setMinutes(int minutes); public int getSeconds(); public void setSeconds(int seconds); public long getTime(); public void setTime(long time); public boolean before(Date when); public boolean after(Date when); public String toLocaleString(); public String toGMTString(); public int getTimezoneOffset(); public static long UTC(int year, int month, int date, int hours, int minutes, int seconds); public static long parse(String s) throws IllegalArgumentException; }

33 Class Date 2/4 Date() current time toString() dow mon dd hh:mm:ss zzz yyyy toGMTString() d mon yyyy hh:mm:ss GMT d : one or two decimal digits total length : 23 or 24 GMT = UT getTimezoneOffset() (this.getTime() - UTC(this.getYear(),..., this.getSeconds())) / (60 * 1000) parse GMT-5, utc+0430, AM, PM, JANUARY, SUNDAY, EST PST

34 class Date 3/4 import java.util.Date; public class MyDate { public static void main( String args[ ] ) { Date Date1 = new Date( 96, 1, 14 ); Date Date2 = new Date( 97, 5, 19 ); Date Date3 = new Date( 96, 5, 1 ); System.out.println( Date1.getTimezoneOffset() ); System.out.println( Date2.getTimezoneOffset() ); System.out.println( Date3.getTimezoneOffset() ); } gura:~/Java/Seminar/java.util> java MyDate

35 class Date 4/4 almost deprecated save for toString() hashCode() getTime() after(Date) before(Date) equals(Date) Date(long) Date() class java.util.Calendar –class java.util.GregorianCalendar future : Lunar Calendar class java.util.TimeZone class java.util.SimpleTimeZone –public class SimpleTimeZone extends TimeZone SimpleTimeZone is a concrete subclass of TimeZone that represents a time zone for use with a Gregorian calendar. class java.text.DateFormat ( subclass of java.text.Format )

36 class Calendar 1/3 Constructor Calendar() Constructs a Calendar with the default time zone as returned by TimeZone.getDefault(), and the default locale. Calendar(TimeZone, Locale) Constructs a Calendar with the given time zone and locale. Methods add(int, int) after(Object) before(Object) clear() clear(int) clone() complete() Fills in any unset fields in the time field list. computeFields() Converts UTC as milliseconds to time field values. computeTime() Converts Calendar's time field values to UTC as milliseconds. equals(Object) get(int) getAvailableLocales() getFirstDayOfWeek() getGreatestMinimum(int) getInstance()... getInstance : + 3 Classes getLeastMaximum(int)...

37 class Calendar 2/3 isLenient() Tell whether date/time interpretation is to be lenient. isSet(int) Determines if the given time field has a value set. roll(int, boolean) Time Field Rolling function. set(int, int) Sets the time field with the given value.... set : + 3 Classes setFirstDayOfWeek(int) Sets what the first day of the week is; e.g., Sunday in US, Monday in France.... : 3 Classes setTime(Date) Sets this Calendar's current time with the given Date. setTimeInMillis(long) Sets this Calendar's current time from the given long value. setTimeZone(TimeZone) Sets the time zone with the given time zone value.

38 class Calendar 3/3 public static final int MINUTE Useful constant for date and time. Used in time fields. public static final int SECOND Useful constant for date and time. Used in time fields. public static synchronized Calendar getInstance(TimeZone zone, Locale aLocale)

39 class Dictionary 1/3 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(); }

40 class Dictionary 2/3 Key Value Widget 124 Gadget 754 FooBar 383 Wadget 843 Dongle 543 Snippet Pseudo-code Dictionary products = new Dictionary( ); products.put( new Integer( 342 ), "Widget" ); products.put( new Integer( 124 ), "Gadget" ); products.put( new Integer( 754 ), "FooBar" ); returns null when to indicate events such as being unable to find a paricular entry, so neither the key nor its element may be null.

41 class Dictionary 3/3 Class java.lang.Integer java.lang.Object | +----java.lang.Number | +----java.lang.Integer public final class Integer extends Number The Integer class wraps a value of the primitive type int in an object. An object of type Integer contains a single field whose type is int. In addition, this class provides several methods for converting an int to a String and a String to an int, as well as other constants and methods useful when dealing with an int.

42 class Hashtable 1/3 public class Hashtable extends Dictionary implements Cloneable { public Hashtable(int initialCapacity, float loadFactor); public Hashtable(int initialCapacity); public Hashtable(); public String toString(); public Object clone(); public int size(); public boolean isEmpty(); public Object get(Object key) throws NullPointerException; public Object put(Object key, Object value) throws NullPointerException; public Object remove(Object key) throws NullPointerException; public Enumeration keys(); public Enumeration elements(); public boolean contains(Object value); public boolean containsKey(Object key); protected void rehash(); public void clear(); }

43 class Hashtable 2/3 automatically grows a new capacity roughly double the current one a capacity is a prime number efficiency loadFactor use containgKey( ), not contains( ) for higher efficiency loadFactor must be lower than 0.5 for higher efficiency ( if memory is sufficent ) protected rehash( ) increases the capacity

44 class Hashtable 3/3 import java.io.DataInputStream; import java.lang.Integer; import java.lang.Math; import java.util.Random; import java.util.Hashtable; class Hashtable1 { public static void main( String args[] ) throws java.io.IOException { DataInputStream dis = new DataInputStream( System.in ); int numElements = 10; String keys[ ] = { "Red", "Green", "Blue", "Cyan", "Magenta", "Yellow", "Black", "Orange", "Purple", "White" }; Hashtable ht; Random randGen = new Random( ); ht = new Hashtable( numElements * 2 ); for ( int i = 0; i < numElements; i ++ ) ht.put( keys[ i ], new Integer( Math.abs( randGen.nextInt( ) ) % numElements ) ); System.out.println( ht.toString( ) ); String keyValue; System.out.println( "Which key to find? " ); keyValue = dis.readLine( ); Integer value = ( Integer) ht.get( keyValue ); if ( value != null ) System.out.println( keyValue + " = " + value ); }

45 class Properties 1/4 import java.io.DataInputStream; import java.lang.Integer; import java.util.Properties; class Properties1 { public static void main( String args[ ] ) throws java.io.IOException { int numElements = 4; String defaultNames[ ] = { "Red", "Green", "Blue", "Purple" }; int defaultValues[ ] = { 1, 2, 3, 4 }; String userNames[ ] = { "Red", "Yellow", "Orange", "Blue" }; int userValues[ ] = { 100, 200, 300, 400 }; DataInputStream dis = new DataInputStream( System.in ); Properties defaultProps = new Properties( ); Properties userProps = new Properties( defaultProps ); for ( int i = 0; i < numElements; i ++ ) { defaultProps.put( defaultNames[ i ], Integer.toString( defaultValues[ i ] ) ); userProps.put( userNames[ i ], Integer.toString( userValues[ i ] ) ); } System.out.println( "Default Properties" ); defaultProps.list( System.out ); System.out.println( "User Defined Properties" ); userProps.list( System.out ); String keyValue; System.out.println( "Which property to find? "); keyValue = dis.readLine( ); System.out.println( "Property '" + keyValue + "' is '" + userProps.getProperty( keyValue ) + "'" ); }

46 Class Properties 2/4 gura:~/Java/Seminar/java.util> java Properties1 Default Properties -- listing properties -- Blue=3 Red=1 Green=2 Purple=4 User Defined Properties -- listing properties -- Blue=400 Yellow=200 Red=100 Orange=300 Green=2 Purple=4 Which property to find? Blue Property 'Blue' is '400' /... Which property to find? 5 Property '5' is 'null'

47 class Properties 3/4 public void load( InputStream in ) throws IOException –key "Truth" and the associatted element value "Beauty" Truth Beauty Truth = Beauty Truth:Beauty –key "fruit" and the associatted elements fruits apple, banana, pear, \ cantaloupe, watermelon, \ kiwi, mango –key "cheeses" and the associatted element empty string cheeses –first non-character # or ! is ignored public void save( OutputStream out, String header ) –suitable for loading –header + '\n' + comment line( current date and time ) + '\n' + Properties table )

48 class Properties 4/4 changes in source above class Properties2 {... System.out.println( "Default Properties" ); defaultProps.save( System.out, "test" ); System.out.println( "User Defined Properties" ); userProps.save( System.out, "test" );... gura:~/Java/Seminar/java.util> java Properties2 Default Properties #test #Sun May 11 07:56:20 KST 1997 Blue=3 Red=1 Green=2 Purple=4 User Defined Properties #test #Sun May 11 07:56:20 KST 1997 Blue=400 Yellow=200 Red=100 Orange=300 Which property to find? Red Property 'Red' is '100'


Download ppt "Java.util Nam Sedong May 12, 1997."

Similar presentations


Ads by Google