Sunspl

Hello,everyone,i am sun. 天道酬勤,笨鳥先飛.
随笔 - 47, 文章 - 0, 评论 - 24, 引用 - 0
数据加载中……

equals 与 ==

初学 Java 有段时间了,感觉似乎开始入了门,有了点儿感觉
但是发现很多困惑和疑问而且均来自于最基础的知识
折腾了一阵子又查了查书,终于对 String 这个特殊的对象有了点感悟

大家先来看看一段奇怪的程序:
public class TestString {
    public static void main(String[] args) {
        String s1 = "Monday";
        String s2 = "Monday";
    }
}
这个程序真是简单啊!可是有什么问题呢?

1. 来自 String 的忧虑
上面这段程序中,到底有几个对象呢?
可能很多人脱口而出:两个,s1 和 s2
为什么?
String 是 final 类,它的值不可变。
看起来似乎很有道理,那么来检测一下吧,稍微改动一下程序
就可以看到结果了:

public class TestString {
    public static void main(String[] args) {
        String s1 = "Monday";
        String s2 = "Monday";
        if (s1 == s2)
            System.out.println("s1 == s2");
        else
            System.out.println("s1 != s2");
    }
}
呵呵,很多人都会说已经不止两个对象了
编译并运行程序,输出:s1 == s2
啊!
为什么 s1 == s2 ?
== 分明是在说:s1 与 s2 引用同一个 String 对象 -- "Monday"!

2. 千变万化的 String
再稍微改动一下程序,会有更奇怪的发现:
public class TestString {
    public static void main(String[] args) {
        String s1 = "Monday";
        String s2 = new String("Monday");
        if (s1 == s2)
            System.out.println("s1 == s2");
        else
            System.out.println("s1 != s2");
        if (s1.equals(s2))
            System.out.println("s1 equals s2");
        else
            System.out.println("s1 not equals s2");
    }
}
我们将 s2 用 new 操作符创建
程序输出:
s1 != s2
s1 equals s2
嗯,很明显嘛
s1 s2分别引用了两个"Monday"String对象
可是为什么两段程序不一样呢?

3. 在 String 的游泳池中游泳
哈哈,翻了翻书终于找到了答案:
原来,程序在运行的时候会创建一个字符串缓冲池
当使用 s2 = "Monday" 这样的表达是创建字符串的时候,程序首先会
在这个String缓冲池中寻找相同值的对象,在第一个程序中,s1先被
放到了池中,所以在s2被创建的时候,程序找到了具有相同值的 s1
将 s2 引用 s1 所引用的对象"Monday"

第二段程序中,使用了 new 操作符,他明白的告诉程序:
“我要一个新的!不要旧的!”与是一个新的"Monday"Sting对象被创
建在内存中。他们的值相同,但是位置不同,一个在池中游泳
一个在岸边休息。哎呀,真是资源浪费,明明是一样的非要分开做什么呢?

4. 继续潜水
再次更改程序:
public class TestString {
    public static void main(String[] args) {
        String s1 = "Monday";
        String s2 = new String("Monday");
        s2 = s2.intern();
        if (s1 == s2)
            System.out.println("s1 == s2");
        else
            System.out.println("s1 != s2");
        if (s1.equals(s2))
            System.out.println("s1 equals s2");
        else
            System.out.println("s1 not equals s2");
    }
}
这次加入:s2 = s2.intern();
哇!程序输出:
s1 == s2
s1 equals s2
原来,程序新建了 s2 之后,又用intern()把他打翻在了池里
哈哈,这次 s2 和 s1 有引用了同样的对象了
我们成功的减少了内存的占用

5. == 与 equals() 的争斗
String 是个对象,要对比两个不同的String对象的值是否相同
明显的要用到 equals() 这个方法
可是如果程序里面有那么多的String对象,有那么多次的要用到 equals ,
哦,天哪,真慢啊
更好的办法:
把所有的String都intern()到缓冲池去吧
最好在用到new的时候就进行这个操作
String s2 = new String("Monday").intern();
嗯,大家都在水池里泡着了吗?哈哈
现在我可以无所顾忌的用 == 来比较 String 对象的值了
真是爽啊,又快又方便!
关于String :)
String 啊 String ,让我说你什么好呢?
你为我们 Java 程序员带来所有的困扰还不够吗?
看看 String 这一次又怎么闹事儿吧

1. 回顾一下坏脾气的 String 老弟

例程1:
class Str {
    public static void main(String[] args) {
        String s = "Hi!";
        String t = "Hi!";
        if (s == t)
            System.out.println("equals");
        else
            System.out.println("not equals");
    }
}

程序输出什么呢?
如果看客们看过我的《来自 String 的困惑》之一
相信你很快会做出正确的判断:
程序输出:equals

2. 哦,天哪,它又在搅混水了

例程2:
class Str {
    public static void main(String[] args) {
        String s = "HELLO";
        String t = s.toUpperCase();
        if (s == t)
            System.out.println("equals");
        else
            System.out.println("not equals");
    }
}
那么这个程序有输出什么呢?
慎重!再慎重!不要被 String 这个迷乱的家伙所迷惑!
它输出:equals
WHY!!!

把程序简单的更改一下:
class Str2 {
    public static void main(String[] args) {
        String s = "Hello";
        String t = s.toUpperCase();
        if (s == t)
            System.out.println("equals");
        else
            System.out.println("not equals");
    }
}
你可能会说:不是一样吗?
不!千真万确的,不一样!这一次输出:not equals

Oh MyGOD!!!
谁来教训一下这个 String 啊!

3. 你了解你的马吗?
“要驯服脱缰的野马,就要了解它的秉性”牛仔们说道。
你了解 String 吗?

解读 String 的 API ,可以看到:
toUpperCase() 和 toLowerCase() 方法返回一个新的String对象,
它将原字符串表示字符串的大写或小写形势;
但是要注意:如果原字符串本身就是大写形式或小写形式,那么返回原始对象。
这就是为什么第二个程序中 s 和 t 纠缠不清的缘故

对待这个淘气的、屡教不改的 String ,似乎没有更好的办法了
让我们解剖它,看看它到底有什么结构吧:

(1) charAt(int n) 返回字符串内n位置的字符,第一个字符位置为0,
最后一个字符的位置为length()-1,访问错误的位置会扔出一块大砖头:
StringIndexOutOfBoundsException 真够大的

(2) concat(String str) 在原对象之后连接一个 str ,但是返回一个新的 String 对象

(3) EqualsIgnoreCase(String str) 忽略大小写的 equals 方法
这个方法的实质是首先调用静态字符方法toUpperCase() 或者 toLowerCase()
将对比的两个字符转换,然后进行 == 运算

(4) trim() 返回一个新的对象,它将原对象的开头和结尾的空白字符切掉
同样的,如果结果与原对象没有差别,则返回原对象

(5) toString() String 类也有 toString() 方法吗?
真是一个有趣的问题,可是如果没有它,你的 String 对象说不定真的不能用在
System.out.println() 里面啊
小心,它返回对象自己

String 类还有很多其他方法,掌握他们会带来很多方便
也会有很多困惑,所以坚持原则,是最关键的

4. 我想买一匹更好的马
来购买更驯服温和的 String 的小弟 StringBuffer 吧
这时候会有人反对:它很好用,它效率很高,它怎么能够是小弟呢?
很简单,它的交互功能要比 String 少,如果你要编辑字符串
它并不方便,你会对它失望
但这不意味着它不强大
public final class String implements Serializable, Comparable, CharSequence
public final class StringBuffer implements Serializable, CharSequence
很明显的,小弟少了一些东东,不过这不会干扰它的前途

StringBuffer 不是由 String 继承来的
不过要注意兄弟它也是 final 啊,本是同根生

看看他的方法吧,这么多稳定可靠的方法,用起来比顽皮的 String 要有效率的多
?br /> Java 为需要改变的字符串对象提供了独立的 StringBuffer 类
它的实例不可变(final),之所以要把他们分开
是因为,字符串的修改要求系统的开销量增大,
占用更多的空间也更复杂,相信当有10000人挤在一个狭小的游泳池里游泳
而岸边又有10000人等待进入游泳池而焦急上火
又有10000人在旁边看热闹的时候,你这个 String 游泳池的管理员也会焦头烂额

在你无需改变字符串的情况下,简单的 String 类就足够你使唤的了,
而当要频繁的更改字符串的内容的时候,就要借助于宰相肚里能撑船的
StringBuffer 了

5. 宰相肚里能撑船
(1) length() 与 capacity()
String 中的 length() 返回字符串的长度
兄弟 StringBuffer 也是如此,他们都由对象包含的字符长度决定

capacity()呢?
public class TestCapacity {
    public static void main(String[] args){
        StringBuffer buf = new StringBuffer("it was the age of wisdom,");
        System.out.println("buf = " + buf);
        System.out.println("buf.length() = " + buf.length());
        System.out.println("buf.capacity() = " + buf.capacity());
        String str = buf.toString();
        System.out.println("str = " + str);
        System.out.println("str.length() = " + str.length());
        buf.append(" " + str.substring(0,18)).append("foolishness,");
        System.out.println("buf = " + buf);
        System.out.println("buf.length() = " + buf.length());
        System.out.println("buf.capacity() = " + buf.capacity());
        System.out.println("str = " + str);
    }
}
程序输出:
buf = it was the age of wisdom.
buf.length() = 25
buf.capacity() = 41
str = it was the age of wisdom
str.length() = 25
buf = it was the age of wisdom, it was the age of foolishness,
buf.length() = 56
buf.capacity() = 84
str = it was the age of wisdom,

可以看到,在内容更改之后,capacity也随之改变了
长度随着向字符串添加字符而增加
而容量只是在新的长度超过了现在的容量之后才增加
StringBuffer 的容量在操作系统需要的时候是自动改变的
程序员们对capacity所能够做的仅仅是可以在初始化 StringBuffer对象的时候
以上片断引用自http://bbs.blueidea.com/viewthread.php?tid=945875&page=###
解释得比较形象和经典。具体的比较,要亲自动手运行一下程序才行,如下为网上找到的专门研究equals和==的关系的程序,相信可从中体会出他们的深刻不同:
String s1 = null;
String s2 = null;
System.out.println(s1==s2);//true
//System.out.println(s1.equals(s2));//NullPointerException
s1 = s2;
System.out.println(s1==s2);//true
//System.out.println(s1.equals(s2));//NullPointerException
System.out.println("***1***");

s1 = null;
s2 = "";
System.out.println(s1==s2);//false
//System.out.println(s1.equals(s2));//NullPointerException
s1 = s2;
System.out.println(s1==s2);//true
System.out.println(s1.equals(s2));//true
System.out.println("***2***");

s1 = "";
s2 = null;
System.out.println(s1==s2);//false
System.out.println(s1.equals(s2));//false
s1 = s2;
System.out.println(s1==s2);//true
//System.out.println(s1.equals(s2));//NullPointerException
System.out.println("***3***");

s1 = "";
s2 = "";
System.out.println(s1==s2);//true
System.out.println(s1.equals(s2));//true
s1 = s2;
System.out.println(s1==s2);//true
System.out.println(s1.equals(s2));//true
System.out.println("***4***");
s1 = new String("");
s2 = new String("");
System.out.println(s1==s2);//false
System.out.println(s1.equals(s2));//true
s1 = s2;
System.out.println(s1==s2);//true
System.out.println(s1.equals(s2));//true
System.out.println("***5***");

s1 = "null";
s2 = "null";
System.out.println(s1==s2);//ture
System.out.println(s1.equals(s2));//true
s1 = s2;
System.out.println(s1==s2);//true
System.out.println(s1.equals(s2));//true
System.out.println("***6***");
s1 = new String("null");
s2 = new String("null");
System.out.println(s1==s2);//flase
System.out.println(s1.equals(s2));//true
s1 = s2;
System.out.println(s1==s2);//true
System.out.println(s1.equals(s2));//true
System.out.println("***7***");

s1 = "abc";
s2 = "abc";
System.out.println(s1==s2);//ture
System.out.println(s1.equals(s2));//true
s1 = s2;
System.out.println(s1==s2);//true
System.out.println(s1.equals(s2));//true
System.out.println("***8***");
s1 = new String("abc");
s2 = new String("abc");
System.out.println(s1==s2);//false
System.out.println(s1.equals(s2));//true
s1 = s2;
System.out.println(s1==s2);//true
System.out.println(s1.equals(s2));//true
System.out.println("***9***");

总结:   多数情况下这两者的区别就是究竟是对对象的引用进行比较还是对对象的值进行比较(其他特殊情况此处不予考虑)。==操作符是比较的对象的引用而不是对象的值。

但在最初的Object对象中的equals方法与==操作符完成功能是相同的。
源码:
java.lang.Object.equals()方法:
-------------------------------------------------------------
public boolean equalss(Object obj) {
 return (this = = obj);
    }
-------------------------------------------------------------
jdk文档中给出如下解释:
-------------------------------------------------------------
The equalss method implements an equivalence relation:
· It is reflexive: for any reference value x, x.equalss(x) should return true.
· It is symmetric: for any reference values x and y, x.equalss(y) should return true if and only if y.equalss(x) returns true.
· It is transitive: for any reference values x, y, and z, if x.equalss(y) returns true and y.equalss(z) returns true, then x.equalss(z) should return true.
· It is consistent: for any reference values x and y, multiple invocations of x.equalss(y) consistently return true or consistently return false, provided no information used in equalss comparisons on the object is modified.
· For any non-null reference value x, x.equalss(null) should return false.
The equalss method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any reference values x and y, this method returns true if and only if x and y refer to the same object (x==y has the value true).
Note that it is generally necessary to override the hashCode method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equals objects must have equals hash codes.
-------------------------------------------------------------

对于String类的equals方法是对什么内容进行比较的呢?下面我们来看它的代码和注释:
源代码:
-------------------------------------------------------------
public boolean equals(Object anObject) {
 if (this == anObject) {
     return true;
 }
 if (anObject instanceof String) {
     String anotherString = (String)anObject;
     int n = count;
     if (n == anotherString.count) {
  char v1[] = value;
  char v2[] = anotherString.value;
  int i = offset;
  int j = anotherString.offset;
  while (n-- != 0) {
      if (v1[i++] != v2[j++])
   return false;
  }
  return true;
     }
 }
 return false;
    }


-------------------------------------------------------------
此方法的注释为:
-------------------------------------------------------------
Compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.
-------------------------------------------------------------
由上面的代码和注释可以得到String类的equal方法是对对象的值进行比较。
根据以上的讨论可以得出结论:equal方法和==操作符是否存在区别要个别对待,要根据equal的每个实现情况来具体判断。

 

posted @ 2008-06-11 22:36 JavaSuns 阅读(768) | 评论 (0)编辑 收藏

tomcat5.5jdbc 连接池配置(转)

 

tomcat5.5.9 jdbc 连接池配置时常会出现两个错误:

1.***not bound

2.Cannot create JDBC driver of class '' for connect URL 'null'

可以通过以下的方法达到正确的配置:

1.现在%tomcat home%/conf/catalina/localhost 下面添加一段独立的context xml段,命名为jasper.xml,例如

<?xml version="1.0" encoding="UTF-8"?>
<Context path="/jasper" docBase="jasper" debug="1" reloadable="true" crossContext="true">
</Context>

2.通过admin的界面(或手动在server.xml界面里进行配置)数据源,以sql2k为例,配置后的server.xml应该为

<?xml version="1.0" encoding="UTF-8"?>
<Server>
  <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener"/>
  <Listener className="org.apache.catalina.storeconfig.StoreConfigLifecycleListener"/>
  <Listener className="org.apache.catalina.mbeans.ServerLifecycleListener"/>
  <GlobalNamingResources>
    <Environment
      name="simpleValue"
      type="java.lang.Integer"
      value="30"/>
    <Resource
      auth="Container"
      description="User database that can be updated and saved"
      name="UserDatabase"
      type="org.apache.catalina.UserDatabase"
      pathname="conf/tomcat-users.xml"
      factory="org.apache.catalina.users.MemoryUserDatabaseFactory"/>
    <Resource
      name="jdbc/Northwind"
      type="javax.sql.DataSource"
      password="*****"
      driverClassName="com.microsoft.jdbc.sqlserver.SQLServerDriver"
      maxIdle="2"
      maxWait="5000"
      username="sa"
      url="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=Northwind"
      maxActive="20"/>
  </GlobalNamingResources>
  <Service
      name="Catalina">
    <Connector
        port="80"
        redirectPort="8443"
        minSpareThreads="25"
        connectionTimeout="20000"
        maxSpareThreads="75"
        maxThreads="150"
        maxHttpHeaderSize="8192">
    </Connector>
    <Connector
        port="8009"
        redirectPort="8443"
        protocol="AJP/1.3">
    </Connector>
    <Engine
        defaultHost="localhost"
        name="Catalina">
      <Realm className="org.apache.catalina.realm.UserDatabaseRealm"/>
      <Host
          appBase="webapps"
          name="localhost">
      </Host>
    </Engine>
  </Service>
</Server>

3.在conf下面的context.xml文件中,</Context>之前加入

 <ResourceLink name="jdbc/Northwind" global="jdbc/Northwind" type="javax.sql.DataSourcer"/>

4.在你的web文件夹下面的WEB-INF中找到web.xml,在最后</web-app>之前加入

<resource-ref>
      <description>Northwind Connection</description>
      <res-ref-name>jdbc/Northwind</res-ref-name>
      <res-type>javax.sql.DataSource</res-type>
      <res-auth>Container</res-auth>
    </resource-ref>

5.保存,重启tomcat,这样,通过测试页面,就可以发现已经可以通过数据库连接池连上sql2k

test1.jsp

<%@ page contentType="text/html; charset=gb2312" language="java" import="java.sql.*" errorPage="" %>
<%@page import="javax.naming.*"%>
<%@page import="javax.sql.*"%>
<%
Context initContext = new InitialContext();
Context envContext  = (Context)initContext.lookup("java:/comp/env");
DataSource ds = (DataSource)envContext.lookup("jdbc/Northwind");
Connection conn = ds.getConnection();
int counts=0;
String sql="select count(*) from orders";
PreparedStatement pst=conn.prepareStatement(sql);
ResultSet rst=pst.executeQuery();
while(rst.next()){
 counts=rst.getInt(1);
}
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>JNDI 测试</title>
</head>

<body>
<%=sql%><br>
pnrreg talbe's count is:<%=counts%>
</body>
</html>

posted @ 2008-06-06 12:04 JavaSuns 阅读(338) | 评论 (0)编辑 收藏

(轉)JS的正则表达式

     摘要: JS的正则表达式 //校验是否全由数字组成 function isDigit(s) { var patrn=/^[0-9]{1,20}$/; if (!patrn.exec(s)) return false return true } //校验登录名:只能输入5-20个以字母开头、可带数字、“_”...  阅读全文

posted @ 2008-04-25 12:44 JavaSuns 阅读(440) | 评论 (0)编辑 收藏

(轉)正则表达式之道

原著:Steve Mansour
sman@scruznet.com
Revised: June 5, 1999
(copied by jm /at/ jmason.org from http://www.scruz.net/%7esman/regexp.htm, after the original disappeared! )

翻译:Neo Lee
neo.lee@gmail.com
2004年10月16日

英文版原文

译者按:原文因为年代久远,文中很多链接早已过期(主要是关于vi、sed等工具的介绍和手册),本译文中已将此类链接删除,如需检查这些链接可以查看上面链接的原文。除此之外基本照原文直译,括号中有“译者按”的部分是译者补充的说明。如有内容方面的问题请直接和Steve Mansor联系,当然,如果你只写中文,也可以和我联系。

目 录

什么是正则表达式
范例
   简单
   中级(神奇的咒语)
   困难(不可思议的象形文字)
不同工具中的正则表达式

什么是正则表达式

一个正则表达式,就是用某种模式去匹配一类字符串的一个公式。很多人因为它们看上去比较古怪而且复杂所以不敢去使用——很不幸,这篇文章也不能够改变这一点,不过,经过一点点练习之后我就开始觉得这些复杂的表达式其实写起来还是相当简单的,而且,一旦你弄懂它们,你就能把数小时辛苦而且易错的文本处理工作压缩在几分钟(甚至几秒钟)内完成。正则表达式被各种文本编辑软件、类库(例如Rogue Wave的tools.h++)、脚本工具(像awk/grep/sed)广泛的支持,而且像Microsoft的Visual C++这种交互式IDE也开始支持它了。

我们将在如下的章节中利用一些例子来解释正则表达式的用法,绝大部分的例子是基于vi中的文本替换命令和grep文件搜索命令来书写的,不过它们都是比较典型的例子,其中的概念可以在sed、awk、perl和其他支持正则表达式的编程语言中使用。你可以看看不同工具中的正则表达式这一节,其中有一些在别的工具中使用正则表达式的例子。还有一个关于vi中文本替换命令(s)的简单说明附在文后供参考。

正则表达式基础

正则表达式由一些普通字符和一些元字符(metacharacters)组成。普通字符包括大小写的字母和数字,而元字符则具有特殊的含义,我们下面会给予解释。

在最简单的情况下,一个正则表达式看上去就是一个普通的查找串。例如,正则表达式"testing"中没有包含任何元字符,,它可以匹配"testing"和"123testing"等字符串,但是不能匹配"Testing"。

要想真正的用好正则表达式,正确的理解元字符是最重要的事情。下表列出了所有的元字符和对它们的一个简短的描述。

元字符   描述


.
匹配任何单个字符。例如正则表达式r.t匹配这些字符串:ratrutr t,但是不匹配root。 
$
匹配行结束符。例如正则表达式weasel$ 能够匹配字符串"He's a weasel"的末尾,但是不能匹配字符串"They are a bunch of weasels."。 
^
匹配一行的开始。例如正则表达式^When in能够匹配字符串"When in the course of human events"的开始,但是不能匹配"What and When in the"。
*
匹配0或多个正好在它之前的那个字符。例如正则表达式.*意味着能够匹配任意数量的任何字符。
\
这是引用府,用来将这里列出的这些元字符当作普通的字符来进行匹配。例如正则表达式\$被用来匹配美元符号,而不是行尾,类似的,正则表达式\.用来匹配点字符,而不是任何字符的通配符。
[ ] 
[c1-c2]
[^c1-c2]
匹配括号中的任何一个字符。例如正则表达式r[aou]t匹配ratrotrut,但是不匹配ret。可以在括号中使用连字符-来指定字符的区间,例如正则表达式[0-9]可以匹配任何数字字符;还可以制定多个区间,例如正则表达式[A-Za-z]可以匹配任何大小写字母。另一个重要的用法是“排除”,要想匹配除了指定区间之外的字符——也就是所谓的补集——在左边的括号和第一个字符之间使用^字符,例如正则表达式[^269A-Z] 将匹配除了2、6、9和所有大写字母之外的任何字符。
\< \>
匹配词(word)的开始(\<)和结束(\>)。例如正则表达式\<the能够匹配字符串"for the wise"中的"the",但是不能匹配字符串"otherwise"中的"the"。注意:这个元字符不是所有的软件都支持的。
\( \)
将 \( 和 \) 之间的表达式定义为“组”(group),并且将匹配这个表达式的字符保存到一个临时区域(一个正则表达式中最多可以保存9个),它们可以用 \1\9 的符号来引用。
|
将两个匹配条件进行逻辑“或”(Or)运算。例如正则表达式(him|her) 匹配"it belongs to him"和"it belongs to her",但是不能匹配"it belongs to them."。注意:这个元字符不是所有的软件都支持的。
+
匹配1或多个正好在它之前的那个字符。例如正则表达式9+匹配9、99、999等。注意:这个元字符不是所有的软件都支持的。
?
匹配0或1个正好在它之前的那个字符。注意:这个元字符不是所有的软件都支持的。
\{i\}