Wednesday 22 March 2017

StringTokenizer, BitSet & Date - Java Tutorials

StringTokenizer

The processing of text often consists of parsing a formatted input string. Parsing is the division of text into a set of discrete parts, or tokens, which in a certain sequence can convey a semantic meaning. The StringTokenizer class provides the first step in this parsing process, often called the lexer (lexical analyzer) or scanner. StringTokenizer implements the Enumeration interface. Therefore, given an input string, you can enumerate the individual tokens contained in it using StringTokenizer.

To use StringTokenizer, you specify an input string and a string that contains delimiters. Delimiters are characters that separate tokens. Each character in the delimiters string is considered a valid delimiter—for example, “,;:” sets the delimiters to a comma, semicolon, and colon. The default set of delimiters consists of the whitespace characters: space, tab, newline, and carriage return.

The StringTokenizer constructors are shown here:

      StringTokenizer(String str)
      StringTokenizer(String str, String delimiters)
      StringTokenizer(String str, String delimiters, boolean delimAsToken)

In all versions, str is the string that will be tokenized. In the first version, the default delimiters are used. In the second and third versions, delimiters is a string that specifies the delimiters. In the third version, if delimAsToken is true, then the delimiters are also returned as tokens when the string is parsed. Otherwise, the delimiters are not returned. Delimiters are not returned as tokens by the first two forms.

Once you have created a StringTokenizer object, the nextToken( ) method is used to extract consecutive tokens. The hasMoreTokens( ) method returns true while there are more tokens to be extracted. Since StringTokenizer implements Enumeration, the hasMoreElements( ) and nextElement( ) methods are also implemented, and they act the same as hasMoreTokens( ) and nextToken( ), respectively.

Here is an example that creates a StringTokenizer to parse “key=value” pairs. Consecutive sets of “key=value” pairs are separated by a semicolon.

  // Demonstrate StringTokenizer.
  import java.util.StringTokenizer;

  class STDemo {
    static String in = "title=Java: The Complete Reference;" +
      "author=Schildt;" +
      "publisher=Osborne/McGraw-Hill;" +
      "copyright=2002";

    public static void main(String args[]) {
      StringTokenizer st = new StringTokenizer(in, "=;");

      while(st.hasMoreTokens()) {
        String key = st.nextToken();
        String val = st.nextToken();
        System.out.println(key + "\t" + val);
      }
    }
  }


The Methods Defined by StringTokenizer

int countTokens( ):  Using the current set of delimiters, the method determines the number of tokens left to be parsed and returns the result.

boolean hasMoreElements( ):  Returns true if one or more tokens remain in the string and returns false if there are none.

boolean hasMoreTokens( ):  Returns true if one or more tokens remain in the string and returns false if there are none.

Object nextElement( ):  Returns the next token as an Object.

String nextToken( ):  Returns the next token as a String.

String nextToken(String delimiters):  Returns the next token as a String and sets the delimiters string to that specified by delimiters.


The output from this program is shown here:

  title Java: The Complete Reference
  author Schildt
  publisher Osborne/McGraw-Hill
  copyright 2002




BitSet

A BitSet class creates a special type of array that holds bit values. This array can increase in size as needed. This makes it similar to a vector of bits. The BitSet constructors are shown here:

      BitSet( )
      BitSet(int size)

The first version creates a default object. The second version allows you to specify its initial size (that is, the number of bits that it can hold). All bits are initialized to zero.


The Methods Defined by BitSet

void and(BitSet bitSet):  ANDs the contents of the invoking BitSet object with those specified by bitSet. The result is placed into the invoking object.

void andNot(BitSet bitSet):  For each 1 bit in bitSet, the corresponding bit in the invoking BitSet is cleared. (Added by Java 2)

int cardinality( ):  Returns the number of set bits in the invoking object. (Added by Java 2, version 1.4)

void clear( ):  Zeros all bits. (Added by Java 2, version 1.4)

void clear(int index):  Zeros the bit specified by index.

void clear(int startIndex, int endIndex):  Zeros the bits from startIndex to endIndex–1. (Added by Java 2, version 1.4)

Object clone( ):  Duplicates the invoking BitSet object.

boolean equals(Object bitSet):  Returns true if the invoking bit set is equivalent to the one passed in bitSet. Otherwise, the method returns false.

void flip(int index):  Reverses the bit specified by index. (Added by Java 2, version 1.4)

void flip(int startIndex, int endIndex):  Reverses the bits from startIndex to endIndex–1. (Added by Java 2, version 1.4)

boolean get(int index):  Returns the current state of the bit at the specified index.

BitSet get(int startIndex, int endIndex):  Returns a BitSet that consists of the bits from startIndex to endIndex–1. The invoking object is not changed. (Added by Java 2, version 1.4)

int hashCode( ):  Returns the hash code for the invoking object.

boolean intersects(BitSet bitSet):  Returns true if at least one pair of corresponding bits within the invoking object and bitSet are 1. (Added by Java 2, version 1.4)

boolean isEmpty( ):  Returns true if all bits in the invoking object are zero. (Added by Java 2, version 1.4)

int length( ):  Returns the number of bits required to hold the contents of the invoking BitSet. This value is determined by the location of the last 1 bit. (Added by Java 2)

int nextClearBit(int startIndex):  Returns the index of the next cleared bit, (that is, the next zero bit), starting from the index specified by startIndex. (Added by Java 2, version 1.4)

int nextSetBit(int startIndex):  Returns the index of the next set bit (that is, the next 1 bit), starting from the index specified by startIndex. If no bit is set, –1 is returned. (Added by Java 2, version 1.4)

void or(BitSet bitSet):  ORs the contents of the invoking BitSet object with that specified by bitSet. The result is placed into the invoking object.

void set(int index):  Sets the bit specified by index.

void set(int index, boolean v):  Sets the bit specified by index to the value passed in v. true sets the bit, false clears the bit. (Added by Java 2, version 1.4)

void set(int startIndex, int endIndex):  Sets the bits from startIndex to endIndex–1. (Added by Java 2, version 1.4)

void set(int startIndex, int endIndex, boolean v):  Sets the bits from startIndex to endIndex–1, to the value passed in v. true sets the bits, false clears the bits. (Added by Java 2, version 1.4)

int size( ):  Returns the number of bits in the invoking BitSet object.

String toString( ):  Returns the string equivalent of the invoking BitSet object.

void xor(BitSet bitSet):  XORs the contents of the invoking BitSet object with that specified by bitSet. The result is placed into the invoking object.


Here is an example that demonstrates BitSet:

  // BitSet Demonstration.
  import java.util.BitSet;

  class BitSetDemo {
    public static void main(String args[]) {
      BitSet bits1 = new BitSet(16);
      BitSet bits2 = new BitSet(16);

      // set some bits
      for(int i=0; i<16; i++) {
        if((i%2) == 0) bits1.set(i);
        if((i%5) != 0) bits2.set(i);
      }

      System.out.println("Initial pattern in bits1: ");
      System.out.println(bits1);
      System.out.println("\nInitial pattern in bits2: ");
      System.out.println(bits2);

      // AND bits
      bits2.and(bits1);
      System.out.println("\nbits2 AND bits1: ");
      System.out.println(bits2);

      // OR bits
      bits2.or(bits1);
      System.out.println("\nbits2 OR bits1: ");
      System.out.println(bits2);

      // XOR bits
      bits2.xor(bits1);
      System.out.println("\nbits2 XOR bits1: ");
      System.out.println(bits2);
    }
  }

The output from this program is shown here. When toString( ) converts a BitSet object to its string equivalent, each set bit is represented by its bit position. Cleared bits are not shown.

  Initial pattern in bits1:
  {0, 2, 4, 6, 8, 10, 12, 14}

  Initial pattern in bits2:
  {1, 2, 3, 4, 6, 7, 8, 9, 11, 12, 13, 14}

  bits2 AND bits1:
  {2, 4, 6, 8, 12, 14}

  bits2 OR bits1:
  {0, 2, 4, 6, 8, 10, 12, 14}

  bits2 XOR bits1:
  {}




Date

The Date class encapsulates the current date and time. Before beginning our examination of Date, it is important to point out that it has changed substantially from its original version defined by Java 1.0. When Java 1.1 was released, many of the functions carried out by the original Date class were moved into the Calendar and DateFormat classes, and as a result, many of the original 1.0 Date methods were deprecated. Java 2 added a few new methods to the time and date classes, but otherwise implemented them in the same form as did 1.1. Since the deprecated 1.0 methods should not be used for new code, they are not described here.

Date supports the following constructors:

      Date( )
      Date(long millisec)

The first constructor initializes the object with the current date and time. The second constructor accepts one argument that equals the number of milliseconds that have elapsed since midnight, January 1, 1970. The nondeprecated methods defined by Date are shown in Table 16-3. With the advent of Java 2, Date also implements the Comparable interface.


The Nondeprecated Methods Defined by Date

boolean after(Date date):  Returns true if the invoking Date object contains a date that is later than the one specified by date. Otherwise, it returns false.

boolean before(Date date):  Returns true if the invoking Date object contains a date that is earlier than the one specified by date. Otherwise, it returns false.

Object clone( ):  Duplicates the invoking Date object.

int compareTo(Date date):  Compares the value of the invoking object with that of date. Returns 0 if the values are equal. Returns a negative value if the invoking object is earlier than date. Returns a positive value if the invoking object is later than date. (Added by Java 2)

int compareTo(Object obj):  Operates identically to compareTo(Date) if obj is of class Date. Otherwise, it throws a ClassCastException. (Added by Java 2)

boolean equals(Object date):  Returns true if the invoking Date object contains the same time and date as the one specified by date. Otherwise, it returns false.

long getTime( ):  Returns the number of milliseconds that have elapsed since January 1, 1970.

int hashCode( ):  Returns a hash code for the invoking object.

void setTime(long time):  Sets the time and date as specified by time, which represents an elapsed time in milliseconds from midnight, January 1, 1970.

String toString( ):  Converts the invoking Date object into a string and returns the result.


As you can see by examining Table 16-3, the Date features do not allow you to obtain the individual components of the date or time. As the following program demonstrates, you can only obtain the date and time in terms of milliseconds or in its default string representation as returned by toString( ). To obtain more-detailed information about the date and time, you will use the Calendar class.

  // Show date and time using only Date methods.
  import java.util.Date;

  class DateDemo {
    public static void main(String args[]) {
      // Instantiate a Date object
      Date date = new Date();

      // display time and date using toString()
      System.out.println(date);

      // Display number of milliseconds since midnight, January 
                                                        1, 1970 GMT
      long msec = date.getTime();
      System.out.println("Milliseconds since Jan. 1, 1970 GMT = " + 
                         msec);
    }
  }

Sample output is shown here:

  Mon Apr 22 09:51:52 CDT 2002
  Milliseconds since Jan. 1, 1970 GMT = 1019487112894


Date Comparison

There are three ways to compare two Date objects. First, you can use getTime( ) to obtain the number of milliseconds that have elapsed since midnight, January 1, 1970, for both objects and then compare these two values. Second, you can use the methods before( ), after( ), and equals( ). Because the 12th of the month comes before the 18th, for example, new Date(99, 2, 12).before(new Date (99, 2, 18)) returns true. Finally, you can use the compareTo( ) method, which is defined by the Comparable interface and implemented by Date.

No comments:

Post a Comment