Results 1 to 2 of 2

Thread: java.util

  1. #1
    Java Tutorial is offline Member
    Join Date
    Nov 2007
    Posts
    22
    Rep Power
    0

    Default java.util

    java.util contains a very useful set of classes, interfaces and exceptions. Its called util package because it contains utility classes that are used in common applications. Following import statement is very common in Java classes:

    Java Code:
    import java.util.*;
    In this tutorial, I will talk about the most common and useful classes.

    java.util.Vector

    A Vector represents a growable array object that can hold objects of any type. One can restrict the Vector by bounding it to a specific type. Vector is very similar to array and each stored object has an index. Time for an example:

    Java Code:
    Vector vec = new Vector();
    vec.add("String1");
    vec.add("String2");
    vec.add("String3");
    
    for(int i=0;i<vec.size();i++)
    System.out.println(vec.get(i));
    In the example above, we simply used a for loop to get the contents of the array. Now lets use java.util.Enumeration for this purpose. Java docs define Enumeration as:
    The Enumeration interface specifies a set of methods that may be used to enumerate, or count through, a set of values.
    Java Code:
    Vector vec = new Vector();
    vec.add("String1");
    vec.add("String2");
    vec.add("String3");
    
    for (Enumeration e = vec.elements() ; e.hasMoreElements() ;) {
    System.out.println(e.nextElement());
    }
    Output:
    Java Code:
    String1
    String2
    String3
    A lot of people are confused about the size and the capacity of Vectors. Both are different. Size of a Vector refers to the number of elements in the Vector, whereas capacity means the number of elements the Vector can hold without expanding. By default, the capacity is 10 elements.

    Java Code:
    Vector vec = new Vector();
    vec.add("String1");
    vec.add("String2");
    vec.add("String3");
    
    System.out.println("Size: " + vec.size());
    System.out.println("Capacity: " + vec.capacity());
    Output:

    Java Code:
    Size: 3
    Capacity: 10
    Java 5 introduced generics which adds more power to Java. Vectors store objects in them, but that object can be of any type. It can be a String, Integer, Float or even a custom object. With generics, you can specify the type of objects that are allowed to be stored in a Vector. In the following example, I tried to store an integer into a Vector that is bounded by String.

    Java Code:
    Vector <String> vec = new Vector<String>();
    vec.add("String1");
    vec.add(1);
    Exception:
    Java Code:
    The method add(int, String) in the type Vector<String> is 
    not applicable for the arguments (int)
    java.util.ArrayList

    ArrayList is very similar to Vector. It represents a growable array of objects which is very useful in programming practices. Natural question is, what is the difference between ArrayList and Vector. Vector is Serializable and ArrayList is not. This means, Vector is preferred over ArrayList in multithreaded environments. But if you are sure that your program won’t be executed in multithreaded environment, then you should use ArrayList, because Java handles Vector in a special way and the performance of Vector is slower as compared of ArrayList.

    Lets take a simple example of ArrayList. I will use Iterator to print the contents of the ArrayList.

    Java Code:
    ArrayList aList = new ArrayList();
    aList.add("String1");
    aList.add("String2");
    aList.add("String3");
    
    Iterator iterator = aList.iterator();
    
    while(iterator.hasNext())
    System.out.println(iterator.next());
    java.util.Arrays

    We use arrays for operations in our Java programming. We need to perform a lot of operations on the arrays. We may define the operations in our class as required, but obviously it takes time. Arrays class of util package provides methods for manipulating arrays.

    Sorting arrays is a common operation and Arrays class provides support for this:

    Java Code:
    int[]myArray = new int[5];
    myArray[0] = 22;
    myArray[1] = 11;
    myArray[2] = 42;
    myArray[3] = 76;
    myArray[4] = 88;
    
    Arrays.sort(myArray);
    
    for(int i=0;i<myArray.length;i++)
    System.out.println(myArray[i]);
    Output:

    Java Code:
    11
    22
    42
    76
    88
    In the example above, we sorted an integer array. Arrays class provides following sorting functions:

    Java Code:
    static void sort(byte[] a)
    static void sort(byte[] a, int fromIndex, int toIndex)
    static void sort(char[] a)
    static void sort(char[] a, int fromIndex, int toIndex)
    static void sort(double[] a)
    static void sort(double[] a, int fromIndex, int toIndex)
    static void sort(float[] a)
    static void sort(float[] a, int fromIndex, int toIndex)
    static void sort(int[] a)
    static void sort(int[] a, int fromIndex, int toIndex)
    static void sort(long[] a)
    static void sort(long[] a, int fromIndex, int toIndex)
    static void sort(Object[] a)
    static void sort(Object[] a, Comparator c)
    static void sort(Object[] a, int fromIndex, int toIndex)
    static void sort(Object[] a, int fromIndex, int toIndex, Comparator c)
    static void sort(short[] a)
    static void sort(short[] a, int fromIndex, int toIndex)
    Arrays class also provides fill method to fill arrays with a value. Following fill methods are provided:

    Java Code:
    static void fill(boolean[] a, boolean val)
    static void fill(boolean[] a, int fromIndex, int toIndex, boolean val)
    static void fill(byte[] a, byte val)
    static void fill(byte[] a, int fromIndex, int toIndex, byte val)
    static void fill(char[] a, char val)
    static void fill(char[] a, int fromIndex, int toIndex, char val)
    static void fill(double[] a, double val)
    static void fill(double[] a, int fromIndex, int toIndex, double val)
    static void fill(float[] a, float val)
    static void fill(float[] a, int fromIndex, int toIndex, float val)
    static void fill(int[] a, int val)
    static void fill(int[] a, int fromIndex, int toIndex, int val)
    static void fill(long[] a, int fromIndex, int toIndex, long val)
    static void fill(long[] a, long val)
    static void fill(Object[] a, int fromIndex, int toIndex, Object val)
    static void fill(Object[] a, Object val)
    static void fill(short[] a, int fromIndex, int toIndex, short val)
    static void fill(short[] a, short val)
    Lets take an example to make things obvious:

    Java Code:
    int[]myArray = new int[5];
    Arrays.fill(myArray, 22);
    for(int i=0;i<myArray.length;i++)
    System.out.println(myArray[i]);
    Output:

    Java Code:
    22
    22
    22
    22
    22
    java.util.Arrays class provides equals method to compare two arrays. Comparison is done on content basis. If two arrays contain same elements, then they are equal.

    Java Code:
    int[]myArray = new int[5];
    Arrays.fill(myArray, 22);
    
    int[]yourArray = new int[5];
    Arrays.fill(yourArray, 22);
    
    
    if(Arrays.equals(myArray, yourArray))
    System.out.println("Equal");
    else
    System.out.println("Not - Equal");

    java.util.Date

    Util package contains Date class to represent date. Date class has 6 constructors but 5 of them are deprecated. Lets use the default constructor and see what is produces:

    Java Code:
    System.out.println(new Date());
    Output:

    Java Code:
    Mon Jan 28 11:51:18 CET 2008

    We may use Date class to find the processing time of some operation. Review the example below:

    Java Code:
    Date d1 = new Date();
    for(int i = 0; i<100;i++)
    {
         System.out.print(".");
    }
    
    Date d2 = new Date();
    long elapsed_time = d2.getTime() - d1.getTime();
    System.out.println("Processing took " + elapsed_time + " milliseconds");
    Output:

    Java Code:
    .................................................. ........................
    ..........................
    Processing took 15 milliseconds
    Date class provides methods before() and after() to compare dates.

    Java Code:
    Date old_date = new Date(24L*60L*60L*1000L);
    Date new_date = new Date();
    System.out.println("Old Date: " + old_date);
    System.out.println("New Date: " + new_date);
    
    if (old_date.before(new_date)) {
    System.out.println("Calculated Date is before the New date.");
    }
    Output:

    Java Code:
    Mon Jan 28 11:58:44 CET 2008
    Old Date: Fri Jan 02 01:00:00 CET 1970
    New Date: Mon Jan 28 11:58:44 CET 2008
    Calculated Date is before the New date.
    The code below gives the current time in milliseconds.

    Java Code:
    Date now = new Date();
    long nowLong = now.getTime();
    System.out.println("Value is " + nowLong);
    java.util.Properties

    Java provides Properties class to save and to retrieve the properties of a program smartly. It is very useful to keep the properties in a file and then use it when required. The following methods are used to load and to store the properties:

    Java Code:
    void   load(InputStream in)
    void   store(OutputStream out, String header)
    Lets take a look at how to set properties:

    Java Code:
    Properties props = new Properties(); 
    props.setProperty("recursiveSearch", "true");
    props.setProperty("noCopyPattern", "*.$$$");
    props.setProperty("maxLevel", "7");
    props.setProperty("fileName", "C:\\temp\\work.html");
    Properties object is seriaziable, so it can be saved on disk. After setting the properties, the props object can be written on the disk using output stream.


    java.util.Random

    Random class generates stream of pseudorandom numbers. It can be used to great affect in applications that require pseudorandom numbers.

    Java Code:
    Random ran = new Random();
    System.out.println("---" + ran.nextInt());
    System.out.println("---" + ran.nextInt());
    Output:

    Java Code:
    ----1154715079
    ---1260042744
    java.util.Locale

    Locale object deals with the geographical details. Different parts of the world have different languages, currencies and time zones. There are some operations that are different for different geographical areas. These are referred as locale-sensitive operations. These operations uses Locale to tailor the information according to the needs.

    Representing numbers is a locale-sensitive operation as formatting of number is different in different parts of the world. The example below prints all the locales available:

    Java Code:
    Locale[] locales = Locale.getAvailableLocales();
    for(int i = 0; i < locales.length; i++){
    String language = locales[i].getLanguage();
    String country = locales[i].getCountry();
    String locale_name = locales[i].getDisplayName();
    System.out.println(i + ": " + language + ", " + country + ", " + locale_name);
    }
    Output:

    Java Code:
    0: es, PE, Spanisch (Peru)
    1: en, , Englisch
    2: es, PA, Spanisch (Panama)
    3: sr, BA, Serbisch (Bosnien und Herzegowina)
    4: mk, , Mazedonisch
    5: es, GT, Spanisch (Guatemala)
    6: no, NO, Norwegisch (Norwegen)
    7: sq, AL, Albanisch (Albanien)
    8: bg, , Bulgarisch
    9: hu, , Ungarisch
    10: pt, PT, Portugiesisch (Portugal)
    11: el, CY, Griechisch (Zypern)
    12: mk, MK, Mazedonisch (Mazedonien)
    13: sv, , Schwedisch
    14: de, CH, Deutsch (Schweiz)
    15: en, US, Englisch (Vereinigte Staaten von Amerika)
    ...
    98: de, DE, Deutsch (Deutschland)
    99: ga, , Irisch
    100: de, LU, Deutsch (Luxemburg)
    101: de, , Deutsch
    102: es, AR, Spanisch (Argentinien)
    103: sk, , Slowakisch
    104: ms, MY, Malay (Malaysia)
    105: hr, HR, Kroatisch (Kroatien)
    106: en, SG, Englisch (Singapur)
    107: da, , Dänisch
    108: mt, , Maltesisch
    109: pl, , Polnisch
    110: tr, , Türkisch
    111: el, , Griechisch
    112: ms, , Malay
    113: sv, SE, Schwedisch (Schweden)
    114: da, DK, Dänisch (Dänemark)
    115: es, HN, Spanisch (Honduras)
    Locale for a country is set using the constructor as shown in the example below:

    Java Code:
    Locale deLocale = new Locale("de", "DE");
    System.out.println("Language: " +
    deLocale.getDisplayLanguage());
    System.out.println("Country: " +
    deLocale.getDisplayCountry());
    Output:

    Java Code:
    Language: Deutsch
    Country: Deutschland
    Now lets take an interesting example. Number formatting varies in different parts of the world. In German language, comma is a decimal point and a decimal point is a comma. Its tricky playing with German numbers but thankfully, Locale is there to help us:

    Java Code:
    Locale deLocale = new Locale("de");
    Locale enLocale = new Locale("en");
    
    NumberFormat nf_en = NumberFormat.getInstance(enLocale);
    System.out.println("Formatted text (en): " + nf_en.format(734547.3343));
    
    NumberFormat nf_de = NumberFormat.getInstance(deLocale);
    System.out.println("Formatted text (de): " + nf_de.format(734547.3343));
    Output:

    Java Code:
    Formatted text (en): 734,547.334
    Formatted text (de): 734.547,334
    java.util.Stack

    Last in first out functionality is provided by Stack. It extends Vector class and provided some methods to use the Vector as a stack. One may call it a restrictive Vector. Following 5 methods are provided in the Stack class:

    Java Code:
    boolean empty() 
    Object peek() 
    Object pop() 
    push(Object item) 
    int search(Object o)
    Lets take a simple example. We will perform push and pop operations on a Stack.

    Java Code:
    Stack stack = new Stack();
    stack.push("Obj1");
    stack.push("Obj2");
    stack.push("Obj3");
    stack.push("Obj4");
    
    System.out.println("Size: " + stack.size());
    
    System.out.println("Stack header is: " + stack.peek());
    System.out.println("Popped value is: " + stack.pop());
    System.out.println("Stack header is: " + stack.peek());
    Output:

    Java Code:
    Size: 4
    Stack header is: Obj4
    Popped value is: Obj4
    Stack header is: Obj3
    java.util.StringTokenizer

    StringTokenizer is a very useful class provided by util package. Consider that you have a string which has delimiters in it. Each delimiter signals end of a token and start of another token. If you plan to use standard string functions like indexOf(…) and subString(..), you may achieve the required output but it will involve a lot of coding. Using StringTokenizer will make life easier for you. Just in fey lines of code, you will achieve the functionality.

    StringTokenizer provides following methods for performing operations:

    Java Code:
    int countTokens()
    boolean hasMoreElements()
    boolean hasMoreTokens()
    Object nextElement()
    String nextToken()
    String nextToken(String delim)
    Time for an example. We have a String which comprises of various countries. Delimiter is semi colon. We want to get country names from that String. In the example below, we will use StringTokenizer for this purpose:

    Java Code:
    		
    String Demo =
    "USA;England;Canada;Germany;France;Sweden;Australia;Brazil";
    
    StringTokenizer Tok = new StringTokenizer(Demo,";");
    System.out.println("Number of tokens: " + Tok.countTokens());
    while (Tok.hasMoreElements())
    System.out.println(Tok.nextElement());
    Output:

    Java Code:
    Number of tokens: 8
    USA
    England
    Canada
    Germany
    France
    Sweden
    Australia
    Brazil
    Java.util.Collection

    Collection is defined as several things grouped together.

    Java collection framework is made up of various interfaces to work with different groups. Implementation of the interfaces allow us to do our job but this means that data structure can be changed without changing the code.

    Java.util package contains an interface called Collection. Collection is an interface which means it defines abstract methods (methods without body). The classes implementing this interface will define the implementation for the abstract methods in the Collection interface.


    Following are the list of classes that implement Collection interface:

    AbstractCollection, AbstractList, AbstractSet, ArrayList, BeanContextServicesSupport, BeanContextSupport, HashSet, LinkedHashSet, LinkedList, TreeSet, Vector


    Conclusion

    Each Java programmer should be aware of java.util package and should use it when needed. It contains utility classes that are used in common programming tasks.

  2. #2
    Join Date
    Jan 2008
    Posts
    4
    Rep Power
    0

    Default

    hi,
    In addition please make a note of the DateFormat and NumberFormat classes which actually belongs to java.text package but are frequently used with the Date classes for formating purpose.
    Regards
    Yo !!!!

Similar Threads

  1. How to use Stack class in java.util package
    By Java Tip in forum java.lang
    Replies: 0
    Last Post: 04-16-2008, 11:32 PM
  2. Using java.util.Stack
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 11-20-2007, 06:17 PM
  3. Using java.util.Formatter
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 11-16-2007, 03:29 PM
  4. java.util.DateFormat not found in import
    By christina in forum New To Java
    Replies: 2
    Last Post: 08-05-2007, 11:31 PM
  5. how to use java.util.Properties?
    By christina in forum New To Java
    Replies: 2
    Last Post: 08-03-2007, 06:26 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •