This code reads and prints the name of all the files and folders in a particular parent folder.
import java.io.File;
public class DirectoryReader {
public static void main(String[] args) {
File folder = new File("c:/");
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
System.out.println("File " + listOfFiles[i].getName());
} else if (listOfFiles[i].isDirectory()) {
System.out.println("Directory " + listOfFiles[i].getName());
}
}
}
}
Friday, September 21, 2007
Wednesday, September 19, 2007
Tip: BlackBerry - Syncing PIM Data with Microsoft Outlook
By Amy Mayer
February 1, 2008
Setting up your Blackberry to synchronize with Microsoft Outlook means your contacts, appointments and tasks can be updated either from your smartphone or at your desk.
Here's how to do it:
Once you have the Blackberry Device Manager installed, launch it from your computer and click on Synchronize. Select the Configuration tab.
When you click on "configure synch" you'll be prompted with a box that allows you to select the feature (such as address book or tasks) and then select the software that's on your computer (in addition to Outlook, the Device Manager is prepared to work with Lotus Organizer, Novell GroupWise, Sage ACT! and others).
After selecting the appropriate software and whether you want the two machines to be synchronized or you simply want to import or export from one to the other, you can select Configure-->advanced settings to further customize your synchronization.
Here, you can decide which device overrides the other or if you want all data to be shared between the two. You can also apply filters and adjust the field mapping terms.
When you've got the settings the way you want them, click OK on the configuration box and Close on the synchronization box.
Now, when you click Synchronize from the Device Manager, you just have to click Synchronize Now and all your data will be shared. If you click the Automatic Synchronization box then you won't even need to tell the manager to synchronize, just connect your BlackBerry to your computer and your data will flow.
February 1, 2008
Setting up your Blackberry to synchronize with Microsoft Outlook means your contacts, appointments and tasks can be updated either from your smartphone or at your desk.
Here's how to do it:
Once you have the Blackberry Device Manager installed, launch it from your computer and click on Synchronize. Select the Configuration tab.
When you click on "configure synch" you'll be prompted with a box that allows you to select the feature (such as address book or tasks) and then select the software that's on your computer (in addition to Outlook, the Device Manager is prepared to work with Lotus Organizer, Novell GroupWise, Sage ACT! and others).
After selecting the appropriate software and whether you want the two machines to be synchronized or you simply want to import or export from one to the other, you can select Configure-->advanced settings to further customize your synchronization.
Here, you can decide which device overrides the other or if you want all data to be shared between the two. You can also apply filters and adjust the field mapping terms.
When you've got the settings the way you want them, click OK on the configuration box and Close on the synchronization box.
Now, when you click Synchronize from the Device Manager, you just have to click Synchronize Now and all your data will be shared. If you click the Automatic Synchronization box then you won't even need to tell the manager to synchronize, just connect your BlackBerry to your computer and your data will flow.
Monday, September 17, 2007
Tip: BlackBerry - Number Lock & CAPS Lock
By Amy Mayer
February 7, 2008
You BlackBerry’s NUM lock function can come in handy when you need to use your keypad as a number pad. While not super-obvious, it is easier to locate than your smartphone’s CAPS lock.
# To launch num lock:
Hold the # (also the shift) key down, then press ALT.
When you're ready to return to letters:
simply press the ALT key.
# CAPS lock takes a bit more effort launch. If all you want is one capital letter, just press the # key, then the letter you want capitalized. But for CAPS lock, the key combination is :
# and the green phone button.
That's right, you hold down the #, or shift, key and then you press the green button as though you were going to make a phone call.
Exit the phone screen and you'll go back to your message with CAPS lock on. To turn it off:
again press # and the green phone.
Cumbersome? Yes. But maybe just enough to calm your rage so you don’t send that message in all caps after all.
February 7, 2008
You BlackBerry’s NUM lock function can come in handy when you need to use your keypad as a number pad. While not super-obvious, it is easier to locate than your smartphone’s CAPS lock.
# To launch num lock:
Hold the # (also the shift) key down, then press ALT.
When you're ready to return to letters:
simply press the ALT key.
# CAPS lock takes a bit more effort launch. If all you want is one capital letter, just press the # key, then the letter you want capitalized. But for CAPS lock, the key combination is :
# and the green phone button.
That's right, you hold down the #, or shift, key and then you press the green button as though you were going to make a phone call.
Exit the phone screen and you'll go back to your message with CAPS lock on. To turn it off:
again press # and the green phone.
Cumbersome? Yes. But maybe just enough to calm your rage so you don’t send that message in all caps after all.
How to use Comparable Interface
List of objects that implement this interface can be sorted automatically by sort method of the list interface. This interface has compareTo() method that is used by the sort() method of the list.
In this code Employee class is implementing Comparable interface and have method compareTO(). ComparableDemo.java is showing the use of this interface. This class first makes a list of objects of type Employee and call sort method of java.util.Collections, which internally uses compareTo() method of Employee class and sort the list accordingly.
Employee.java
public class Employee implements Comparable {
int EmpID;
String Ename;
double Sal;
static int i;
public Employee() {
EmpID = i++;
Ename = "dont know";
Sal = 0.0;
}
public Employee(String ename, double sal) {
EmpID = i++;
Ename = ename;
Sal = sal;
}
public String toString() {
return "EmpID " + EmpID + "\n" + "Ename " + Ename + "\n" + "Sal" + Sal;
}
public int compareTo(Object o1) {
if (this.Sal == ((Employee) o1).Sal)
return 0;
else if ((this.Sal) > ((Employee) o1).Sal)
return 1;
else
return -1;
}
}
ComparableDemo.java
import java.util.*;
public class ComparableDemo{
public static void main(String[] args) {
List ts1 = new ArrayList();
ts1.add(new Employee ("Tom",40000.00));
ts1.add(new Employee ("Harry",20000.00));
ts1.add(new Employee ("Maggie",50000.00));
ts1.add(new Employee ("Chris",70000.00));
Collections.sort(ts1);
Iterator itr = ts1.iterator();
while(itr.hasNext()){
Object element = itr.next();
System.out.println(element + "\n");
}
}
}
Output:
EmpID 1
Ename Harry
Sal20000.0
EmpID 0
Ename Tom
Sal40000.0
EmpID 2
Ename Maggie
Sal50000.0
EmpID 3
Ename Chris
Sal70000.0
In this code Employee class is implementing Comparable interface and have method compareTO(). ComparableDemo.java is showing the use of this interface. This class first makes a list of objects of type Employee and call sort method of java.util.Collections, which internally uses compareTo() method of Employee class and sort the list accordingly.
Employee.java
public class Employee implements Comparable {
int EmpID;
String Ename;
double Sal;
static int i;
public Employee() {
EmpID = i++;
Ename = "dont know";
Sal = 0.0;
}
public Employee(String ename, double sal) {
EmpID = i++;
Ename = ename;
Sal = sal;
}
public String toString() {
return "EmpID " + EmpID + "\n" + "Ename " + Ename + "\n" + "Sal" + Sal;
}
public int compareTo(Object o1) {
if (this.Sal == ((Employee) o1).Sal)
return 0;
else if ((this.Sal) > ((Employee) o1).Sal)
return 1;
else
return -1;
}
}
ComparableDemo.java
import java.util.*;
public class ComparableDemo{
public static void main(String[] args) {
List ts1 = new ArrayList();
ts1.add(new Employee ("Tom",40000.00));
ts1.add(new Employee ("Harry",20000.00));
ts1.add(new Employee ("Maggie",50000.00));
ts1.add(new Employee ("Chris",70000.00));
Collections.sort(ts1);
Iterator itr = ts1.iterator();
while(itr.hasNext()){
Object element = itr.next();
System.out.println(element + "\n");
}
}
}
Output:
EmpID 1
Ename Harry
Sal20000.0
EmpID 0
Ename Tom
Sal40000.0
EmpID 2
Ename Maggie
Sal50000.0
EmpID 3
Ename Chris
Sal70000.0
Tuesday, September 11, 2007
Difference between String StringBuffer and StringBuilder
String is immutable whereas StringBuffer and StringBuilder can change their values.
The only difference between StringBuffer and StringBuilder is that StringBuilder is unsynchronized whereas StringBuffer is synchronized. So when the application needs to be run only in a single thread then it is better to use StringBuilder. StringBuilder is more efficient than StringBuffer.
Criteria to choose among String, StringBuffer and StringBuilder
1. If your text is not going to change use a string Class because a String object is immutable.
2. If your text can change and will only be accessed from a single thread, use a StringBuilder because StringBuilder is unsynchronized.
3. If your text can changes, and will be accessed from multiple threads, use a StringBuffer because StringBuffer is synchronous.
The only difference between StringBuffer and StringBuilder is that StringBuilder is unsynchronized whereas StringBuffer is synchronized. So when the application needs to be run only in a single thread then it is better to use StringBuilder. StringBuilder is more efficient than StringBuffer.
Criteria to choose among String, StringBuffer and StringBuilder
1. If your text is not going to change use a string Class because a String object is immutable.
2. If your text can change and will only be accessed from a single thread, use a StringBuilder because StringBuilder is unsynchronized.
3. If your text can changes, and will be accessed from multiple threads, use a StringBuffer because StringBuffer is synchronous.
Saturday, September 08, 2007
Tip: Using Your BlackBerry as an MP3 Player
By Amy Mayer
February 8, 2008
Click to View
Now that you've grown an awesome digital music library on your desktop—maybe it's even replaced CDs as your music-medium of choice—isn't it time you enjoyed choice selections on your BlackBerry? Whether your all-in-one replaces your iPod remains to be seen, but to get music onto your BlackBerry, you'll need to connect it to your computer and launch the Device Manager.
To maximize the amount of music you can transfer, and minimize the impact on your BlackBerry's device memory, install a media card, the larger the capacity the better. Then, activate mass storage mode on the BlackBerry by selecting Options from the home screen and then Advanced Options„³Media Card„³Mass Storage Mode Support„³ON.
(You can use the Device Memory to store your music files, but they will take up considerable room quickly.)
From the Device Manager, click on Media Manager: The Media Manager will open a file transfer screen. Use the top-left corner to navigate to the place where your music files are stored on your computer. On the lower left area, indicate if you wish to store to a media card or your Device Memory.
When you select folders in the upper-left corner, the contents appear on the upper-right side. Select songs you want to copy and use the "Copy Down" button to place them on your BlackBerry. You'll be prompted with the question of whether to convert or not. Converting should reduce the strain on your BlackBerry's resources if you're using Device Memory. Whether you'll hear a difference after conversion depends on your ears, your device's speaker and whether you're using a headset.
To playback on the BlackBerry, select Media from the home screen. Then select Music. If you haven't placed your music in this folder, you may need to browse to find your music folder. But once you do, just click a file to play it.
The amount of music you can store will be limited by what else you're keeping on your device. But since it's quick and easy to copy files, you can always trash the tunes you're bored with and copy on some new ones. As for listening, if those around you tire of hearing your taste over the built-in speaker, then that's another reason to consider a headset.
February 8, 2008
Click to View
Now that you've grown an awesome digital music library on your desktop—maybe it's even replaced CDs as your music-medium of choice—isn't it time you enjoyed choice selections on your BlackBerry? Whether your all-in-one replaces your iPod remains to be seen, but to get music onto your BlackBerry, you'll need to connect it to your computer and launch the Device Manager.
To maximize the amount of music you can transfer, and minimize the impact on your BlackBerry's device memory, install a media card, the larger the capacity the better. Then, activate mass storage mode on the BlackBerry by selecting Options from the home screen and then Advanced Options„³Media Card„³Mass Storage Mode Support„³ON.
(You can use the Device Memory to store your music files, but they will take up considerable room quickly.)
From the Device Manager, click on Media Manager: The Media Manager will open a file transfer screen. Use the top-left corner to navigate to the place where your music files are stored on your computer. On the lower left area, indicate if you wish to store to a media card or your Device Memory.
When you select folders in the upper-left corner, the contents appear on the upper-right side. Select songs you want to copy and use the "Copy Down" button to place them on your BlackBerry. You'll be prompted with the question of whether to convert or not. Converting should reduce the strain on your BlackBerry's resources if you're using Device Memory. Whether you'll hear a difference after conversion depends on your ears, your device's speaker and whether you're using a headset.
To playback on the BlackBerry, select Media from the home screen. Then select Music. If you haven't placed your music in this folder, you may need to browse to find your music folder. But once you do, just click a file to play it.
The amount of music you can store will be limited by what else you're keeping on your device. But since it's quick and easy to copy files, you can always trash the tunes you're bored with and copy on some new ones. As for listening, if those around you tire of hearing your taste over the built-in speaker, then that's another reason to consider a headset.
Friday, September 07, 2007
How to use HashSet
HashSet class is a concrete implementation of Set interface. It creates a collection that uses a hash table for storage. Hash table stores information by using a mechanism called hashing. In hashing, the informational content of a key is used to determine a unique value, called its hash code. The hash code is then used as an index at which the data associated with the key is stored. The transformation of key into its hash code is performed automatically. You never see the hash code itself. The advantage of hashing is that it allows the execution time of basic operation, such as add(), contains(), remove(), and size() to remain constant even for large sets.
HashSet is not synchronized. If more than one thread wants to access it at the same time then it must be synchronized externally.
This code shows the use of HashSet. This will identify the number of duplicate words in a String. The String is passed as command line arguments.
Add() method of the HashSet add the object into the storage if it is not already present.
import java.util.*;
public class FindDups {
public static void main(String[] args) {
Set s = new HashSet();
for(int i=0; i if(!s.add(args[i]))
System.out.println("Duplicate detected : " + args[i]);
}
System.out.println(s.size() + " distinct words detected : " + s );
}
}
Run the program: C:\> java FindDups i came i came i conquered
Output Screen :
Duplicate detected: i
Duplicate detected: i
4 distinct words detected : [came,saw,conquered,i]
HashSet is not synchronized. If more than one thread wants to access it at the same time then it must be synchronized externally.
This code shows the use of HashSet. This will identify the number of duplicate words in a String. The String is passed as command line arguments.
Add() method of the HashSet add the object into the storage if it is not already present.
import java.util.*;
public class FindDups {
public static void main(String[] args) {
Set s = new HashSet();
for(int i=0; i
System.out.println("Duplicate detected : " + args[i]);
}
System.out.println(s.size() + " distinct words detected : " + s );
}
}
Run the program: C:\> java FindDups i came i came i conquered
Output Screen :
Duplicate detected: i
Duplicate detected: i
4 distinct words detected : [came,saw,conquered,i]
The Enhanced For Loop
This Tech Tip reprinted with permission by java.sun.com
Introduced as a new language feature in J2SE 5.0, the enhanced for loop allows you to iterate through a collection without having to create an Iterator or without having to calculate beginning and end conditions for a counter variable. The enhanced for loop is the easiest of the new features to immediately incorporate in your code. In this tip you will see how the enhanced for loop replaces more traditional ways of sequentially accessing elements in a collection.
So what does an enhanced for loop look like? Suppose you have a collection of TechTip objects called RecentTips. You could use an enhanced for loop with the collection as follows:
for (TechTip tip: RecentTips)
You read this as "for each TechTip in RecentTips". Here the variable tip is used to point to the current instance of TechTip in the collection. Because of the "for each" wording, the enhanced-for construct is also referred to as the for-each construct.
If you compare the enhanced for loop to the typical way of iterating over a collection, it's clear that the for each loop is simpler and can make your code more readable.
Also note that the enhanced for loop is designed to simplify your work with generics. Although this tip does include two examples of using the enhanced for loop with generics, it's not the focus of the tip. Instead the objective of this tip is to introduces you to the more basic changes you can make to your code to use the for each loop.
First, consider how you might use a for loop to iterate through the elements of an Array. For simplicity, load an array with six ints that represent the squares of the ints from zero to five. Here's a for loop that does the iteration:
for (int i=0; i< squares.length; i++)
The line illustrates the classic use of the for loop. It specifies the initial value of one or more counters, sets up a terminating condition, and describes how the counters might be incremented.
Here is a short program, OldForArray, that uses the for loop.
public class OldForArray {
public static void main(String[] args){
int[] squares = {0,1,4,9,16,25};
for (int i=0; i< squares.length; i++){
System.out.printf("%d squared is %d.\n",i, squares[i]);
}
}
}
Compile and run the OldForArray program, and you get the following:
0 squared is 0.
1 squared is 1.
2 squared is 4.
3 squared is 9.
4 squared is 16.
5 squared is 25.
If you change the test program to use the enhanced for loop, you specify the relevant variable and the collection that the variable comes from. Here is a line that's an enhanced for loop:
for (int i : squares)
You can read the line as "iterate on elements from the collection named squares. "The current element will be referenced by the int i."
You don't need to determine how many elements are in the array before looping. There is also no need to specify how to increment the current position. "Under the covers," the enhanced for loop for an array is equivalent to the for loop presented earlier.
The test program NewForArray gives the same result as OldForArray.
public class NewForArray {
public static void main(String[] args) {
int j = 0;
int[] squares = {0, 1, 4, 9, 16, 25};
for (int i : squares) {
System.out.printf("%d squared is %d.\n", j++, i);
}
}
}
An array is an indexed collection of elements of a single type that is specified when the array is declared. With more general collections such as ArrayLists, the elements are stored as Objects. You could use the C style for loop to iterate through a collection like this:
for (int i = 0; i < list.size(); i++)
You then can use list.get(i) to reference the current element. For example, the following program, OldForArrayList, uses autoboxing to fill the ArrayList and to then read from the ArrayList:
import java.util.ArrayList;
import java.util.List;
public class OldForArrayList {
private static List squares = new ArrayList();
private static void fillList() {
for (int i = 0; i < 6; i++) {
squares.add(i * i);
}
}
private static void outputList() {
for (int i = 0; i < squares.size(); i++) {
System.out.printf("%d squared is %d.\n",
i, squares.get(i));
}
}
public static void main(String args[]) {
fillList();
outputList();
}
}
However, because ArrayList is part of the collections framework, it is more common to iterate through it using an Iterator in the following pattern:
while( iterator.hasNext()) {
doSomethingWith (iterator.next());
}
You can bundle this in a for loop as shown in the following program, IteratorForArrayList:
import java.util.ArrayList;
import java.util.List;
import java.util.Iterator;
public class IteratorForArrayList {
private static List squares = new ArrayList();
private static void fillList() {
for (int i = 0; i < 6; i++) {
squares.add(i * i);
}
}
private static void outputList() {
Iterator iterator = squares.iterator();
int j=0;
for (; iterator.hasNext();) {
System.out.printf("%d squared is %d.\n",
j++, iterator.next());
}
}
public static void main(String args[]) {
fillList();
outputList();
}
}
It looks a bit unusual to have a for loop with no first or third parameter. There is no initial condition, and the incrementing of the position in the List is performed in the body of the for loop with the call iterator.next().
The enhanced for loop makes the explicit use of an iterator unnecessary. Rather than create an Iterator object for the ArrayList and then use the iterator in the for loop, you use the following:
for ( Integer square : squares)
This indicates that the name of the collection is squares. It also indicates that the currently referenced item is of type Integer and is referenced by the variable square.
This code will not compile because there is no way of knowing that the contents of the ArrayList is of type Integer. To fix this, you need to use another feature introduced in J2SE 5.0, namely generics. You need to specify in the declaration and definition of squares that it can only hold elements of type Integer. You do this as follows:
private static List squares
= new ArrayList();
The following program, NewArrayList, shows how to use the enhanced for loop together with generics:
import java.util.List;
import java.util.ArrayList;
public class NewArrayList {
private static List squares
= new ArrayList();
private static void fillList() {
for (int i = 0; i < 6; i++) {
squares.add(i * i);
}
}
private static void outputList() {
int j=0;
for (Integer square : squares) {
System.out.printf("%d squared is %d.\n",
j++, square);
}
}
public static void main(String args[]) {
fillList();
outputList();
}
}
This NewArrayList example is a bit simplistic, but it demonstrates the syntactic differences between using the classic for loop and the enhanced for loop. Here is another example that compares the syntactic differences between the loops. The example is excerpted from a talk given by Joshua Bloch and Neil Gafter at the 2004 JavaOne Conference. In the example, a method is applied to each element in a collection. To start, the example uses an Iterator like this:
void cancelAll (Collection c) {
for (Iterator i = c.iterator(); i.hasNext(); ) {
TimerTask tt = (TimerTask) i.next();
tt.cancel();
}
}
Next, an enhanced for loop is introduced to eliminate the use of the Iterator:
void cancelAll( Collection c ) {
for (Object o : c)
( (TimerTask) o). cancel();
}
There is still a matter of having to treat the elements of the collection as being of type Object and then casting them to type TimerTask. This is fixed by introducing generics like this:
void cancelAll( Collection c ) {
for (TimerTask task : c)
task.cancel();
}
It's important to note that the enhanced for loop can't be used everywhere. You can't use the enhanced for loop:
* To remove elements as you traverse collections
* To modify the current slot in an array or list
* To iterate over multiple collections or arrays
However aside from these cases, you should try to use the enhanced for loop code to simplify your code.
As with anything new, the syntax for the enhanced for loop might seem unfamiliar and difficult to read. You have probably used the C style for loop for many years and possibly in more than one language. It is, however, cleaner not having to create a counter variable or an Iterator. You also do not need to worry about where your collection begins and ends to set up the initial value and loop termination conditions.
For more information on the enhanced for loop, see The For-Each Loop.
Copyright (c) 2004-2005 Sun Microsystems, Inc.
All Rights Reserved.
Introduced as a new language feature in J2SE 5.0, the enhanced for loop allows you to iterate through a collection without having to create an Iterator or without having to calculate beginning and end conditions for a counter variable. The enhanced for loop is the easiest of the new features to immediately incorporate in your code. In this tip you will see how the enhanced for loop replaces more traditional ways of sequentially accessing elements in a collection.
So what does an enhanced for loop look like? Suppose you have a collection of TechTip objects called RecentTips. You could use an enhanced for loop with the collection as follows:
for (TechTip tip: RecentTips)
You read this as "for each TechTip in RecentTips". Here the variable tip is used to point to the current instance of TechTip in the collection. Because of the "for each" wording, the enhanced-for construct is also referred to as the for-each construct.
If you compare the enhanced for loop to the typical way of iterating over a collection, it's clear that the for each loop is simpler and can make your code more readable.
Also note that the enhanced for loop is designed to simplify your work with generics. Although this tip does include two examples of using the enhanced for loop with generics, it's not the focus of the tip. Instead the objective of this tip is to introduces you to the more basic changes you can make to your code to use the for each loop.
First, consider how you might use a for loop to iterate through the elements of an Array. For simplicity, load an array with six ints that represent the squares of the ints from zero to five. Here's a for loop that does the iteration:
for (int i=0; i< squares.length; i++)
The line illustrates the classic use of the for loop. It specifies the initial value of one or more counters, sets up a terminating condition, and describes how the counters might be incremented.
Here is a short program, OldForArray, that uses the for loop.
public class OldForArray {
public static void main(String[] args){
int[] squares = {0,1,4,9,16,25};
for (int i=0; i< squares.length; i++){
System.out.printf("%d squared is %d.\n",i, squares[i]);
}
}
}
Compile and run the OldForArray program, and you get the following:
0 squared is 0.
1 squared is 1.
2 squared is 4.
3 squared is 9.
4 squared is 16.
5 squared is 25.
If you change the test program to use the enhanced for loop, you specify the relevant variable and the collection that the variable comes from. Here is a line that's an enhanced for loop:
for (int i : squares)
You can read the line as "iterate on elements from the collection named squares. "The current element will be referenced by the int i."
You don't need to determine how many elements are in the array before looping. There is also no need to specify how to increment the current position. "Under the covers," the enhanced for loop for an array is equivalent to the for loop presented earlier.
The test program NewForArray gives the same result as OldForArray.
public class NewForArray {
public static void main(String[] args) {
int j = 0;
int[] squares = {0, 1, 4, 9, 16, 25};
for (int i : squares) {
System.out.printf("%d squared is %d.\n", j++, i);
}
}
}
An array is an indexed collection of elements of a single type that is specified when the array is declared. With more general collections such as ArrayLists, the elements are stored as Objects. You could use the C style for loop to iterate through a collection like this:
for (int i = 0; i < list.size(); i++)
You then can use list.get(i) to reference the current element. For example, the following program, OldForArrayList, uses autoboxing to fill the ArrayList and to then read from the ArrayList:
import java.util.ArrayList;
import java.util.List;
public class OldForArrayList {
private static List squares = new ArrayList();
private static void fillList() {
for (int i = 0; i < 6; i++) {
squares.add(i * i);
}
}
private static void outputList() {
for (int i = 0; i < squares.size(); i++) {
System.out.printf("%d squared is %d.\n",
i, squares.get(i));
}
}
public static void main(String args[]) {
fillList();
outputList();
}
}
However, because ArrayList is part of the collections framework, it is more common to iterate through it using an Iterator in the following pattern:
while( iterator.hasNext()) {
doSomethingWith (iterator.next());
}
You can bundle this in a for loop as shown in the following program, IteratorForArrayList:
import java.util.ArrayList;
import java.util.List;
import java.util.Iterator;
public class IteratorForArrayList {
private static List squares = new ArrayList();
private static void fillList() {
for (int i = 0; i < 6; i++) {
squares.add(i * i);
}
}
private static void outputList() {
Iterator iterator = squares.iterator();
int j=0;
for (; iterator.hasNext();) {
System.out.printf("%d squared is %d.\n",
j++, iterator.next());
}
}
public static void main(String args[]) {
fillList();
outputList();
}
}
It looks a bit unusual to have a for loop with no first or third parameter. There is no initial condition, and the incrementing of the position in the List is performed in the body of the for loop with the call iterator.next().
The enhanced for loop makes the explicit use of an iterator unnecessary. Rather than create an Iterator object for the ArrayList and then use the iterator in the for loop, you use the following:
for ( Integer square : squares)
This indicates that the name of the collection is squares. It also indicates that the currently referenced item is of type Integer and is referenced by the variable square.
This code will not compile because there is no way of knowing that the contents of the ArrayList is of type Integer. To fix this, you need to use another feature introduced in J2SE 5.0, namely generics. You need to specify in the declaration and definition of squares that it can only hold elements of type Integer. You do this as follows:
private static List squares
= new ArrayList();
The following program, NewArrayList, shows how to use the enhanced for loop together with generics:
import java.util.List;
import java.util.ArrayList;
public class NewArrayList {
private static List
= new ArrayList
private static void fillList() {
for (int i = 0; i < 6; i++) {
squares.add(i * i);
}
}
private static void outputList() {
int j=0;
for (Integer square : squares) {
System.out.printf("%d squared is %d.\n",
j++, square);
}
}
public static void main(String args[]) {
fillList();
outputList();
}
}
This NewArrayList example is a bit simplistic, but it demonstrates the syntactic differences between using the classic for loop and the enhanced for loop. Here is another example that compares the syntactic differences between the loops. The example is excerpted from a talk given by Joshua Bloch and Neil Gafter at the 2004 JavaOne Conference. In the example, a method is applied to each element in a collection. To start, the example uses an Iterator like this:
void cancelAll (Collection c) {
for (Iterator i = c.iterator(); i.hasNext(); ) {
TimerTask tt = (TimerTask) i.next();
tt.cancel();
}
}
Next, an enhanced for loop is introduced to eliminate the use of the Iterator:
void cancelAll( Collection c ) {
for (Object o : c)
( (TimerTask) o). cancel();
}
There is still a matter of having to treat the elements of the collection as being of type Object and then casting them to type TimerTask. This is fixed by introducing generics like this:
void cancelAll( Collection c ) {
for (TimerTask task : c)
task.cancel();
}
It's important to note that the enhanced for loop can't be used everywhere. You can't use the enhanced for loop:
* To remove elements as you traverse collections
* To modify the current slot in an array or list
* To iterate over multiple collections or arrays
However aside from these cases, you should try to use the enhanced for loop code to simplify your code.
As with anything new, the syntax for the enhanced for loop might seem unfamiliar and difficult to read. You have probably used the C style for loop for many years and possibly in more than one language. It is, however, cleaner not having to create a counter variable or an Iterator. You also do not need to worry about where your collection begins and ends to set up the initial value and loop termination conditions.
For more information on the enhanced for loop, see The For-Each Loop.
Copyright (c) 2004-2005 Sun Microsystems, Inc.
All Rights Reserved.
Thursday, September 06, 2007
Tip: Changing BlackBerry SIM cards
By Amy Mayer
February 8, 2008
Though it's possible to remove a SIM (subscriber identity module) card and swap it between compatible devices, how you do it varies, even among BlackBerry wireless handhelds and smartphones.
BlackBerry Pearl
On the BlackBerry Pearl, for example, you simply remove the battery door, take out the battery and find a thin metal flap—bigger than the one for the microSD card—that lifts up. Place the SIM inside, close the flap, replace the battery and door and you're phone number now works on the Pearl.
BlackBerry 8800
On the BlackBerry 8800, on the other hand, you again remove the back, exposing the slot for the microSD card and the battery. But after you remove the battery, there's no obvious door or flap to reveal where a SIM goes. Freeiphoner.com (see below for one) has some good illustrations of what you'll be looking at.
If you look carefully to the left of the micro SD slot, you'll see a tiny arrow embossed in the plastic. The SIM slides into the slot indicated by the arrow.
You'll need the metallic side facing down and the slanted corner of the SIM closest to the microSD slot (again, refer to the illustrations). Removing the SIM from this one is tricky as it's so small and fits so snuggly.
Remove or insert the SIM card into holder.
Try unbending a paper clip and gently touching the SIM with the tip of the clip to ease the card out just enough to get your fingers on it.
BlackBerry 8700
Accessing a SIM cared in the BlackBerry 8700 is a little simpler than with the 8800. It is more like with the Pearl.
Here’s what you do:
Remove the door and the battery. Then you'll see the SIM card holder.
Slide the SIM metallic-side down into the notches made for it and ensure it lies flat within the metal guides. Gently press down and tug to get it out. Remember to replace the battery and door.
February 8, 2008
Though it's possible to remove a SIM (subscriber identity module) card and swap it between compatible devices, how you do it varies, even among BlackBerry wireless handhelds and smartphones.
BlackBerry Pearl
On the BlackBerry Pearl, for example, you simply remove the battery door, take out the battery and find a thin metal flap—bigger than the one for the microSD card—that lifts up. Place the SIM inside, close the flap, replace the battery and door and you're phone number now works on the Pearl.
BlackBerry 8800
On the BlackBerry 8800, on the other hand, you again remove the back, exposing the slot for the microSD card and the battery. But after you remove the battery, there's no obvious door or flap to reveal where a SIM goes. Freeiphoner.com (see below for one) has some good illustrations of what you'll be looking at.
If you look carefully to the left of the micro SD slot, you'll see a tiny arrow embossed in the plastic. The SIM slides into the slot indicated by the arrow.
You'll need the metallic side facing down and the slanted corner of the SIM closest to the microSD slot (again, refer to the illustrations). Removing the SIM from this one is tricky as it's so small and fits so snuggly.
Remove or insert the SIM card into holder.
Try unbending a paper clip and gently touching the SIM with the tip of the clip to ease the card out just enough to get your fingers on it.
BlackBerry 8700
Accessing a SIM cared in the BlackBerry 8700 is a little simpler than with the 8800. It is more like with the Pearl.
Here’s what you do:
Remove the door and the battery. Then you'll see the SIM card holder.
Slide the SIM metallic-side down into the notches made for it and ensure it lies flat within the metal guides. Gently press down and tug to get it out. Remember to replace the battery and door.
Subscribe to:
Posts (Atom)