Download Phys 484 Basic Utility Classes

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

Mirror symmetry (string theory) wikipedia , lookup

Strähle construction wikipedia , lookup

Transcript
Phys 484
Basic Utility Classes
In this lecture we will discuss some commonly used basic Java utility classes. We will
cover the following:
•
•
•
•
•
•
•
•
ArrayList
String
StringBuffer
StringTokenizer
Date
Vector
Hashtable
Properties
ArrayList class
Earlier in the semester some of you asked me about Java array structures that would not
require defining a fixed size. ArrayList class allows you to have an array with any
number of elements in it. In fact, the elements can be of any class type.
We will discuss ArrayList with an example. See Listing 1 below.
In line 3 we import the ArrayList class in order to be able to use it.
In line 9 we instantiate an array list of String objects. Note that you can define an array
list of any objects. (As an exercise, try to use one of the earlier examples we had.) Just
use the syntax
ArrayList<CLASS_TYPE>
In lines 14-17 we add entries to the array list. Note that the index of the entry is
incremented under the covers. There is another way to add an entry in which you can
explicitly specify the index.
In lines 22-26 we loop over the array list. Note that size() method returns the number of
entries in the array list. get(i) returns the element in location i.
In lines 31-34 we show a new way to loop over array list. This was introduced to Java
language in version 5. Look at the syntax closely. You will need to first specify the class
type and define a variable (String name), use a “:”, and then, place the arraylist variable.
Odd looking at first, but once you get used to it, the code looks pretty neat.
Listing 1. ArrayList example
Array list has quite a few other methods that we will not cover here, but will point you to
the documentation for it. Note that this is standard in Java: one goes to the Java doc to
get the details of each method. In listing 2 we show all the methods from an Eclipse
snapshot and here is the complete documentation:
http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html
Listing 2. All methods of ArrayList class.
String class
A string object can be constructed without using the new operator:
String s = “This is a string constructed without new”;
This string could also be constructed as follows:
String s = new String(“This is a string constructed with new”);
Instances of String class are immutable. (An immutable object is an object whose
state cannot be modified after it is created.)
String s = “abc”;
String s1 = “def”;
s = s + s1;
The plus operator does not change the string “abc” physically. It creates a new string
and have variable s point to it.
String class is final. I have not introduced this concept before. A “final” class is one that
cannot be extended. So, you cannot inherit from String class.
Here are some of the commonly used String methods:
•
•
•
•
•
•
•
•
•
•
•
•
equals() : compares to another String
equalsIgnoreCase() : compares while ignoring letter case
compareTo() : compares two strings lexicographically.
indexof() : finds the index of occurrence of a string within a string
lastIndexOf() : similar to the previous one. Finds the last occurrence
startsWith() : Tests if this string starts with the specified prefix.
endsWith() : Tests if this string ends with the specified prefix.
toLowercase() : converts a string to lower case
substring() : returns a new string that is a substring of this one
toUpperCase() : converts to upper caae
trim() : removes spaces around a string
valueOf() : returns a string representation of the given object
I should emphasize here that I do not expect you to memorize these methods. You will
remember some of them as you use String class over and over, but you may need to look
up javadoc for some methods. Eclipse code-complete feature is very helpful for you to
remember a method. When you type “.” after a variable name, Eclipse will automatically
bring up the list of methods that the class of that object variable has. You can then go
through the list and remember what you are looking for. There is always the Javadoc, of
course:
http://docs.oracle.com/javase/6/docs/api/java/lang/String.html
See the String example in sample code for some of these methods.
StringBuffer class
StringBuffer class instances are mutable. That is, the object state can change.
(Remember that this is not true for String class objects.)
StingBuffer class is final. You cannot extend it to define a new class.
You can convert a String using StringBuffer class's toString() method as follows:
StringBuffer sb = “This is a string buffer string”;
String s = sb.toString();
or
String s = new String(sb);
Most commonly used methods are:
•
•
•
•
•
•
append()
insert()
length()
reverse()
setCharAt()
toString()
Javadoc for StringBuffer class is here:
http://docs.oracle.com/javase/6/docs/api/java/lang/StringBuffer.html
Why would you need a StringBuffer object while you have the simpler-looking String
class? Consider the following string addition:
String s = s1 + s2;
Quite innocent looking. However, this operation is rather expensive. Under the covers it
creates StringBuffer objects, appends, and then, instantiates a final string object. That is
a lot of overhead. If you have a few such operations, using string addition is OK.
However, if you have a program that does thousands of these operations frequently, it
can slow down significantly and you rather look into using StringBuffer. (I reduced the
performance of such a program from about 2 minutes down to seconds after noticing that
this was the problem.)
See the sample program for examples of StrinBuffer use.
StringTokenizer class
This class is in java.util package. It allows you to cut a string that has various substrings
separated by any character like “:”, “|”, “;”, “ “, etc into the individual elements. For
instance, assume you have the following:
String s = “Istanbul:Ankara:Izmir:Antalya”;
and you are asked to print the individual city names. What you can do is to define a
string tokenizer as follows:
StringTokenizer st = new StringTokenizer(s, “:”);
Note that I used “:” as the delimiter. Then,
while (st.hasMoreTokens())
{
String token = st.nextToken();
System.out.println("Next city name is " + token);
}
Note that I highlighted important methods in bold. Listing 3 below has the complete
sample program. Javadoc for StringTokenizer class is here:
http://docs.oracle.com/javase/1.4.2/docs/api/java/util/StringTokenizer.html
Listing 3. StringTokenizer class.
Class Date
Date objects represents a specific date and time. Important methods are create(), set(),
compare() and extract().
Here is an example: let's say you would like to print today's date. Java has some utilities
like giving you the time of the day in milliseconds since the first day of 1970 as follows:
long timeNow = System.currenttimemillis();
You can construct a Date object from this as follows:
Date todaysDate = new Date(timeNow);
And print it as follows:
System.out.println(“Today's date is ” + todaysDate);
The output is
Today's date is Fri Nov 25 10:29:03 EST 2011
You can instantiate Date objetcs as follows:
new Date(“November 25, 2011”);
or
new Date(“25 November 2011”)
The Javadoc for Date class is here:
http://docs.oracle.com/javase/6/docs/api/java/sql/Date.html
Also, see the sample program I provided.
Class Vector
Vector class is like a dynamically growing array. Similar to ArrayList, it can store objects
of any type. It cannot store primitive types like int, double, etc. (There is a trick to
doing that.) It provides methods to insert/remove elements into any positions. It also
provides methods to enumerate through array of Object references.
Here is an example to create a vector and add some elements to it.
Vector<String> vector = new Vector<String>();
String s1= "one";
String s2 = "two";
String s3 = "three";
vector.addElement(s1);
vector.addElement(s2);
vector.add(s3);
Here is the Javadoc:
http://docs.oracle.com/javase/6/docs/api/java/util/Vector.html
Also, see the sample program.
HashTable Class
Consider the following problem: you need to implement an English-Turkish dictionary
such that people will be able to search words and look up meanings. Assume this
dictionary will have 10,000 words. How would you go about this problem? Would you
store all words alphabetically in an array of 10,000 elements? If so, when a user looks
up a word, how would you locate it in this array of 10,000 words? Would you search
through it linearly? If a lot of users is trying to access your program, that would be a
performance nightmare. Well, hashtables to the rescue …
A Hashtable allows you to store multiple objects such that you can access them via a key
. Let's continue with our dictionary example and assume we keep a single Turkish
translation of each English word in the dictionary. (We know that is not true, but let's
simplify the problem.) You can define the dictionary as
Hashtable<String, String> dictionary = new Hashtable<String, String>();
Now, put four words in the dictionary as an example:
dictionary.put("good", "iyi");
dictionary.put("bad", "kotu");
dictionary.put("ok", "tamam");
dictionary.put("excellent", "mukemmel");
And now, look up the meaning of one word:
String englishWord = "good";
String turkishTranslation = dictionary.get(englishWord);
And print:
System.out.println("Turkish word for " + englishWord + " is " +
turkishTranslation);
In general, you will need to use Hashtable if your search is not based on an index that
can easily be mapped to an array index, like names, student numbers, etc.
Javadoc for Hashtable:
http://docs.oracle.com/javase/6/docs/api/java/util/Hashtable.html
There is also a related class called HashMap. See the Javadoc and as an exercise try to
figure out the difference:
http://docs.oracle.com/javase/6/docs/api/java/util/HashMap.html
Also, see the sample program.