5/1/07

Collector class in java

Arrays, in java language, has fix size, member must be same type. We must known size of it before create array.

This post is note about some collector classes in package java.util
Vector will use to collect 'instance of class', can vary size, member doesn't need to be same type. Vector use much memory, not suitable to store or transfer over network. So use Vector to store data, after finish change Vector to Enumeration by

Enumeration e = v.elements();

Stack is order oriented data structure i.e. 'pop' and 'push' data from one side of stack. It based on the principle of Last In First Out. Member in stack must be instance of class like vector, data in primitive type need to change to be instance of 'type wrapper class' before pop into it.
example
import java.util.*;
class StackTest1 {
public static void main(String[] args) {
String t[] = {"Hello", "how", "do", "you", "do?"};
Stack s = new Stack();
for (int i = 0; i < t.length; i++)
s.push(t[i]);
while (!s.empty())
System.out.print(s.pop() + " ");
}
}

Hashtable use to store pair (key,value).
Properties extends from Hashtable and more popular. It use to store pair value of String and String.
example below show the usage
import java.util.*;
import java.io.*;
class PropertyTest {
public static void main(String[] args) throws IOException {
Properties p1 = new Properties();
p1.put("500", "John Rambo");
p1.put("123", "Jack Ripper");
p1.put("741", "Bill Gate");
/*use getProperty, getPropertyNames*/
System.out.println(p1.getProperty("123"));
//return default value if no key
System.out.println(p1.getProperty("999", "Bob Dylan"));
Enumeration e = p1.propertyNames();
while (e.hasMoreElements())
System.out.print(e.nextElement()+",");
/*save/get properties with file*/
FileOutputStream fo = new FileOutputStream("tmp");
p1.store(fo, "My Properties File");
fo.close();
FileInputStream fi = new FileInputStream("tmp");
Properties p2 = new Properties();
p2.load(fi);
p2.list(System.out);
}
}

0 comments: