[Reserved] Practical tool class library java.util

xiaoxiao2021-03-06  106

This chapter describes the Java's utility library java.util package. In this package, Java provides some practical methods and data structures. For example, Java provides a date (DATA) class, Calendar class to generate and acquire date and time, providing random number (Random) class to generate various types of random numbers, but also provide stack, vector (Vector) , Bit set (BitSet) and hashtable, etc. to represent the corresponding data structure.

Figure 8.1 shows the basic hierarchical diagram of the java.util package. Below we will specify several important classes.

┌Java.util.bitset

│Java.util.calendar

│ └Java.util.gregoriancalendar

│Java.util.date

│Java.util.Dictionary

│ └Java.util.hashtable

│ └java.util.properties

│Java.util.EventObject

│Java.util.ResourceBundle

┌ ordinary class ┤ jJava.util.ListResourceBundle

│ │ └java.util.propertyResourceBundle

│ │ jva.util.local

│ │ jva.util.observable

│ │Java.util.random

│ │Java.util.StringTokenizer

│ │Java.util.Vector

│ │ └java.util.stack

Java.util┤ └java.util.timezone

│ └java.util.simpletimezone

│ ┌java.util.enumeration

├ 接 接┤java.util.eventlistener

│ └Java.util.observer

│ ┌Java.util.emptyStackException

└ └ └ 类 ┤Java.util.MissingResourceException

│Java.util.nosuchelementException

└Java.util.toomanyListenerSexception

Figure 8.1 Basic hierarchy of java.util package

8.2 Date Class Date

Java encapsulates information about the date and time in the date class, and the user can obtain the system time or set the date and time by calling the appropriate method. There are many methods in the Date class that have been outdated after JDK1.0, and we will introduce other classes for newly added functions in JDK1.0 in JDK1.0.

Six constructors are defined in the date class.

(1) public Date ()

The date time of the date class object created is set to the dateable time corresponding to the time.

Example Date Today = New Date (); // Today is set to create a date corresponding to the time.

(2) Public Date (Long Date)

The line type parameter DATE can be obtained by calling the Static method PARSE (String S) in the Date class.

Example long L = Date.Parse ("MON 6 JAN 1997 13: 3: 00");

Date day = new date (l);

// DAY is Monday, January 6, 1997, 13: 3: 00.

(3) Public Date (String S)

Generate a day object by string S. The format of S is the same as the mode of string parameters in the method PARSE.

Example Date Day = New Date ("MON 6 JAN 1997 13: 3: 00");

// DAY is Monday, January 6, 1997, 13: 3: 00.

(4) Public Date (int year, int month, int Date) (5) Public Date (int year, int month, int Date, int hrs, int min)

(6) Public Date (int Year, int MONTH, INT DATE, INT HRS, INT min, Int sec)

Create a day object according to a given parameter.

Parameter Description:

The value of YEAR is: the year-1900 needs to be set. For example, the year to set is 1997, the value of YEAR should be 97, that is, the result of 1997-1900. So the minimum of 1900 can be set in Date;

The value domain of Month is 0 ~ 11, 0 represents January, 11 table representative December;

Date's value domain between 1 to 31;

The value domain of the HRS is between 0 and 23. HRS = 0 from 1 o'clock in the midnight, from noon to 1 pm hrs = 12;

The value domain between MIN and SEC is between 0 and 59.

Example Date Day = New Date (11, 3, 4);

// Day in: 04-APR-11 12:00:00 AM

In addition, an incorrect parameter can also be given.

The set time is February 30, 1910, which will be explained on March 2.

Date Day = New Date (10, 1, 30, 10, 12, 34);

System.out.println ("Day's Date IS: Day);

// Print results: day's date is: web mar 02 10:13:34 GMT 08: 00 1910

Below we give some common methods in the DATE class.

(1) Public Static Long Utc (int year, int month, int Date, int hrs. Int min, int SEC)

This method will calculate the UTC value with a given parameter. UTC is a timing system that is slightly different from the timing system of GMT (Greenwich Time). The UTC timing system is based on atomic clock, and the GTMT timing system is based on astronomical observations. The usual GMT timing system used is used.

(2) Public Static Long Parse (String S)

This method converts the string S into a LONG type date. This method has been used when introducing the construction method Date (long Date).

String S has a certain format, generally:

(Sunday time GMT time zone)

If the time zone is not indicated, it is a local time zone.

(3) Public void setmonth (int MONTH)

(4) Public int getMonth ()

These two methods are set and acquired a monthly value.

The value domain of the obtained month is from 0 to 11, 0 represents January, 11. December.

(5) Public string toString ()

(6) Public string tolocalstring ()

(7) public string Togmtstring ()

Convert a given date object to a string of different formats. The specific formats they correspond to the example 8.1.

(8) Public int gettimezoneoffset ()

This method is used to obtain the time zone offset of the date object.

The basic methods in the DATE class described above are specifically applicable in Example 8.1, and the corresponding results are printed. Since some excessive methods are used, there is warning information when compiling. In addition, since the time in this example is related to the platform, the different JDK versions are not identical to this process, so the results of the different versions of JDK execution this example may be slightly different.

Example 8.1 Dateapp.java

Import java.lang.system;

Import java.util.date; public class dateapp {

Public static void main (string args []) {

Date Today = new date ();

The date in // Today is set to create the date and time of the time, assuming the creation time is March 1997

// 23:51: 54 seconds.

System.out.println ("Today's Date IS" Today;

// Return the general time representation, the result is the result in this example

// Today's Date Is Fri May 23 17:51:54 1997

System.out.Println ("Today's Date (Internet GMT) IS:"

Today.toGmtstring ());

// The return result is a GMT time representation, and the result is the result in this example.

// Today's Date (Internet GMT) IS: 23 May 1997 09: 51: 54: GMT

System.out.Println ("Today's Date (Locale) IS:"

Today.tolocalestring ());

// Return the result is the time representation of local habits, the result is

// Today's Date (Locale) IS: 05/23/97 17:51:54

System.out.println ("Today's Year IS:" Today.GactYear ());

System.out.Println ("Today's Month IS:" 1));

System.out.println ("Today's Date IS:" Today.Getdate ());

// Call the method in the DATE class to get the value of the year.

// Different constructors are called to create a DATE class.

Date day1 = new date (100, 1, 23, 10, 12, 34);

System.out.println ("Day1's date is:" day1);

Date day2 = new date ("SAT 12 AUG 1996 13: 3: 00");

System.out.println ("Day2's date is:" day2);

Long L = Date.Parse ("SAT 5 AUG 1996 13: 3: 00 GMT 0800");

Date day3 = new date (l);

System.out.println ("Day3's Date (GMT) IS:" day3.togmtstring ());

System.out.println ("Day3's Date (Locale) IS:"

day3.tolocalestring ());

System.out.println ("Day3's Time Zone Offset IS:"

day3.gettimezoneoffset ());

}

}

Run results (JDK1.3 version, different from the original text, the original version is JDK1.0):

E: / java / tutorial / java01> Java DateApp

Today's Date Is Thu Dec 27 17:58:16 CST 2001

Today's Date (Internet GMT) IS: 27 DEC 2001 09:58:16 GMTTODAY's DATE (LOCALE) IS: 2001-12-27 17:58:16

Today's Year IS: 101

Today's Month IS: 12

Today's Date IS: 27

Day1's date is: Wed Feb 23 10:12:34 CST 2000

Day2's date is: fri aug 12 13:03:00 CST 1996

Day3's date (gmt) IS: 5 aug 1996 05:03:00 GMT

Day3's Date (Locale) IS: 1996-8-5 13:03:00

Day3's Time Zone Offset IS: -480

E: / java / tutorial / java01>

8.3 Calendar Calendar

In the early JDK version, the Date (Date) class is attached to two functions: (1) Allow the use of years, month, day, time, minute, seconds to explain the date: (2) Allow a string representing the date to format Analysis of chemical and syntactic. The class Calendar is provided in JDK1.1 to complete the first function, class DateFormat to complete the second function. DateFormat is a class in the Java.Text package. Unlike the Date class, the DateFormat class accepts a date string represented by various languages ​​and different habits. This section describes the class Calendar in the java.util package and other newly added related classes.

Class Calendar is an abstract class that completes the Date class and a common date representation (ie, a set of interstitial domains such as Year, Month, Day, Hour Representation Date).

Due to the different rules used, different calendar systems differ from the interpretation of the same date. It provides a subclass of Calendar classes in JDK1.1, which implements the general calendar system in the world. Of course, users can also inherit the Calendar class and increase the required rules to achieve different calendar systems.

The Gregoriancalendar inherited the Calendar class. This section will introduce the relevant methods in the Calendar class while introducing class Gregoriancalendar.

Gregoriancalendar provides seven constructor:

(1) public gregoriancalendar ()

The correlation value in the created object is set to specify the time zone, the current time of the default place, that is, the time zone at which the program is running, the current time of the location.

(2) Public Gregoriancalendar (TIMEZONE ZONE)

The correlation value in the created object is set to the current time of the time zone zone, the default location.

(3) Public Gregoriancalendar (LOCALE Alocale)

The correlation value in the created object is set to the default time zone, the current time of the specified place alocale.

(4) Public Gregoriancalendar (Timezone Zone, Local Alocale)

The correlation value in the created object is set to the specified time zone, the current time of the specified location.

The nature of the class Timezone used above is as follows:

Timezone is a class in the java.util package, which encapsulates information about the time zone. Each time zone corresponds to a set of IDs. The class Timezone provides some ways to complete the conversion between the time zone and the corresponding ID.

(I) Knowing a particular ID, can call the method

Public Static Synchronized Timezone GetTimezone (String ID)

To get the corresponding time zone object.

Example The ID of the Pacific Time Zone is PST, with the following method to obtain a time zone object corresponding to the Pacific Time Zone: Timezone Tz = Timezone.getTimezone ("PST");

Call method getDefault () can get the object of the time zone where the host is located.

Timezone tz = timezone.getDefault ();

(II) Call the following method to get the ID of the time zone

■ Public static synchronized string [] getAvailableIDS (int RAWOFFSET)

Get an ID array based on a given time zone offset value. The IDs of the different regions of the same time may be different, which is due to the uniform in different regions to implement the summer time.

String s [] = Timezone.GetavailableIDS (-7 * 60 * 60 * 1000);

Print S, the result is S [0] = PNT, S [1] = MST

■ public static synchronized string [] getavailableids ()

Get all supported IDs provided.

■ Public String getId ()

Get the ID of a specific time zone object.

Timezone tz = timezone.getDefault ();

String s = tz.getid ();

Print S and the result is S = CTT.

The object used above represents a specific geographic, political or cultural area. Locale is just a mechanism that is used to identify a class of objects, and local itself does not contain such objects.

There are two ways to get an object of a Locale:

(I) Call the construction method of the Locale class

Locale (String Language, String Country)

Locale (String Language, String Variant)

Parameter Description: Language ?? The code defined in ISO-639 consists of two lowercase letters.

The code defined in ISO-3166 consists of two uppercase letters in ISO-3166.

Variant® salesman and code for a particular browser, such as using WIN represents Windows.

(II) Call the constant defined in the Locale class

The Local class provides a large amount of constant for users to create a Locale object.

Case Locale.china

Create an object of Locale for China.

Other methods in class Timezone and class locale, readers can check the API.

(5) Public Gregoriancalendar (int year, int month, int Date)

(6) Public Gregoriancalendar (int Year, int MONTH, INT DATE, INT HOUR, INT Minute)

(7) Public Gregoriancalendar (int Year, int MONTH, INT DATE, INT HOUR, INT Minute, Int Second)

Create a GregorianCalendar object with a given date and time.

Parameter Description:

Year - Set the variable of the calendar object, Year; MONTH- sets the variable of the calendar object;

Date- Set the variable of the calendar object; Hour-Set the variable of the calendar object Hour_of_day;

Minute-Set the variable of the calendar object minute; Second-Set the variable of the calendar object SECOND.

Different from the DATE class is the value of Year does not have 1900, and Year's value represents the actual year. The meaning of Month is the same as the DATE class, and 0 represents January, 11 represents December.

Case Gregoriancalendar Cal = New Gregoriancalendar (1991, 2, 4)

The date of CAL is March 4, 1991.

In addition to similar ways to Date, the Calendar class also provides a method of scrolling calculation and mathematical calculations on calendar. The calculation rule is determined by a given calendar system. When performing a date calculation, sometimes the information is insufficient or the information is not true. Calendar has a corresponding method to solve these problems. The default settings will be used when the information is insufficient, and the default settings in the GregorianCalendar class is generally Year = 1970, Month = January, Date = 1.

When the information is not in real time, Calendar will first select the corresponding Calendar variable combination, and discard other conflictable information.

Month day_of_month

Month week_of_month day_of_week

Month day_of_week_of_month day_of_week

Day_of year

Day_of_week_week_of_year

Hour_of_day

8.4 Random Digital Random

The class java.util.random in the Java Practical Tool Class library provides methods of producing various types of random numbers. It generates int, long, float, double, and goussian equivalents. This is also the most different from the method random () in java.lang.math, and the latter only produces a Double type random number.

The method in the class random is very simple, it has only two construction methods and six ordinary methods.

Construction method:

(1) Public random ()

(2) Public Random (long seed)

Java generates a random number there is a base value SEED. In the first method, the base value is default, the system time is used as SEED.

Ordinary method:

(1) Public synronized void setseed (long seed)

This method is to set the base value SEED.

(2) public int nextint ()

This method is to generate an integer random number.

(3) Public long nextlong ()

This method is to generate a LONG type random number.

(4) Public float nextfloat ()

This method is to generate a Float type random number.

(5) Public double nextdouble ()

This method is to generate a Double type random number.

(6) Public synchronized double nextgoussian ()

This method is to generate a Double type Goussian random number.

Example 8.2 Randomapp.java.

// Import java.lang. *;

Import java.util.random;

Public class randomapp {

Public static void main (string args []) {

Random ran1 = new random ();

Random ran2 = new random (12345);

// Create two objects of two class random.

System.out.Println ("The 1st Set of Random Numbers);

System.out.println ("/ T INTEGER:" RAN1.NEXTINT ());

System.out.println ("/ t long:" ran1.nextlong ());

System.out.println ("/ t float:" ran1.nextfloat ());

System.out.println ("/ t Double:" ran1.nextdouble ());

System.out.println ("/ T Gaussian:" ran1.nextgaussian ()); // Generate a variety of random numbers

System.out.print ("The 2nd Set of Random Numbers);

For (int i = 0; i <5; i ) {

System.out.println (ran2.nextint () "");

IF (i == 2) system.out.println ();

// Generate different random numbers of the same type.

System.out.println (); // original

}

}

}

operation result:

E: / java01> Java RandomApp

The 1st Set of Random Numbers:

INTEGER: -173899656

Long: 8056223819738127077

Float: 0.6293638

Double: 0.7888394520265607

Gaussian: 0.5015701094568733

The 2nd set of random numbers: 1553932502

-2090749135

-287790814

-355989640

-716867186

E: / java01>

8.5 Vector Class Vector

Java.util.Vector provides a vector class to achieve a function similar to a dynamic array. In the Java language. As mentioned at the beginning, it is not a pointer concept, but if the pointer can be used correctly and flexibly, it is indeed greatly improved the quality of the program, such as the so-called "dynamic array" in C, C , is generally implemented by a pointer. In order to make up for this defect, Java provides a rich library to facilitate the programmer, and the VECTOR class is one of them. In fact, flexible use of arrays can also complete the functionality of the vector class, but the large number of methods provided in the quantity class greatly facilitate the user's use.

Once a vector class is created, you can insert different classes of different classes, neither the type of capacity is not required to be selected, and it is convenient to find. Use the vector class for pre-definition of the array size or not to pre-define the size of the array.

Vector class provides three construction methods:

Public vector ()

Public Vector (int InitialCapacity, int CapacityIncrement)

Public Vector (Int InitiaLCapacity)

Using the first method, the system automatically manages the vector object. If two methods are used, the system will set the capacity of the vector object according to the parameter initialcapacity (ie, the size of the vector object can store data). When the number of data that is really stored exceeds the capacity, the system will expand the storage capacity of the vector object. Parameters CapacityInCrement gives each expanded expansion value. When CapacityInCrement is 0, each time it is doubled. Use this feature to optimize storage.

Various methods are provided in the VECTOR class that makes it easy for users to use:

■ Insert function

(1) Public final synchronized void addelement (Object Obj)

Insert the OBJ into the tail of the vector. OBJ can be an object of any class. For the same vector object, different types of objects can be inserted therein. However, inserting should be an object rather than a value, it should be aware that the numerical value is converted into a corresponding object when inserting a value.

Insert an integer 1, don't call v1.addelement (1) directly, the correct method is:

Vector v1 = new vector ();

Integer integer1 = new integer (1);

v1.addelement (Integer1); (2) Public final synchronized void setElementat (Object Obj, int index)

Set the objects at Index to OBJ, the original object will be overwritten.

(3) Public final synchronized void insertelementat (Object Obj, int index)

Insert OBJ, the original object, and the object after the index specified are inward.

■ Delete function

(1) Public final synchronized void transoveElement (Object Obj)

Remove OBJ from the vector. If there is a plurality of existence, start trial from the vector head, delete the found vector member found with the OBJ.

(2) Public final synchronized void transoveAllelement ()

Delete all objects in the vector.

(3) Public final synchronized void removelelementlat (int index)

Delete the object that Index refers to.

■ Query search function

(1) Public final int indexof (Object Obj)

Start search of OBJ from the vector head, return the resulting subscript corresponding to the first OBJ, if this OBJ is not present, returns -1.

(2) Public final synchronized int indexof (Object Obj, int index)

Search OBJ from the subscript represented by Index.

(3) Public final int lastindexof (Object obj)

Reverse search OBJ from the tail of the vector.

(4) Public final synchronized int lastindexof (Object Obj, int INDEX)

From the subscript represented by INDEX, the end-to-head is retrograde OBJ.

(5) Public final synchronized Object firstElement ()

Get the first OBJ in the vector object.

(6) Public final synchronized Object lastelement ()

Get the last OBJ in the vector object.

After learning the most basic method of the vector, let's take a look at 8.3Vectorapp.java.

Example 8.3 VectorApp.java.

Import java.util.vector;

Import java.lang. *; // This sentence should not be, but the original

Import java.util.enumeration;

Public class vectorApp {

Public static void main (String [] args) {

Vector v1 = new vector ();

Integer integer1 = new integer (1);

v1.addelement ("one");

// Add to string object

v1.addelement (integer1);

v1.addelement (integer1);

// Add to INTEGER object

v1.addelement ("two");

v1.addelement (new integer (2));

v1.addelement (integer1);

v1.addelement (integer1);

System.out.println ("The Vector V1 IS: / N / T" V1);

/ / Convert V1 into a string and print

v1.insertelementat ("Three", 2);

V1.insertelementat (New Float (3.9), 3);

System.out.Println ("The Vector V1 (Used Method Insert ()) IS: / N / T" V1); // Insert a new object into the designated location, the object after the specified position is backwards

V1.SETELEMENTAT ("FOUR", 2);

System.out.println ("The Vector V1 (Used Method SetElementat ()) IS: / N / T" V1);

// Set the object of the specified location to a new object

V1.RemoveElement (Integer1);

/ / From the vector object V1, INTEGER1 is started from the beginning, from the beginning

// Looking, delete the first integer1

ENUMERATION ENUM = v1.elements ();

System.out.print ("Used Method RemoveElement ()) is:");

While (enum.hasmoreElements ())

System.out.print (Enum.nexTelement () "" "

SYSTEM.OUT.Println ();

// Use the enumerated method to get each element of the vector object

System.out.println ("Top-to-bottom):"

V1.indexof (integer1));

System.out.println ("Tottom-TO-TOP):"

v1.lastIndexof (Integer1));

/ / Find the location of the object in Integer1 in different directions

v1.setsize (4);

System.out.println ("The New Vector IS:" V1);

/ / Re-set the size of V1, excess elements are discarded

}

}

operation result:

E: / java01> Java Vectorapp

The Vector V1 IS:

[One, 1, 1, Two, 2, 1, 1]

The Vector V1 (Used Method Insertelementat ()) IS:

[One, 1, Three, 3.9, 1, Two, 2, 1, 1]

The Vector V1 (Used Method SetElementat ()) IS:

[One, 1, Four, 3.9, 1, Two, 2, 1, 1]

The Vector V1 (Used Method RemoveEleMent ()) IS: One Four 3.9 1 Two 2 1 1

Top-to-bottom: 3

Tottom-TO-TOP: 7

The New Vector (Resized The Vector) IS: [One, Four, 3.9, 1]

E: / java01>

From the results of Example 8.3, you can clearly understand the role of the above methods, and some need to explain.

(1) Class Vector definition method

Public Final Int size ()

This method is used to acquire the number of vector elements. Its return value is the number of elements that actually exist, rather than vector. Method cappactly () can be called to obtain a capacity value.

method:

Public Final Synchronized Void Setsize (Int Newsize)

This method is used to define the vector size. If the number of existing members of the vector has exceeded the value of Newsize, the excess element of the exceeding is lost. (2) One object of the Enumeration class is defined in the program

Enumeration is an interface class in java.util, encapsulated a method of enumerating data collection in Enumeration.

Method HawMoreElement () is provided in Enumeration to determine that there are other elements and methods NEXTELEMENT () to get the next element. Using these two methods can sequentially obtain the elements in the collection.

Methods in Vector:

Public final synchronized enumeration Elements ()

This method will correspond to an enumeration type. There are also such methods in other classes in the java.util package to facilitate the user to obtain the corresponding enumeration type.

8.6 Stack STACK

The Stack class is a subclass of the Vector class. It provides users with the stack of this advanced data structure. The basic characteristics of the stack are advanced. That is, the element is first placed in the stack will be launched. The operation of the stack is provided in the Stack class.

basic method:

Public Object Push (Object Hem)

In the HEM in the stack, the HEM can be any class of objects.

Public Object Pop ()

Pop up an object.

Public Object PEEK ()

Return to the top elements, but this element is not popped up.

Public int search (Object Obj)

Search Object OBJ, returns the location it.

Public Boolean Empty ()

Case whether the stack is empty.

Example 8.4 Stackapp.java uses the various methods above.

Example 8.4 Stackapp.java.

Import java.lang. *;

Import java.util. *;

Public class stackapp {

Public static void main (string args []) {

Stack sta = new stack ();

Sta.push ("apple");

Sta.push ("banana");

Sta.push ("cherry");

// Pressing the string object

Sta.push (New Integer (2));

// Pressing the object of Integer, the value is 2

Sta.push (New Float (3.5));

// Pressing the object of FLOAT, the value is 3.5

System.out.println ("THE Stack IS," STA);

// Corresponding stack STA

System.out.println ("Top of Stack IS:" sta.peek ());

// Corresponding to the top element, but does not pop up this element

System.out.println ("The position of object cherry is:"

sta.search ("cherry"));

// Print the location of the object cherry

System.out.print ("Pop The Element of The Stack:");

While (! sta.empty ())

System.out.print (sta.pop () "");

SYSTEM.OUT.Println ();

// Populate the elements in the stack and print it. Comparison with the results of the first printed STA, you can see the stack

// Features

}

}

Run results (omitted)

8.7 Hardbach Hashtable

The hash table is an important storage method and a common retrieval method. Its basic idea is to calculate the value of the relational code as an argument. By calculating the corresponding function value by a certain function relationship, interpret this value as a node's storage address, deposit the node to the storage address corresponding to the storage address. . The method of retrieving the key code is retrieved. The hash table now has a complete algorithm to insert, delete, and resolve conflicts. In Java, the hash table is used to store objects and enable fast retrieval. Java.util.hashtable provides a way to use a hash table without considering how its hash table really works.

The hash table class provides three construction methods, namely:

Public hashtable ()

Public HashTable (int initialcapacity)

Public HashTable (int Initialcapacity, Float LoadFactor)

Parameters INITIALCAPACITY is the initial capacity of HashTable, and its value should be greater than 0. LoadFactor is also known as load factors, is a floating point number between 0.0 to 0.1. It is a percentage, indicating when the hash table needs to expand, for example, there is a hash table, the capacity is 100, and the load factor is 0.9, then the hash table 90% has been used, this hash table It will automatically expand into a larger hash table. If the user does not assign these parameters, the system will automatically process without the need for user worry.

HashTable provides basic insertion, retrieval, etc.

■ Insert

Public Synchronized Void Put (Object Key, Object Value)

Set a keyword key to the object value and add it to the HashTable. If this keyword already exists, the old object corresponding to this key is updated to the new object value. This indicates that the same keyword in the hash table is impossible to correspond to different objects (from the basic idea of ​​the hash table, this is also obvious).

■ Retrieval

Public Synchronized Object Get (Object Key)

Get the corresponding object based on a given keyword key.

Public Synchronized Boolean ContainsKey (Object Key)

Judging whether there is a keyword key in the hash table.

Public Synchronized Boolean Contains (Object Value)

It is determined whether the value is an element in the hash table.

■ Delete

Public Synchronized Object Remove (Object Key)

Remove the object corresponding to the keyword key from the hash table.

Public synchronized void clear ()

Clear hash table

In addition, Hashtalbe also provides methods to obtain corresponding enumerations:

Public synchronized enumeration keys ()

Returns the keyword corresponding to the keyword.

Public synchronized enumeration Elements ()

Returns the enumeration object corresponding to the element.

Example 8.5 HashTable.java gives examples of using havehtable.

Example 8.5 Hashtalbe.java.

// Import java.lang. *;

Import java.util.hashtable;

Import java.util.enumeration;

Public class haashapp {

Public static void main (string args []) {

Hashtable hash = new hashtable (2, (float) 0.8);

// Create a hash table object Hash, the initial capacity is 2, the load factor is 0.8

Hash.put ("jiangsu", "nanjing");

// give a string object "jiangsu" give a keyword "nanjing" and add it to havehhash.put ("beijing", "beijing");

Hash.put ("zhejiang", "hangzhou");

System.out.println ("The Hashtable Hash1 IS:" HASH);

System.out.println ("THE SIZE OF THIS HASH TABLE HASH.SIZE ());

// Print the contents and size of Hash

ENUMERATION ENUM1 = Hash.Elements ();

System.out.print ("The Element of Hash IS:");

While (enum1.hasmoreElements ())

System.out.print (Enum1.nexTelement () ");

SYSTEM.OUT.Println ();

// Print the content in Hash in sequence

IF (Hash.Containskey ("jiangsu"))

System.out.println ("The Capatial of Jiangsu IS" Hash.Get ("jiangsu");

Hash.Remove ("beijing");

// Remove keyword beijing corresponding object

System.out.println ("The Hashtable Hash2 IS:" HASH);

System.out.println ("THE SIZE OF THIS HASH TABLE HASH.SIZE ());

}

}

operation result:

THE Hashtable Hash1 IS: {beijing = beijing, zhejiang = hangzhou, jiangsu = nanjing}

The size of this hash Table is 3

The element of hashing is: beijing hangzhou nanjing

The capatial of jiangsu is nanjing

THE Hashtable Hash2 is: {zhejiang = hangzhou, jiangsu = nanjing}

The size of this hash Table is 2

Hashtable is a subclass of the Dictionary (Dictionary) class. The keyword corresponds to the data value in the dictionary class. The dictionary class is an abstract class. There is also a class Properties in java.util, which is a subclass of HashTable. Use it to perform operations related to object properties.

8.8 Bit Collection BitSet

The operation of a set of binary data is encapsulated in the bit collection class.

Let's take a look at 8.6 bitsetapp.java.

Example 8.6 BitSetApp.java

// Import java.lang. *;

Import java.util.bitset;

Public class bitsetApp {

Private static int n = 5;

Public static void main (String [] args) {

BitSet set1 = new bitset (n);

For (int i = 0; i

// Assign 1 of the set1, that is, all TRUE

BitSet set2 = new bitset ();

Set2 = (bitset) set1.clone ();

// set2 is set1 copy

Set1.clear (0); set2.clear (2);

// Put the 2nd bit of the 0th bit of set1

System.out.println ("The set1 is:" set1);

/ / Directly convert the set1 into a string output, the output content is where the set1 is in the position of TRUE

// Print results are the set1 is: {1, 2, 3, 4}

System.out.println ("The Hash Code of Set2 IS:" Set2.hashcode ());

// Print set2's Hashcode

PrintBit ("set1", set1);

PrintBit ("set2", set2);

// Call the print program PrintBit (), print each element in the object

// Print set1 results for the bit set1 is: false true true true true

set1.and (set2);

PrintBit ("set1 and set2", set1);

/ / Complete set1 and set2, and print results

set1.or (set2);

PrintBit ("set1 or set2", set1);

/ / Complete set1 or set2, and print results

Set1.xor (set2);

PrintBit ("SET1 XOR SET2", SET1);

/ / Complete Set1 XOR SET2, and print results

}

// Print the contents of the bitset object

Public Static Void PrintBit (String Name, BitSet Set) {

System.out.print ("The bit" name "is:");

For (int i = 0; i

System.out.print (set.get (i) ");

SYSTEM.OUT.Println ();

}

}

operation result:

The set1 IS: {1, 2, 3, 4}

The Hash Code of Set2 IS: 1225

The bit set1 is: false True True True TRUE

The bit set2 is: True True False True TRUE

The bit set1 and set2 is: false True False True TRUE

The bit set1 or set2 is: True True False True True

The bit set1 xor set2 is: False False False False False

The two constructs provided by the BitSet class are used in the program:

Public bitset ();

Public BitSet (INT N);

The parameter n represents the size of the object of the BitSet class created. The size of the BitSet class is automatically expanded by the system when necessary.

Other methods:

Public void set (INT N)

Set the nth bit of the BitSet object to 1.

Public Void Clear (INT N)

Clear the nth bit of the BitSet object.

Public Boolean Get (INT N)

The value of the nth bit of the set object is read, which is a Boolean value. When the nth bit is 1, returns true; the nth bit is 0, returns false.

In addition, as shown in the program, when the object of a BitSet class is converted into a string output, the content of the output is where the TRUE is located in this object.

A set of steps are provided in BitSet, namely:

Public void and (bitset set)

Public void or (bitset set) Public void XOR (BitSet Set)

Use them to complete the two bits between the two bits, or, a different or operation.

One method in the BitSet class is a method of obtaining the size of the bit collection. Its return value is different from the bit set size n set when it is initialized, typically 64.

summary

This chapter we introduced some common classes in Java's utility class library java.util. There are other classes in the java.util package. The specific usage users they can check the API themselves. In the next chapter, we will learn to use the Java.awt package for window programming. In the example in the following seal, we will use the various classes introduced in this chapter.

转载请注明原文地址:https://www.9cbs.com/read-98240.html

New Post(0)