Tuesday, October 18, 2011

Generic

Generic can be placed in class/interface declaration, variable declaration, method parameter or method return value.

In method return value :
public static <B> List<B> aMethod() {...} // any reference can replace B.

In method parameter :
public static <B> List<B> aMethod(B b) {...} // any reference can replace B.
public <B> void aMethod(B b) {...} // any reference can replace B
public <B extends Number> void aMethod(B b) {...} // B must be subclass of Number

In variable declaration :
List<String> list = new ArrayList<String>(); // list of String, no other type

In interface or class declaration :
interface IDao <X extends IEntity> {...} // X must be subclass of IEntity
interface IBidDao extends IDao<Bid> // Bid replaces X and Bid is subclass of IEntity
class BaseDao<X extends IEntity> implements IDao<X> // BaseDao takes X which is then substitutes X in IDao

We can put ? to replace B or X above, which also means any but with restrictions:

List<?> list = new ArrayList<Integer>(); means any class can fit in, and as for List, we can't add object to the list. In general, all of the methods in List that take the generic object as parameter are not applicable (compile error as in add, addAll, etc).

List<? extends Number> list = new ArrayList<Integer>(); means any class that extends Number can fit in, and as for List, we can't add object to the list. In general, all of the methods in List that take the generic object as parameter are not applicable (compile error as in add, addAll, etc).

List<? super Number> list = new ArrayList<Object>(); means any class on top of Number inheritance hierarchy can fit in, and as for List, we can add object to the list as opposed to <?> or <? extends Number>.

The ? and super keyword in generic only apply to variable declaration or method parameter not to class declaration:
List<? extends Number> list = new ArrayList<Integer>();
public void aMethod(List<? extends Number> list) {...}

Monday, October 10, 2011

Java Collection



List
- List of things.
1. ArrayList -> Growable array. Good for fast iteration but not for a lot of insertion and deletion.
2. Vector -> Same as ArrayList but its methods are synchronized for thread safety.
3. LinkedList -> Same as ArrayList. Good for fast insertion and deletion but not for iteration.

Set - Unique things
1. HashSet -> Collection with no duplicate objects and unpredictable iteration order.
2. LinkedHashSet -> Ordered version of HashSet, ordered in which they are inserted.
3. TreeSet -> Sorted Set by natural order using Red-Black tree structure.

Map - Things with unique ID
1. HashMap -> The simplest map class.
2. Hashtable -> Same as HashMap but its methods are synchronized for thread safety.
3. LinkedHashMap -> Ordered version of HashMap, ordered in which they are inserted.
4. TreeMap -> Sorted Map by natural order.

Queue - Things arranged by the order in which they are to be processed
1. PriorityQueue

Comparable & Comparator

When we add two objects in a collection that doesn't allow duplication as in Set, we have to override the Objet.equals() method as well as Object.hashCode() method. But now we want to make all objects in a List or array sortable, that's why we have to deal with two interfaces: Comparable and Comparator.

Comparable

Implements Comparable interface in the bean class to make the bean comparable:

public class SerializableBean implements Comparable {

private String name;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

@Override
public int compareTo(SerializableBean o) {
return name.compareTo(o.name);
}
}

Now we can sort the list or array containing the beans using:

Collections.sort(list);
Arrays.sort(arr);

We can also find an index of an object inside the collection using binary search tree after sorting it:

Collections.binarySearch(list, key);
Arrays.binarySearch(arr, key);

Comparator

Create a new class that implements Comparator interface:

public class CompareByName implements Comparator {

@Override
public int compare(SerializableBean bean1, SerializableBean bean2) {
return bean1.getName().compareTo(bean2.getName());
}

}

Now we can use it to sort a list or array:

Collections.sort(list, new CompareByName());
Arrays.sort(arr, new CompareByName());

We can also find an index of an object inside the collection using binary search tree after sorting it:

Collections.binarySearch(list, key, new CompareByName());
Arrays.binarySearch(arr, key, new CompareByName());

Thursday, October 6, 2011

SCJP 6 Part IX - Formatting String with Formatter

Here is the format
%[arg_index$][flags][width][.precision]conversion_char

arg_index
An integer followed directly by a $, this indicates which argument should be printed in this position.

flags
"-" Left justify this argument
"+" Include a sign (+ or -) with this argument
"0" Pad this argument with zeroes
"," Use locale-specific grouping separators
"(" Enclose negative numbers in parentheses

width
This value indicates the minimum number of characters to print.

precision
When formatting a floating-point number, precision indicates the number of digits to print after the decimal point.

conversion_char
The type of argument we'll be formatting.
b boolean
c char
d integer
f floating point
s string

Formatter formatter = new Formatter(System.out);

// format int and use italian switzerland separator
formatter.format(new Locale("it", "ch"), "%,d", 1000000); // 1'000'000

// format int, use italian switzerland separator, and give parentheses for negative int
formatter.format(new Locale("it", "ch"), "%(,d", -1000000); // (1'000'000)

// format int, use italian switzerland separator, and put a sign on it
formatter.format(new Locale("it", "ch"), "%,+d", 1000000); // +1'000'000

SCJP 6 Part VIII - Regex With Scanner

// split string by a dot
Scanner scanner = new Scanner("my.name.is.budi");
scanner.useDelimiter("\\.");
while (scanner.hasNext()) {
System.out.println(scanner.next());
}

result:

my
name
is
budi

// split string by regex (zero or one comma) and a space
Scanner scanner1 = new Scanner("1 isn't true, 0 isn't false, 2.0 is double");
scanner1.useDelimiter("[,]? ");
while (scanner1.hasNext()) {
// is the next token can be converted to int
if (scanner1.hasNextInt()) {
System.out.println("Found int : " + scanner1.nextInt());
// is the next token can be converted to boolean
} else if (scanner1.hasNextBoolean()) {
System.out.println("Found boolean : " + scanner1.nextBoolean());
// is the next token can be converted to double
} else if (scanner1.hasNextDouble()) {
System.out.println("Found double : " + scanner1.nextDouble());
} else {
System.out.println(scanner1.next());
}
}

result:

Found int : 1
isn't
Found boolean : true
Found int : 0
isn't
Found boolean : false
Found double : 2.0
is
double

SCJP 6 Part VII - Regex

Pattern pattern = Pattern.compile("aba");
Matcher matcher = pattern.matcher("abababababababa");
while (matcher.find()) {
System.out.println("aba has been found at index : " + matcher.start() + " " + matcher.group());
}

result:

aba has been found at index : 0 aba
aba has been found at index : 4 aba
aba has been found at index : 8 aba
aba has been found at index : 12 aba

Pattern pattern1 = Pattern.compile("\\d");
Matcher matcher1 = pattern1.matcher("jatim1");
while (matcher1.find()) {
System.out.println("a digit has been found at index : " + matcher1.start() + " " + matcher1.group());
}

result:

a digit has been found at index : 5 1

Pattern pattern2 = Pattern.compile("\\s");
Matcher matcher2 = pattern2.matcher("my name is ...");
while (matcher2.find()) {
System.out.println("a space has been found at index : " + matcher2.start());
}

result:

a space has been found at index : 2
a space has been found at index : 7
a space has been found at index : 10

Pattern pattern3 = Pattern.compile("\\w");
Matcher matcher3 = pattern3.matcher("123 -> lets go");
while (matcher3.find()) {
System.out.println("a letter or a digit or an underscore has been found at index : " + matcher3.start() + " " + matcher3.group());
}

result:

a letter or a digit or an underscore has been found at index : 0 1
a letter or a digit or an underscore has been found at index : 1 2
a letter or a digit or an underscore has been found at index : 2 3
a letter or a digit or an underscore has been found at index : 7 l
a letter or a digit or an underscore has been found at index : 8 e
a letter or a digit or an underscore has been found at index : 9 t
a letter or a digit or an underscore has been found at index : 10 s
a letter or a digit or an underscore has been found at index : 12 g
a letter or a digit or an underscore has been found at index : 13 o

Pattern pattern4 = Pattern.compile("[ap]");
Matcher matcher4 = pattern4.matcher("al pacino");
while (matcher4.find()) {
System.out.println("character 'a' or 'p' has been found at index : " + matcher4.start() + " " + matcher4.group());
}


result:

character 'a' or 'p' has been found at index : 0 a
character 'a' or 'p' has been found at index : 3 p
character 'a' or 'p' has been found at index : 4 a

Pattern pattern5 = Pattern.compile("[a-l]");
Matcher matcher5 = pattern5.matcher("al pacino");
while (matcher5.find()) {
System.out.println("character 'a' until 'l' has been found at index : " + matcher5.start() + " " + matcher5.group());
}


result:

character 'a' until 'l' has been found at index : 0 a
character 'a' until 'l' has been found at index : 1 l
character 'a' until 'l' has been found at index : 4 a
character 'a' until 'l' has been found at index : 5 c
character 'a' until 'l' has been found at index : 6 i

Pattern pattern6 = Pattern.compile("[a-lA-L]");
Matcher matcher6 = pattern6.matcher("aL PaCiNo");

while (matcher6.find()) {
System.out.println("character 'a' until 'l' OR 'A' until 'L' has been found at index : " + matcher6.start() + " " + matcher6.group());
}


return:

character 'a' until 'l' OR 'A' until 'L' has been found at index : 0 a
character 'a' until 'l' OR 'A' until 'L' has been found at index : 1 L
character 'a' until 'l' OR 'A' until 'L' has been found at index : 4 a
character 'a' until 'l' OR 'A' until 'L' has been found at index : 5 C
character 'a' until 'l' OR 'A' until 'L' has been found at index : 6 i

Pattern pattern7 = Pattern.compile("\\d+");
Matcher matcher7 = pattern7.matcher("(031) 531 4249");
while (matcher7.find()) {
System.out.println("a group of digit has been found at index : " + matcher7.start() + " " + matcher7.group());
}

result (+ means one or more, \\d+ means one or more digit):

a group of digit has been found at index : 1 031
a group of digit has been found at index : 6 531
a group of digit has been found at index : 10 4249

Pattern pattern8 = Pattern.compile("0[xX]([0-9a-fA-F])+");
Matcher matcher8 = pattern8.matcher("0xffffff 0X778899 0X1 0XXX");
while (matcher8.find()) {
System.out.println("a hexadecimal has been found at index : " + matcher8.start() + " " + matcher8.group());
}

result:

a hexadecimal has been found at index : 0 0xffffff
a hexadecimal has been found at index : 9 0X778899
a hexadecimal has been found at index : 18 0X1

Pattern pattern9 = Pattern.compile("\\(\\d\\d\\d\\)([-\\s])?\\d\\d\\d([-\\s]?)\\d\\d\\d\\d");
Matcher matcher9 = pattern9.matcher("(031)-5314249, (031) 5314249, (031)5314249, (031)-531-4249, (031)-531 4249, (031) 531-42490000");
while (matcher9.find()) {
System.out.println("a valid phone number has been found at index : " + matcher9.start() + " " + matcher9.group());
}

result (? means zero or one,
([-\\s])? means zero or one either - or space):

a valid phone number has been found at index : 0 (031)-5314249
a valid phone number has been found at index : 15 (031) 5314249
a valid phone number has been found at index : 30 (031)5314249
a valid phone number has been found at index : 44 (031)-531-4249
a valid phone number has been found at index : 60 (031)-531 4249
a valid phone number has been found at index : 76 (031) 531-4249

Pattern pattern10 = Pattern.compile("[iI][nN][dD][oO]([a-zA-Z])*");
Matcher matcher10 = pattern10.matcher("Indonesia India indo123 indochina indo");
while (matcher10.find()) {
System.out.println("a string start with indo has been found at index : " + matcher10.start() + " " + matcher10.group());
}

result (* means zero or more):

a string start with indo has been found at index : 0 Indonesia
a string start with indo has been found at index : 16 indo
a string start with indo has been found at index : 24 indochina
a string start with indo has been found at index : 34 indo

Pattern pattern11 = Pattern.compile("f...");
Matcher matcher11 = pattern11.matcher("fool feel fast fame fee flash");
while (matcher11.find()) {
System.out.println(". is used to find any single char : " + matcher11.start() + " " + matcher11.group());
}

result:

. is used to find any single char : 0 fool
. is used to find any single char : 5 feel
. is used to find any single char : 10 fast
. is used to find any single char : 15 fame
. is used to find any single char : 20 fee
. is used to find any single char : 24 flas

Wednesday, October 5, 2011

SCJP 6 Part VI - Locale - NumberFormat - DateFormat

// locale italy language in country switzerland
Locale localeItalyInSwitzerland = new Locale("it", "ch");

// default DateFormat using SHORT format
DateFormat format = DateFormat.getInstance();
System.out.println("Default format : " + format.format(new Date()));

// format using date and time format.
DateFormat dateTimeFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.MEDIUM, localeItalyInSwitzerland);
System.out.println("Date & time format : " + dateTimeFormat.format(new Date()));

// format date only
DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.LONG, localeItalyInSwitzerland);
System.out.println("Date format : " + dateFormat.format(new Date()));

// format time only
DateFormat timeFormat = DateFormat.getTimeInstance(DateFormat.MEDIUM, localeItalyInSwitzerland);
System.out.println("Time format : " + timeFormat.format(new Date()));

// general-purpose number format
NumberFormat format1 = NumberFormat.getInstance(localeItalyInSwitzerland);
System.out.println("General purpose format : " + format1.format(1000000));

// general-purpose number format
NumberFormat format2 = NumberFormat.getNumberInstance(localeItalyInSwitzerland);
System.out.println("General purpose format : " + format2.format(1000000));

// currency format
NumberFormat currencyFormat = NumberFormat.getCurrencyInstance(localeItalyInSwitzerland);
System.out.println("Currency format : " + currencyFormat.format(1000000));

// integer format
NumberFormat integerFormat = NumberFormat.getIntegerInstance(localeItalyInSwitzerland);
System.out.println("Integer format : " + integerFormat.format(1000000));

// percent format
NumberFormat percentFormat = NumberFormat.getPercentInstance(localeItalyInSwitzerland);
System.out.println("Percent format : " + percentFormat.format(1000000));

Tuesday, October 4, 2011

SCJP 6 Part V - Serialization

public class SerializableBean implements Serializable {

private String name;
private Date birthDate;
private Double money;

public void setName(String name) {
this.name = name;
}

public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}

public void setMoney(Double money) {
this.money = money;
}

public String toString() {
SimpleDateFormat format = new SimpleDateFormat("dd/MMMM/yyyy");
return name + " " + format.format(birthDate) + " " + money;
}

}

// data to be serialized
SerializableBean bean = new SerializableBean();
bean.setBirthDate(new Date());
bean.setMoney(10000000d);
bean.setName("Rochmat Santoso");

// create new file if one doesn't exist
File file = new File("myTextFile.txt");

// serialize data
FileOutputStream fileOutputStream = new FileOutputStream(file);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);

objectOutputStream.writeObject(bean);
objectOutputStream.flush();
objectOutputStream.close();

fileOutputStream.flush();
fileOutputStream.close();

// deserialize data
FileInputStream fileInputStream = new FileInputStream(file);
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);

SerializableBean bean1 = (SerializableBean) objectInputStream.readObject();
System.out.println(bean1);
objectInputStream.close();

fileInputStream.close();

SCJP 6 Part IV - File IO

// create new file if one doesn't exist
File file = new File("myTextFile.txt");
boolean isSuccessfullyCreated = file.createNewFile();
if (isSuccessfullyCreated) {
System.out.println("File has been created successfully!");
} else {
System.out.println("Failed creating file!");
}

// create an object to write to the file, remove the old content
FileWriter fileWriter = new FileWriter(file);
fileWriter.write("New Content");
fileWriter.write("\n");
fileWriter.write("Added String");
fileWriter.flush();
fileWriter.close();

// another way to write to the file, remove the old content
PrintWriter printWriter = new PrintWriter(file);
printWriter.println("Another content");
printWriter.println("Another added content");
printWriter.flush();
printWriter.close();

// advanced way to write to the file, remove the old content
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file));
bufferedWriter.write("The new content");
bufferedWriter.newLine();
bufferedWriter.write("The added content");
bufferedWriter.flush();
bufferedWriter.close();

// create an object to read from the file
FileReader fileReader = new FileReader(file);
StringBuilder sb = new StringBuilder();
while (true) {
int content = fileReader.read();

if (content == -1) {
System.out.println("The content is : " + sb);
break;
} else {
sb.append((char) content);
}
}
fileReader.close();

// advanced way to read from the file
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
StringBuilder sb1 = new StringBuilder();
while (true) {
String content = bufferedReader.readLine();

if (content == null) {
System.out.println("The content is : " + sb1);
break;
} else {
sb1.append(content);
sb1.append("\n");
}
}
bufferedReader.close();

// console
Console console = System.console();

System.out.print("Type something : ");
String typed = console.readLine();
System.out.println("You typed : " + typed);

System.out.print("Type your secret : ");
String secret = String.valueOf(console.readPassword());
System.out.println("Your secret was : " + secret);
 

©2009 Stay the Same | by TNB