j2ee技术
package demo.xml;
//作者 sunchengjun
//时间 2006年11日5日
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class DOMParsePage {
public DOMParsePage() {
DocumentBuilderFactory domfac=DocumentBuilderFactory.newInstance();
try {
DocumentBuilder dombuilder=domfac.newDocumentBuilder();
InputStream is=new FileInputStream("C:/123.xml");
Document doc=dombuilder.parse(is);
Element root=doc.getDocumentElement();
NodeList books=root.getChildNodes();
if(books!=null){
for(int i=0;i<books.getLength();i++){
Node book=books.item(i);
for(Node node=book.getFirstChild();node!=null;node=node.getNextSibling())
{
if(node.getNodeType()==Node.ELEMENT_NODE){
if(node.getNodeName().equals("title")){
String bookname=node.getFirstChild().getNodeValue();
System.out.println(bookname);
}
if(node.getNodeName().equals("author")){
String author1=node.getFirstChild().getNodeValue();
System.out.println(author1);
}
if(node.getNodeName().equals("description")){
String addtime=node.getFirstChild().getNodeValue();
System.out.println(addtime);
}
if(node.getNodeName().equals("pubDate")){
String price=node.getFirstChild().getNodeValue();
System.out.println(price);
}
}
}
}
}
}
catch (ParserConfigurationException e) {
e.printStackTrace();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (SAXException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new DOMParsePage();
}
}
Jason
2006-11-05 19:53:01
阅读:1167
评论:1
引用:0
/*
*java中对日期的加减操作
*gc.add(1,-1)表示年份减一.
*gc.add(2,-1)表示月份减一.
*gc.add(3.-1)表示周减一.
*gc.add(5,-1)表示天减一.
*以此类推应该可以精确的毫秒吧.没有再试.大家可以试试.
*GregorianCalendar类的add(int field,int amount)方法表示年月日加减.
*field参数表示年,月.日等.
*amount参数表示要加减的数量.
*
* UseDate.java 测试如下:
*/
package temp.util;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.text.SimpleDateFormat;
public class UseDate {
Date d=new Date();
GregorianCalendar gc =new GregorianCalendar();
SimpleDateFormat sf =new SimpleDateFormat("yyyy-MM-dd");
public String getYears()
{
gc.setTime(d);
gc.add(1,+1);
gc.set(gc.get(Calendar.YEAR),gc.get(Calendar.MONTH),gc.get(Calendar.DATE));
return sf.format(gc.getTime());
}
public String getHalfYear()
{
gc.setTime(d);
gc.add(2,+6);
gc.set(gc.get(Calendar.YEAR),gc.get(Calendar.MONTH),gc.get(Calendar.DATE));
return sf.format(gc.getTime());
}
public String getQuarters()
{
gc.setTime(d);
gc.add(2,+3);
gc.set(gc.get(Calendar.YEAR),gc.get(Calendar.MONTH),gc.get(Calendar.DATE));
return sf.format(gc.getTime());
}
public String getLocalDate()
{
return sf.format(d);
}
public static void main(String[] args)
{
UseDate ud= new UseDate();
System.out.println(ud.getLocalDate());
System.out.println(ud.getYears());
System.out.println(ud.getHalfYear());
System.out.println(ud.getQuarters());
}
}
Jason
2006-03-09 15:37:13
阅读:4965
评论:1
引用:0
先前写静态的方法就是将模板也就是源码放在fw.write("")里面,然后写成文件的,后来我觉得不同的jsp页面这样做起来比较麻烦.
后来,我在网上找到一种方法,将其方法修改后写成文件,原来是如此的方便.
<%@ page contentType="text/html;charset=gb2312"%>
<%@ page import="java.io.*,java.sql.Date,java.util.*,java.text.*"%>
<%
String sCurrentLine;
String sTotalString;
sCurrentLine="";
sTotalString="";
java.io.InputStream l_urlStream;
java.net.URL l_url = new java.net.URL("http://www.mv163.com.cn/indexs.jsp");
java.net.HttpURLConnection l_connection = (java.net.HttpURLConnection) l_url.openConnection();
l_connection.connect();
l_urlStream = l_connection.getInputStream();
java.io.BufferedReader l_reader = new java.io.BufferedReader(new java.io.InputStreamReader(l_urlStream));
while ((sCurrentLine = l_reader.readLine()) != null)
{
sTotalString+=sCurrentLine;
}
//out.println(sTotalString);
String path=request.getRealPath("123");
FileWriter fw=new FileWriter(path + "\\index.html");
fw.write(sTotalString);
fw.close();
out.println("<script language=\"JavaScript\" type=\"text/javascript\">alert(\"生成成功,点击返回!\");window.location.href=\"javascript:history.go(-1)\"</script>");
%>
后来,我在网上找到一种方法,将其方法修改后写成文件,原来是如此的方便.
<%@ page contentType="text/html;charset=gb2312"%>
<%@ page import="java.io.*,java.sql.Date,java.util.*,java.text.*"%>
<%
String sCurrentLine;
String sTotalString;
sCurrentLine="";
sTotalString="";
java.io.InputStream l_urlStream;
java.net.URL l_url = new java.net.URL("http://www.mv163.com.cn/indexs.jsp");
java.net.HttpURLConnection l_connection = (java.net.HttpURLConnection) l_url.openConnection();
l_connection.connect();
l_urlStream = l_connection.getInputStream();
java.io.BufferedReader l_reader = new java.io.BufferedReader(new java.io.InputStreamReader(l_urlStream));
while ((sCurrentLine = l_reader.readLine()) != null)
{
sTotalString+=sCurrentLine;
}
//out.println(sTotalString);
String path=request.getRealPath("123");
FileWriter fw=new FileWriter(path + "\\index.html");
fw.write(sTotalString);
fw.close();
out.println("<script language=\"JavaScript\" type=\"text/javascript\">alert(\"生成成功,点击返回!\");window.location.href=\"javascript:history.go(-1)\"</script>");
%>
Jason
2005-09-18 09:37:37
阅读:3549
评论:0
引用:0
在数据库操作中,一项事务是指由一条或多条对数据库更新的sql语句所组成的一个不可分割的工作单元。只有当事务中的所有操作都正常完成了,整个事务才能被提交到数据库,如果有一项操作没有完成,就必须撤消整个事务。
例如在银行的转帐事务中,假定张三从自己的帐号上把1000元转到李四的帐号上,相关的sql语句如下:
update account set monery=monery-1000 where name=’zhangsan’
update account set monery=monery+1000 where name=’lisi’
这个两条语句必须作为一个完成的事务来处理。只有当两条都成功执行了,才能提交这个事务。如果有一句失败,整个事务必须撤消。
在connection类中提供了3个控制事务的方法:
(1) setAutoCommit(Boolean autoCommit):设置是否自动提交事务;
(2) commit();提交事务;
(3) rollback();撤消事务;
在jdbc api中,默认的情况为自动提交事务,也就是说,每一条对数据库的更新的sql语句代表一项事务,操作成功后,系统自动调用commit()来提交,否则将调用rollback()来撤消事务。
在jdbc api中,可以通过调用setAutoCommit(false) 来禁止自动提交事务。然后就可以把多条更新数据库的sql语句做为一个事务,在所有操作完成之后,调用commit()来进行整体提交。倘若其中一项sql操作失败,就不会执行commit()方法,而是产生相应的sqlexception,此时就可以捕获异常代码块中调用rollback()方法撤消事务。
例如在银行的转帐事务中,假定张三从自己的帐号上把1000元转到李四的帐号上,相关的sql语句如下:
update account set monery=monery-1000 where name=’zhangsan’
update account set monery=monery+1000 where name=’lisi’
这个两条语句必须作为一个完成的事务来处理。只有当两条都成功执行了,才能提交这个事务。如果有一句失败,整个事务必须撤消。
在connection类中提供了3个控制事务的方法:
(1) setAutoCommit(Boolean autoCommit):设置是否自动提交事务;
(2) commit();提交事务;
(3) rollback();撤消事务;
在jdbc api中,默认的情况为自动提交事务,也就是说,每一条对数据库的更新的sql语句代表一项事务,操作成功后,系统自动调用commit()来提交,否则将调用rollback()来撤消事务。
在jdbc api中,可以通过调用setAutoCommit(false) 来禁止自动提交事务。然后就可以把多条更新数据库的sql语句做为一个事务,在所有操作完成之后,调用commit()来进行整体提交。倘若其中一项sql操作失败,就不会执行commit()方法,而是产生相应的sqlexception,此时就可以捕获异常代码块中调用rollback()方法撤消事务。
Jason
2005-07-31 17:35:17
阅读:2311
评论:0
引用:0
最近研了一下java的事务处理,原来是这么一回事,如果对数据库进行多次操作,每一次的执行或步骤都是一个事务.如果数据库操作在某一步没有执行或出现异常而导致事务失败,这样有的事务被执行有的就没有被执行,从而就有了事务的回滚,取消先前的操作.....
JavaBean中使用JDBC方式进行事务处理
public int delete(int sID) {
dbc = new DataBaseConnection();
Connection con = dbc.getConnection();
try {
con.setAutoCommit(false);// 更改JDBC事务的默认提交方式
dbc.executeUpdate("delete from xiao where ID=" + sID);
dbc.executeUpdate("delete from xiao_content where ID=" + sID);
dbc.executeUpdate("delete from xiao_affix where bylawid=" + sID);
con.commit();//提交JDBC事务
con.setAutoCommit(true);// 恢复JDBC事务的默认提交方式
dbc.close();
return 1;
}
catch (Exception exc) {
con.rollBack();//回滚JDBC事务
exc.printStackTrace();
dbc.close();
return -1;
}
}
JavaBean中使用JDBC方式进行事务处理
public int delete(int sID) {
dbc = new DataBaseConnection();
Connection con = dbc.getConnection();
try {
con.setAutoCommit(false);// 更改JDBC事务的默认提交方式
dbc.executeUpdate("delete from xiao where ID=" + sID);
dbc.executeUpdate("delete from xiao_content where ID=" + sID);
dbc.executeUpdate("delete from xiao_affix where bylawid=" + sID);
con.commit();//提交JDBC事务
con.setAutoCommit(true);// 恢复JDBC事务的默认提交方式
dbc.close();
return 1;
}
catch (Exception exc) {
con.rollBack();//回滚JDBC事务
exc.printStackTrace();
dbc.close();
return -1;
}
}
Jason
2005-07-30 22:21:19
阅读:5542
评论:6
引用:0
目前,正在做广告联盟的程序,涉及到作弊这一块,用cookie毕竟可以清除,于是就想到了mac,到网上搜索半天,没有找到相关的文章,于是尝试找英文的,谁知道一找便发现一篇关于获得MAC Address,觉得不错,于是帖出供大家分享.
来源:http://forums.java.sun.com/thread.jspa?threadID=245711&tstart=240
/*
* 创建日期 2005-7-21
* @author jason
* @email sunchj2001@163.com
* 窗口 - 首选项 - Java - 代码样式 - 代码模板
*/
import java.net.InetAddress;
import java.io.InputStream;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.text.ParseException;
import java.util.StringTokenizer;
public final class NetworkInfo {
private final static String getMacAddress() throws IOException {
String os = System.getProperty("os.name");
try {
if (os.startsWith("Windows")) {
return windowsParseMacAddress(windowsRunIpConfigCommand());
} else if (os.startsWith("Linux")) {
return linuxParseMacAddress(linuxRunIfConfigCommand());
} else {
throw new IOException("unknown operating system: " + os);
}
} catch (ParseException ex) {
ex.printStackTrace();
throw new IOException(ex.getMessage());
}
}
/*
* Linux stuff
*/
private final static String linuxParseMacAddress(String ipConfigResponse)
throws ParseException {
String localHost = null;
try {
localHost = InetAddress.getLocalHost().getHostAddress();
} catch (java.net.UnknownHostException ex) {
ex.printStackTrace();
throw new ParseException(ex.getMessage(), 0);
}
StringTokenizer tokenizer = new StringTokenizer(ipConfigResponse, "\n");
String lastMacAddress = null;
while (tokenizer.hasMoreTokens()) {
String line = tokenizer.nextToken().trim();
boolean containsLocalHost = line.indexOf(localHost) >= 0;
// see if line contains IP address
if (containsLocalHost && lastMacAddress != null) {
return lastMacAddress;
}
// see if line contains MAC address
int macAddressPosition = line.indexOf("HWaddr");
if (macAddressPosition <= 0)
continue;
String macAddressCandidate = line.substring(macAddressPosition + 6)
.trim();
if (linuxIsMacAddress(macAddressCandidate)) {
lastMacAddress = macAddressCandidate;
continue;
}
}
ParseException ex = new ParseException("cannot read MAC address for "
+ localHost + " from [" + ipConfigResponse + "]", 0);
ex.printStackTrace();
throw ex;
}
private final static boolean linuxIsMacAddress(String macAddressCandidate) {
// TODO: use a smart regular expression
if (macAddressCandidate.length() != 17)
return false;
return true;
}
private final static String linuxRunIfConfigCommand() throws IOException {
Process p = Runtime.getRuntime().exec("ifconfig");
InputStream stdoutStream = new BufferedInputStream(p.getInputStream());
StringBuffer buffer = new StringBuffer();
for (;;) {
int c = stdoutStream.read();
if (c == -1)
break;
buffer.append((char) c);
}
String outputText = buffer.toString();
stdoutStream.close();
return outputText;
}
/*
* Windows stuff
*/
private final static String windowsParseMacAddress(String ipConfigResponse)
throws ParseException {
String localHost = null;
try {
localHost = InetAddress.getLocalHost().getHostAddress();
} catch (java.net.UnknownHostException ex) {
ex.printStackTrace();
throw new ParseException(ex.getMessage(), 0);
}
StringTokenizer tokenizer = new StringTokenizer(ipConfigResponse, "\n");
String lastMacAddress = null;
while (tokenizer.hasMoreTokens()) {
String line = tokenizer.nextToken().trim();
// see if line contains IP address
if (line.endsWith(localHost) && lastMacAddress != null) {
return lastMacAddress;
}
// see if line contains MAC address
int macAddressPosition = line.indexOf(":");
if (macAddressPosition <= 0)
continue;
String macAddressCandidate = line.substring(macAddressPosition + 1)
.trim();
if (windowsIsMacAddress(macAddressCandidate)) {
lastMacAddress = macAddressCandidate;
continue;
}
}
ParseException ex = new ParseException("cannot read MAC address from ["
+ ipConfigResponse + "]", 0);
ex.printStackTrace();
throw ex;
}
private final static boolean windowsIsMacAddress(String macAddressCandidate) {
// TODO: use a smart regular expression
if (macAddressCandidate.length() != 17)
return false;
return true;
}
private final static String windowsRunIpConfigCommand() throws IOException {
Process p = Runtime.getRuntime().exec("ipconfig /all");
InputStream stdoutStream = new BufferedInputStream(p.getInputStream());
StringBuffer buffer = new StringBuffer();
for (;;) {
int c = stdoutStream.read();
if (c == -1)
break;
buffer.append((char) c);
}
String outputText = buffer.toString();
stdoutStream.close();
return outputText;
}
/*
* Main
*/
public final static void main(String[] args) {
try {
System.out.println("Network infos");
System.out.println(" Operating System: "
+ System.getProperty("os.name"));
System.out.println(" IP/Localhost: "
+ InetAddress.getLocalHost().getHostAddress());
System.out.println(" MAC Address: " + getMacAddress());
} catch (Throwable t) {
t.printStackTrace();
}
}
}
来源:http://forums.java.sun.com/thread.jspa?threadID=245711&tstart=240
/*
* 创建日期 2005-7-21
* @author jason
* @email sunchj2001@163.com
* 窗口 - 首选项 - Java - 代码样式 - 代码模板
*/
import java.net.InetAddress;
import java.io.InputStream;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.text.ParseException;
import java.util.StringTokenizer;
public final class NetworkInfo {
private final static String getMacAddress() throws IOException {
String os = System.getProperty("os.name");
try {
if (os.startsWith("Windows")) {
return windowsParseMacAddress(windowsRunIpConfigCommand());
} else if (os.startsWith("Linux")) {
return linuxParseMacAddress(linuxRunIfConfigCommand());
} else {
throw new IOException("unknown operating system: " + os);
}
} catch (ParseException ex) {
ex.printStackTrace();
throw new IOException(ex.getMessage());
}
}
/*
* Linux stuff
*/
private final static String linuxParseMacAddress(String ipConfigResponse)
throws ParseException {
String localHost = null;
try {
localHost = InetAddress.getLocalHost().getHostAddress();
} catch (java.net.UnknownHostException ex) {
ex.printStackTrace();
throw new ParseException(ex.getMessage(), 0);
}
StringTokenizer tokenizer = new StringTokenizer(ipConfigResponse, "\n");
String lastMacAddress = null;
while (tokenizer.hasMoreTokens()) {
String line = tokenizer.nextToken().trim();
boolean containsLocalHost = line.indexOf(localHost) >= 0;
// see if line contains IP address
if (containsLocalHost && lastMacAddress != null) {
return lastMacAddress;
}
// see if line contains MAC address
int macAddressPosition = line.indexOf("HWaddr");
if (macAddressPosition <= 0)
continue;
String macAddressCandidate = line.substring(macAddressPosition + 6)
.trim();
if (linuxIsMacAddress(macAddressCandidate)) {
lastMacAddress = macAddressCandidate;
continue;
}
}
ParseException ex = new ParseException("cannot read MAC address for "
+ localHost + " from [" + ipConfigResponse + "]", 0);
ex.printStackTrace();
throw ex;
}
private final static boolean linuxIsMacAddress(String macAddressCandidate) {
// TODO: use a smart regular expression
if (macAddressCandidate.length() != 17)
return false;
return true;
}
private final static String linuxRunIfConfigCommand() throws IOException {
Process p = Runtime.getRuntime().exec("ifconfig");
InputStream stdoutStream = new BufferedInputStream(p.getInputStream());
StringBuffer buffer = new StringBuffer();
for (;;) {
int c = stdoutStream.read();
if (c == -1)
break;
buffer.append((char) c);
}
String outputText = buffer.toString();
stdoutStream.close();
return outputText;
}
/*
* Windows stuff
*/
private final static String windowsParseMacAddress(String ipConfigResponse)
throws ParseException {
String localHost = null;
try {
localHost = InetAddress.getLocalHost().getHostAddress();
} catch (java.net.UnknownHostException ex) {
ex.printStackTrace();
throw new ParseException(ex.getMessage(), 0);
}
StringTokenizer tokenizer = new StringTokenizer(ipConfigResponse, "\n");
String lastMacAddress = null;
while (tokenizer.hasMoreTokens()) {
String line = tokenizer.nextToken().trim();
// see if line contains IP address
if (line.endsWith(localHost) && lastMacAddress != null) {
return lastMacAddress;
}
// see if line contains MAC address
int macAddressPosition = line.indexOf(":");
if (macAddressPosition <= 0)
continue;
String macAddressCandidate = line.substring(macAddressPosition + 1)
.trim();
if (windowsIsMacAddress(macAddressCandidate)) {
lastMacAddress = macAddressCandidate;
continue;
}
}
ParseException ex = new ParseException("cannot read MAC address from ["
+ ipConfigResponse + "]", 0);
ex.printStackTrace();
throw ex;
}
private final static boolean windowsIsMacAddress(String macAddressCandidate) {
// TODO: use a smart regular expression
if (macAddressCandidate.length() != 17)
return false;
return true;
}
private final static String windowsRunIpConfigCommand() throws IOException {
Process p = Runtime.getRuntime().exec("ipconfig /all");
InputStream stdoutStream = new BufferedInputStream(p.getInputStream());
StringBuffer buffer = new StringBuffer();
for (;;) {
int c = stdoutStream.read();
if (c == -1)
break;
buffer.append((char) c);
}
String outputText = buffer.toString();
stdoutStream.close();
return outputText;
}
/*
* Main
*/
public final static void main(String[] args) {
try {
System.out.println("Network infos");
System.out.println(" Operating System: "
+ System.getProperty("os.name"));
System.out.println(" IP/Localhost: "
+ InetAddress.getLocalHost().getHostAddress());
System.out.println(" MAC Address: " + getMacAddress());
} catch (Throwable t) {
t.printStackTrace();
}
}
}
Jason
2005-07-21 09:28:43
阅读:2468
评论:6
引用:0
我们大家一起庆祝一下党的生日.
Jason
2005-07-01 11:45:01
阅读:2869
评论:4
引用:0
来源:http://www.javaresearch.org/article/showarticle.jsp?column=545&thread=17460
哈希表是一种重要的存储方式,也是一种常见的检索方法。其基本思想是将关系码的值作为自变量,通过一定的函数关系计算出对应的函数值,把这个数值解释为结点的存储地址,将结点存入计算得到存储地址所对应的存储单元。检索时采用检索关键码的方法。现在哈希表有一套完整的算法来进行插入、删除和解决冲突。在Java中哈希表用于存储对象,实现快速检索。
Java.util.Hashtable提供了种方法让用户使用哈希表,而不需要考虑其哈希表真正如何工作。
哈希表类中提供了三种构造方法,分别是:
public Hashtable()
public Hashtable(int initialcapacity)
public Hashtable(int initialCapacity,float loadFactor)
参数initialCapacity是Hashtable的初始容量,它的值应大于0。loadFactor又称装载因子,是一个0.0到0.1之间的float型的浮点数。它是一个百分比,表明了哈希表何时需要扩充,例如,有一哈希表,容量为100,而装载因子为0.9,那么当哈希表90%的容量已被使用时,此哈希表会自动扩充成一个更大的哈希表。如果用户不赋这些参数,系统会自动进行处理,而不需要用户操心。
Hashtable提供了基本的插入、检索等方法。
■插入
public synchronized void put(Object key,Object value)
给对象value设定一关键字key,并将其加到Hashtable中。若此关键字已经存在,则将此关键字对应的旧对象更新为新的对象Value。这表明在哈希表中相同的关键字不可能对应不同的对象(从哈希表的基本思想来看,这也是显而易见的)。
■检索
public synchronized Object get(Object key)
根据给定关键字key获取相对应的对象。
public synchronized boolean containsKey(Object key)
判断哈希表中是否包含关键字key。
public synchronized boolean contains(Object value)
判断value是否是哈希表中的一个元素。
■删除
public synchronized object remove(object key)
从哈希表中删除关键字key所对应的对象。
public synchronized void clear()
清除哈希表
另外,Hashtalbe还提供方法获取相对应的枚举集合:
public synchronized Enumeration keys()
返回关键字对应的枚举对象。
public synchronized Enumeration elements()
返回元素对应的枚举对象。
例8.5 Hashtable.java给出了使用Hashtable的例子。
例8.5 Hashtalbe.java。
//import java.lang.*;
import java.util.Hashtable;
import java.util.Enumeration;
public class HashApp{
public static void main(String args[]){
Hashtable hash=new Hashtable(2,(float)0.8);
//创建了一个哈希表的对象hash,初始容量为2,装载因子为0.8
hash.put("Jiangsu","Nanjing");
//将字符串对象“Jiangsu”给定一关键字“Nanjing”,并将它加入hash
hash.put("Beijing","Beijing");
hash.put("Zhejiang","Hangzhou");
System.out.println("The hashtable hash1 is: "+hash);
System.out.println("The size of this hash table is "+hash.size());
//打印hash的内容和大小
Enumeration enum1=hash.elements();
System.out.print("The element of hash is: ");
while(enum1.hasMoreElements())
System.out.print(enum1.nextElement()+" ");
System.out.println();
//依次打印hash中的内容
if(hash.containsKey("Jiangsu"))
System.out.println("The capatial of Jiangsu is "+hash.get("Jiangsu"));
hash.remove("Beijing");
//删除关键字Beijing对应对象
System.out.println("The hashtable hash2 is: "+hash);
System.out.println("The size of this hash table is "+hash.size());
}
}
运行结果:
The hashtable hash1 is: {Beijing=Beijing, Zhejiang=Hangzhou, Jiangsu=Nanjing}
The size of this hash table is 3
The element of hash is: Beijing Hangzhou Nanjing
The capatial of Jiangsu is Nanjing
The hashtable hash2 is: {Zhejiang=Hangzhou, Jiangsu=Nanjing}
The size of this hash table is 2
Hashtable是Dictionary(字典)类的子类。在字典类中就把关键字对应到数据值。字典类是一个抽象类。在java.util中还有一个类Properties,它是Hashtable的子类。用它可以进行与对象属性相关的操作。
哈希表是一种重要的存储方式,也是一种常见的检索方法。其基本思想是将关系码的值作为自变量,通过一定的函数关系计算出对应的函数值,把这个数值解释为结点的存储地址,将结点存入计算得到存储地址所对应的存储单元。检索时采用检索关键码的方法。现在哈希表有一套完整的算法来进行插入、删除和解决冲突。在Java中哈希表用于存储对象,实现快速检索。
Java.util.Hashtable提供了种方法让用户使用哈希表,而不需要考虑其哈希表真正如何工作。
哈希表类中提供了三种构造方法,分别是:
public Hashtable()
public Hashtable(int initialcapacity)
public Hashtable(int initialCapacity,float loadFactor)
参数initialCapacity是Hashtable的初始容量,它的值应大于0。loadFactor又称装载因子,是一个0.0到0.1之间的float型的浮点数。它是一个百分比,表明了哈希表何时需要扩充,例如,有一哈希表,容量为100,而装载因子为0.9,那么当哈希表90%的容量已被使用时,此哈希表会自动扩充成一个更大的哈希表。如果用户不赋这些参数,系统会自动进行处理,而不需要用户操心。
Hashtable提供了基本的插入、检索等方法。
■插入
public synchronized void put(Object key,Object value)
给对象value设定一关键字key,并将其加到Hashtable中。若此关键字已经存在,则将此关键字对应的旧对象更新为新的对象Value。这表明在哈希表中相同的关键字不可能对应不同的对象(从哈希表的基本思想来看,这也是显而易见的)。
■检索
public synchronized Object get(Object key)
根据给定关键字key获取相对应的对象。
public synchronized boolean containsKey(Object key)
判断哈希表中是否包含关键字key。
public synchronized boolean contains(Object value)
判断value是否是哈希表中的一个元素。
■删除
public synchronized object remove(object key)
从哈希表中删除关键字key所对应的对象。
public synchronized void clear()
清除哈希表
另外,Hashtalbe还提供方法获取相对应的枚举集合:
public synchronized Enumeration keys()
返回关键字对应的枚举对象。
public synchronized Enumeration elements()
返回元素对应的枚举对象。
例8.5 Hashtable.java给出了使用Hashtable的例子。
例8.5 Hashtalbe.java。
//import java.lang.*;
import java.util.Hashtable;
import java.util.Enumeration;
public class HashApp{
public static void main(String args[]){
Hashtable hash=new Hashtable(2,(float)0.8);
//创建了一个哈希表的对象hash,初始容量为2,装载因子为0.8
hash.put("Jiangsu","Nanjing");
//将字符串对象“Jiangsu”给定一关键字“Nanjing”,并将它加入hash
hash.put("Beijing","Beijing");
hash.put("Zhejiang","Hangzhou");
System.out.println("The hashtable hash1 is: "+hash);
System.out.println("The size of this hash table is "+hash.size());
//打印hash的内容和大小
Enumeration enum1=hash.elements();
System.out.print("The element of hash is: ");
while(enum1.hasMoreElements())
System.out.print(enum1.nextElement()+" ");
System.out.println();
//依次打印hash中的内容
if(hash.containsKey("Jiangsu"))
System.out.println("The capatial of Jiangsu is "+hash.get("Jiangsu"));
hash.remove("Beijing");
//删除关键字Beijing对应对象
System.out.println("The hashtable hash2 is: "+hash);
System.out.println("The size of this hash table is "+hash.size());
}
}
运行结果:
The hashtable hash1 is: {Beijing=Beijing, Zhejiang=Hangzhou, Jiangsu=Nanjing}
The size of this hash table is 3
The element of hash is: Beijing Hangzhou Nanjing
The capatial of Jiangsu is Nanjing
The hashtable hash2 is: {Zhejiang=Hangzhou, Jiangsu=Nanjing}
The size of this hash table is 2
Hashtable是Dictionary(字典)类的子类。在字典类中就把关键字对应到数据值。字典类是一个抽象类。在java.util中还有一个类Properties,它是Hashtable的子类。用它可以进行与对象属性相关的操作。
Jason
2005-06-26 10:11:04
阅读:5132
评论:0
引用:0
给客户做系统的时候,我们定义了一个字段,其值类似于10-1#103,谁知道通过地址栏传递的时候没有传过去,只传了#号前面的,可是比较特殊的字符.后来就想了一个办法,替换字符,就这样终于问题解决了.
我的那个替换函数如下:
public String htmlz(String str,String newstr,String oldstr)
{
int find = -1;
int oldrep = oldstr.length();
do{
find = str.indexOf(oldstr);
if(find != -1)
str = str.substring(0,find) + newstr + str.substring(find+oldrep);
}while(find != -1);
return str;
}
我的那个替换函数如下:
public String htmlz(String str,String newstr,String oldstr)
{
int find = -1;
int oldrep = oldstr.length();
do{
find = str.indexOf(oldstr);
if(find != -1)
str = str.substring(0,find) + newstr + str.substring(find+oldrep);
}while(find != -1);
return str;
}
Jason
2005-06-24 16:39:27
阅读:2006
评论:1
引用:0
package com.tiantian;
import java.util.*;
public class JAVAContainer {
public static void main(String[] args) throws Exception {
// ArrayList
{
ArrayList arraylist = new ArrayList();
arraylist.add(0, "end");//指定索引加入值
// 需注意的是,如果现有2个值,我加入索引为5的那么就会出现异常
for (int i = 0; i < 2; i++) {
arraylist.add(i, String.valueOf(i));
}
System.out.println("ArrayList:");
for (int i = 0; i < arraylist.size(); i++) {
System.out.print(arraylist.get(i) + ";");
}
arraylist.add("0");//直接加入值到ArrayList的最后
arraylist.add("0");
System.out.print(" ArrayList's lastIndexOf("0") is "
+ arraylist.lastIndexOf("0"));
}
// Arrays
{
String[] array = new String[] { "a", "b", "c" };
List list = Arrays.asList(array);
System.out.println(" Arrays:");
for (int i = 0; i < list.size(); i++) {
System.out.print(list.get(i) + ";");
}
System.out.print(" Arrays's length is " + array.length);//打印数组的长度
}
// Collections
{
String[] array = new String[] { "a", "b", "c" };
List list = Arrays.asList(array);
Collections.fill(list, "Fill");//用Fill填充全部元素
System.out.println(" Collections:");
for (int i = 0; i < list.size(); i++) {
System.out.print(list.get(i) + ";");
}
array = new String[] { "1", "2", "3" };
List list2 = Arrays.asList(array);
Collections.copy(list, list2);//拷贝list2的数据进list
System.out.println(" " + list);
Collections.swap(list, 2, 1);//调换索引为1和2的元素的位置
System.out.println(list);
}
// EventObject
{
String s = "hello";
String s2 = s;
EventObject eventobject = new EventObject(s);//一个准容器类型,确切的归类它不是容器
System.out.println("EventObject:");
System.out.println(eventobject.getSource());
System.out.println(eventobject.equals(s2));
}
// HashMap
{
HashMap hashmap = new HashMap();//一个速度最快的容器
hashmap.put("0", "c");
hashmap.put("1", "a");
hashmap.put("2", "b");
hashmap.put("3", "a");
System.out.println("HashMap:");
System.out.println(hashmap);//该容器有其内部的排序方式
Set set = hashmap.keySet();//获取全部键
Iterator iterator = set.iterator();
while (iterator.hasNext()) {
System.out.print(hashmap.get(iterator.next()) + ";");
}
}
// HashSet
{
HashSet hashset = new HashSet();//一个绝对不能重复的类型
hashset.add("c");
hashset.add("b");
hashset.add("a");
hashset.add("a");
hashset.add("b");
System.out.println(" HashSet:");
System.out.println(hashset);
Iterator iterator = hashset.iterator();//取出元素
while (iterator.hasNext()) {
System.out.print(iterator.next() + ";");
}
}
// Hashtable
{
Hashtable hashtable = new Hashtable();//一个完全可以由其他容器替换的老容器类型
hashtable.put("0", "c");
hashtable.put("1", "a");
hashtable.put("3", "c");
hashtable.put("2", "b");
System.out.println(" Hashtable:");
Enumeration enumeration = hashtable.elements();//获取元素,Enumeration已经不是主流,Iterator是它的下一代替代品
while (enumeration.hasMoreElements()) {
System.out.print(enumeration.nextElement() + ";");
}
}
// IdentityHashMap
{
IdentityHashMap identityhashmap = new IdentityHashMap();
identityhashmap.put("0", "c");
identityhashmap.put("1", "a");
identityhashmap.put("3", "b");
identityhashmap.put("2", "a");
System.out.println(" IdentityHashMap:");
System.out.println(identityhashmap);
System.out.println(identityhashmap.containsKey("3"));//是否包含这个键
System.out.println(identityhashmap.containsValue("a"));//是否包含值
Set set = identityhashmap.entrySet();//传为Set类型
System.out.println(set);
set = identityhashmap.keySet();//全部键
System.out.println(set);
}
// LinkedHashMap
{
LinkedHashMap linkedhashmap = new LinkedHashMap();
linkedhashmap.put("0", "b");
linkedhashmap.put("2", "a");
linkedhashmap.put("1", "c");
linkedhashmap.put("3", "b");
System.out.println("LinkedHashMap:");
System.out.println(linkedhashmap);
System.out.println(linkedhashmap.containsKey("2"));//是否包含这个键
System.out.println(linkedhashmap.containsValue("c"));//是否包含值
Set set = linkedhashmap.keySet();
Iterator iterator = set.iterator();
while (iterator.hasNext()) {
System.out.print(linkedhashmap.get(iterator.next()) + ";");
}
}
// LinkedHashSet
{
LinkedHashSet linkedhashset = new LinkedHashSet();//它包含了几种Set的属性但却没有自己的特色
linkedhashset.add("c");
linkedhashset.add("a");
linkedhashset.add("a");
linkedhashset.add("b");
System.out.println(" LinkedHashSet:");
System.out.println(linkedhashset);
System.out.println(linkedhashset.contains("a"));//是否包含对象
Iterator iterator = linkedhashset.iterator();
while (iterator.hasNext()) {
System.out.print(iterator.next() + ";");
}
}
// LinkedList
{
LinkedList linkedlist = new LinkedList();//自由使用是它的特色
linkedlist.add("a");
linkedlist.add(1, "c");
linkedlist.addLast("b");
linkedlist.addFirst("d");
System.out.println(" LinkedList:");
System.out.println(linkedlist);
// linkedlist.clear();//该方法清空容器
// linkedlist.remove(0);//删除索引为0的元素
// linkedlist.remove("d");//删除值为d的元素
// linkedlist.removeFirst();//删除第一个元素
// linkedlist.removeLast();//删除最后一个元素
for (int i = 0; i < linkedlist.size(); i++) {
System.out.print(linkedlist.get(i) + ";");
}
}
// Stack
{
Stack stack = new Stack();//堆栈
stack.add("b");
stack.add(0, "c");
stack.push("d");
stack.add("e");
stack.push("a");
Enumeration enumeration = stack.elements();
System.out.println(" Stack:");
while (enumeration.hasMoreElements()) {
System.out.print(enumeration.nextElement() + ";");
}
// 后进先出
System.out.println(" " + stack.peek());
System.out.println(stack.pop());
System.out.println(stack.contains("d") + ";" + stack.contains("a"));//是否包含该元素,有趣的事情发生了
System.out.println(stack.search("c"));//非常有用的属性,检索,但是由后向前的排列
}
// TreeMap
{
TreeMap treemap = new TreeMap();
treemap.put("0", "d");
treemap.put("2", "a");
treemap.put("1", "b");
treemap.put("3", "c");
System.out.println(" TreeMap:");//可以对键排序
System.out.println(treemap);
System.out.println(treemap.firstKey());//返回第一个键
Set set = treemap.keySet();
Iterator iterator = set.iterator();
while (iterator.hasNext()) {
System.out.print(treemap.get(iterator.next()) + ";");
}
}
// TreeSet
{
TreeSet treeset = new TreeSet();//自动排序内容
treeset.add("b");
treeset.add("a");
treeset.add("c");
treeset.add("d");
System.out.println(" TreeSet:");
System.out.println(treeset);
System.out.println(treeset.first());//返回第一个元素
Iterator iterator = treeset.iterator();
while (iterator.hasNext()) {
System.out.print(iterator.next() + ";");
}
}
// Vector
{
Vector vector = new Vector();
vector.add(0, "b");
vector.add("a");
vector.addElement("d");
vector.add("c");
System.out.println(" Vector:");
System.out.println(vector);
vector.set(2, "h");//替换掉指定索引的元素
System.out.println(vector);
Object[] str = vector.toArray();
for (int i = 0; i < str.length; i++) {
System.out.print(str<i> + ";");
}
vector.setSize(2);//重新设置大小为2
System.out.println(" " + vector);
}
// WeakHashMap
{
WeakHashMap weakhashmap = new WeakHashMap();
weakhashmap.put("1", "b");
weakhashmap.put("2", "c");
weakhashmap.put("0", "d");
weakhashmap.put("3", "a");
System.out.println(" WeakHashMap:");
System.out.println(weakhashmap);
System.out.println(weakhashmap.containsKey("3"));//是否包含键
System.out.println(weakhashmap.containsValue("d"));//是否包含值
Set set = weakhashmap.entrySet();
Iterator iterator = set.iterator();
while (iterator.hasNext()) {
System.out.print(iterator.next() + ";");
}
// weakhashmap.remove("2");//删除该键对应的值
// weakhashmap.get("1");//获取指定键的值
}
}
}
来源:http://blog.yesky.com/Blog/tiantian911/archive/0001/01/01/108330.html
Jason
2005-06-02 16:49:52
阅读:4454
评论:0
引用:0
