Tuesday, 25 March 2008

SCJP Exam for J2SE 5 Book by Paul Sanghera

First i would like to congratulate Paul Sanghera for writing SCJP Exam for J2SE 5 book.I and my wife Sneha completed yesterday one time revision of this book and we are planning to write exam sometime later.

However we found 2 minor problems.

Problem 1:

In the "Memorize" section of Chapter 10 "Collections And Generics" one point states that

--> If you want to use the objects of your class as keys in a map, you must override the equals(…) method of the Object class.

However,i think we need to override hashCode() method also inorder to get accurate results.

For Example:


package certification;

import java.util.HashMap;
import java.util.Map;

public class MapDemo {

public static void main(String[] args) {
Map<SomeClassMap,SomeClassMap> map=new HashMap<SomeClassMap,SomeClassMap>();

SomeClassMap classMap1=new SomeClassMap();
classMap1.setStr("Demo");
SomeClassMap classMap2=new SomeClassMap();
classMap2.setStr("Demo");

map.put(classMap1,classMap2);
map.put(classMap2,classMap2);

System.out.println(map.size());
}
}

class SomeClassMap {
private String str;

public String getStr() {
return str;
}

public void setStr(String str) {
this.str = str;
}

public int hashCode() {
return str.hashCode();
}

public boolean equals(Object obj) {
System.out.println("entered");
if(this==obj) {
return true;
}
SomeClassMap someClass=(SomeClassMap)obj;

if(someClass.getStr().equals(this.getStr()))
return true;
else
return false;
}



Problem 2:

In chapter 9 regular expressions we found the available email validator may not validate in all situations.

For example when we run EmailValidator program and provide input as "prashantjvrsrediffmail.com" it is considering as valid case???

Just for reference i am pasting the code of the program.


package certification;
import java.util.regex.*;
public class EmailValidator {
public static void main(String[] args) {
String email="";
email = "prashantjvrsrediffmail.com";


//Look for for email addresses starting with
//invalid symbols: dots or @ signs.
Pattern p = Pattern.compile("^\\.+|^\\@+");
Matcher m = p.matcher(email);
if (m.find()) {
System.err.println("Invalid email address: starts with a dot or an @ sign.");
System.exit(0);
}
//Look for email addresses that start with
//www.
p = Pattern.compile("^www\\.");
m = p.matcher(email);
if (m.find()) {
System.out.println("Invalid email address: starts with www.");
System.exit(0);
}
p = Pattern.compile("[^A-Za-z0-9\\@\\.\\_]");
m = p.matcher(email);

if(m.find()) {
System.out.println("Invalid email address: contains invalid characters");

} else{

System.out.println(email + " is a valid email address.");
}



}
}


Hope you enjoy reading this book soon!!!!!!

No comments: