Oracle9i的全文检索技术

摘要 全文检索技术是智能信息管理的关键技术之一,Oracle Text作为Oracle9i的一个组件,提供了强大的全文检索功能,用Oracle9i做后台数据库,就可以充分利用其全文检索技术,构建复杂的大型文档管理系统。本文主要介绍了Oracle Text的体系结构及其使用。   关键词 Oracle Text 全文检索   Oracle一直致力于全文检索技术的研究,当Oracle9i Rlease2发布之时,Oracle数据库的全文检索技术已经非常完美,Oracle Text使Oracle9i具备了强大的文本检索能力和智能化的文本管理能力。Oracle Text是Oracle9i采用的新名称,在Oracle8/8i中它被称作Oracle interMedia Text,在Oracle8以前它的名称是Oracle ConText Cartridge。使用Oracle9i和Oracle Text,可以方便而有效地利用标准的SQL工具来构建基于文本的新的开发工具或对现有应用程序进行扩展。应用程序开发人员可以在任何使用文本的Oracle数据库应用程序中充分利用Oracle Text搜索,应用范围可以是现有应用程序中可搜索的注释字段,也可是实现涉及多种文档格式和复杂搜索标准的大型文档管理系统。Oracle Text支持Oracle数据库所支持的大多数语言的基本全文搜索功能。本文将介绍如何使用Oracle9i的全文检索技术来为自己的应用提供一个优秀的解决方案。     1 Oracle Text的体系架构   下图是Oracle Text的体系架构。 图1 Oracle Text的体系架构   以上面的体系架构图为基础,Oracle Text 索引文档时所使用的主要逻辑步骤如下:   (1)数据存储逻辑搜索表的所有行,并读取列中的数据。通常,这只是列数据,但有些数据存储使用列数据作为文档数据的指针。例如,URL_DATASTORE 将列数据作为 URL 使用。   (2)过滤器提取文档数据并将其转换为文本表示方式。存储二进制文档 (如 Word 或 Acrobat 文件) 时需要这样做。过滤器的输出不必是纯文本格式 -- 它可以是 XML 或 HTML 之类的文本格式。   (3)分段器提取过滤器的输出信息,并将其转换为纯文本。包括 XML 和 HTML 在内的不同文本格式有不同的分段器。转换为纯文本涉及检测重要文档段标记、移去不可见的信息和文本重新格式化。   (4)词法分析器提取分段器中的纯文本,并将其拆分为不连续的标记。既存在空白字符分隔语言使用的词法分析器,也存在分段复杂的亚洲语言使用的专门词法分析器。   (5)索引引擎提取词法分析器中的所有标记、文档段在分段器中的偏移量以及被称为非索引字的低信息含量字列表,并构建反向索引。倒排索引存储标记和含有这些标记的文档。   2 简单的示例   这里先给出一个简单示例说利用Oracle Text实现全文检索的方法与步骤,在后面在进行具体的说明。Orcale9i提供了Oracle Text Manager可以简化许多工作,所有在Oracle Text Manager中完成的工作,都可以在通过PL/SQL来实现。要使用Oracle Text,必须具有CTXAPP角色或者是CTXSYS用户。Oracle Text为系统管理员提供CTXSYS用户,为应用程序开发人员提供CTXAPP角色。   CTXSYS用户可执行以下任务:启动Oracle Text服务器,执行CTXAPP角色的所有任务。 具有CTXAPP角色的用户可执行以下任务: 创建索引,管理 Oracle Text 数据字典,包括创建和删除首选项,进行Oracle Text 查询,使用 Oracle Text PL/SQL程序包。   使用Oracle Text的步骤:   (1)创建表来保存某些文档。该示例使用一个主关键字列来标识每个文档,使用一个小的VARCHAR2列来保存每个文档。 CREATE TABLE docs (id NUMBER PRIMARY KEY, text VACHAR2(80));   (2)将两个示例文档置入该表: INSERT INTO docs VALUES (1, he first doc); INSERT INTO docs VALUES (2, he second doc); COMMIT;   (3)使用Oracle Text Manager来创建和修改首选项,首选项将与索引相关联。   (4)使用Oracle Text Manager创建文本索引。另外,可以输入以下使用默认首选项的 SQL 语句: CREATE INDEX doc_index ON docs(text) INDEXTYPE IS CTXSYS.CONTEXT;   (5)使用 CONTAINS 函数,发出基于内容的文档查询。例如: SELECT id FROM docs WHERE CONTAINS (text, first) > 0;   这将在文本列包含单词 first (即文档1) 的 docs 中查找所有行。语句中的>0部分是有效的Oracle SQL所必需的,Oracle SQL不支持函数的布尔返回值。   以上只是一个简单的示例,旨在给出使用Oracle Text建立全文索引的完整步骤,归纳起来如下:   (1)建表并装载文本(包含带有需要检索的文本字段)   (2)配置索引   (3)建立索引   (4)发出查询   (5)索引维护:同步与优化(将在后面介绍)   3 文本装载   要实现文本的全文检索首先必须把正确的文本加载到数据库表中,默认的建立索引行为要求将文档装载在文本列中,尽管可以用其它方式 (包括文件系统和 URL 形式)存储文档 (在"数据存储"选项进行设置)。默认情况下,系统应该将文档装载在文本列中。文本列可以是VARCHAR2、CLOB、BLOB、CHAR或BFILE。注意,只有在将Oracle7系统移植到Oracle8的情况下才支持用LONG和LONG RAW 这两个相反的列类型存储文本。不能为列类型NCLOB、DATE和NUMBER建立索引。   关于文档格式,因为系统能为包括HTML、PDF、Microsoft Word和纯文本在内的大多数文档格式建立索引,可以将其中的任何文档类型装载到文本列中(在"过滤器"选项中设置)。有关所支持的文档格式的详细信息,可以参阅Oracle Text Users Guide and Reference 中的附录"Supported Filter Formats"。   装载方法主要有以下几种:   (1)SQL INSERT 语句   (2)ctxload 可执行文件   (3)SQL*Loader   (4)从 BFILE 中装载 LOB 的 DBMS_LOB.LOADFROMFILE() PL/SQL 过程   (5)Oracle Call Interface   4 为文本建立索引   文本装入文本列后,就可以创建Oracle Text索引。文档以许多不同方案、格式和语言存储。因此,每个 Oracle Text 索引有许多需要设置的选项,以针对特定情况配置索引。创建索引时,Oracle Text可使用若干个默认值,但在大多数情况下要求用户通过指定首选项来配置索引。   每个索引的许多选项组成功能组,称为"类",每个类集中体现配置的某一方面,可以认为这些类就是与文档数据库有关的一些问题。例如:数据存储、过滤器、词法分析器、相关词表、存储等。   每个类具有许多预定义的行为,称之为对象。每个对象是类问题可能具有的答案,并且大多数对象都包含有属性。通过属性来定制对象,从而使对索引的配置更加多变以适应于不同的应用。   (1)存储(Storage)类   存储类指定构成Oracle Text索引的数据库表和索引的表空间参数和创建参数。它仅有一个基本对象:BASIC_STORAGE,其属性包括:I_Index_Clause、I_Table_Clause、K_Table_Clause、N_Table_Clause、P_Table_Clause、R_Table_Clause。   (2)数据存储(Datastore)类   数据存储:关于列中存储文本的位置和其他信息。默认情况下,文本直接存储到列中,表中的每行都表示一个单独的完整文档。其他数据存储位置包括存储在单独文件中或以其 URL 标识的 Web 页上。七个基本对象包括:Default_Datastore、Detail_Datastore、Direct_Datastore、File_Datastore、Multi_Column_Datastore 、URL_Datastore、User_Datastore,。   (3)文档段组(Section Group)类   文档段组是用于指定一组文档段的对象。必须先定义文档段,然后才能使用索引通过 WITHIN 运算符在文档段内进行查询。文档段定义为文档段组的一部分。包含七个基本对象:AUTO_SECTION_GROUP、BASIC_SECTION_GROUP、HTML_SECTION_GROUP、NEWS_SECTION_GROUP、NULL_SECTION_GROUP、XML_SECTION_GROUP、PATH_SECTION_GROUP。   (4)相关词表(Wordlist)类   相关词表标识用于索引的词干和模糊匹配查询选项的语言,只有一个基本对象BASIC_WORDLIST,其属性有:Fuzzy_Match、Fuzzy_Numresults、Fuzzy_Score、Stemmer、Substring_Index、Wildcard_Maxterms、Prefix_Index、Prefix_Max_Length、Prefix_Min_Length。   (5)索引集(Index Set)   索引集是一个或多个Oracle 索引 (不是Oracle Text索引) 的集合,用于创建 CTXCAT类型的Oracle Text索引,只有一个基本对象BASIC_INDEX_SET。   (6)词法分析器(Lexer)类   词法分析器类标识文本使用的语言,还确定在文本中如何标识标记。默认的词法分析器是英语或其他西欧语言,用空格、标准标点和非字母数字字符标识标记,同时禁用大小写。包含8个基本对象:BASIC_LEXER、CHINESE_LEXER、CHINESE_VGRAM_LEXER、JAPANESE_LEXER、JAPANESE_VGRAM_LEXER、KOREAN_LEXER、KOREAN__MORPH_ LEXER、MULTI_LEXER。   (7)过滤器(Filter)类   过滤器确定如何过滤文本以建立索引。可以使用过滤器对文字处理器处理的文档、格式化的文档、纯文本和 HTML 文档建立索引,包括5个基本对象:CHARSET_FILTER、INSO_FILTER INSO、NULL_FILTER、PROCEDURE_FILTER、USER_FILTER。   (8)非索引字表(Stoplist)类   非索引字表类是用以指定一组不编入索引的单词 (称为非索引字)。有两个基本对象:BASIC_STOPLIST (一种语言中的所有非索引字) 、 MULTI_STOPLIST (包含多种语言中的非索引字的多语言非索引字表)。   5 查询   建立了索引,就可以使用 SELECT 语句中的 CONTAINS 运算符发出文本查询。使用 CONTAINS 可以进行两种查询:单词查询和ABOUT查询。   5.1 词查询示例   词查询是对输入到 CONTAINS 运算符中单引号间的精确单词或短语的查询。在以下示例中,我们将查找文本列中包含 oracle 一词的所有文档。每行的分值由使用标签 1 的 SCORE 运算符选定: SELECT SCORE(1) title from news WHERE CONTAINS(text, oracle, 1) > 0;   在查询表达式中,可以使用 AND 和 OR 等文本运算符来获取不同结果。还可以将结构性谓词添加到 WHERE 子句中。可以使用 count(*)、CTX_QUERY.COUNT_HITS 或 CTX_QUERY.EXPLAIN 来计算查询的命中 (匹配) 数目。   5.2 ABOUT查询示例   在所有语言中,ABOUT查询增加了某查询所返回的相关文档的数目。在英语中,ABOUT 查询可以使用索引的主题词组件,该组件在默认情况下创建。这样,运算符将根据查询的概念返回文档,而不是仅依据所指定的精确单词或短语。例如,以下查询将查找文本列中关于主题 politics 的所有文档,而不是仅包含 politics 一词的文档: SELECT SCORE(1) title from news WHERE CONTAINS(text, about(politics), 1) > 0;   6 显示满足查询条件的文档   通常,通过使用Oracle Text查询应用程序,用户可查看查询所返回的文档。用户从命中列表中选择一个文档,然后应用程序以某种形式显示该文档。通过Oracle Text,可以用不同的方式再现文档。例如,可以通过突出显示查询词来显示文档。突出显示的查询词可以是相关词查询中的词,也可以是英文 ABOUT 查询中的主题词。   以下是关于输出效果和用于每个输出效果的过程的信息:   突出显示的文档,纯文本格式版本(CTX_DOC.MARKUP)   突出显示的文档,HTML版本(CTX_DOC.MARKUP)   突出显示纯文本格式版本的偏移量信息(CTX_DOC.HIGHLIGHT)   突出显示HTML 版本的偏移量信息(CTX_DOC.HIGHLIGHT)   纯文本格式版本,无突出显示(CTX_DOC.FILTER)   HTML版本文档,无突出显示(CTX_DOC.FILTER)   7 索引维护   索引建好后,如果表中的数据发生变化,比如增加或修改了记录,怎么办?由于对表所发生的任何DML语句,都不会自动修改索引,因此,必须定时同步(sync)和优化(optimize)索引,以正确反映数据的变化。 在索引建好后,可以在该用户下查到Oracle自动产生了以下几个表:(假设索引名为myindex): DR$myindex$I,DR$myindex$K,DR$myindex$R,DR$myindex$N   其中以I表最重要,可以查询一下该表: select token_text, token_count from DR$ myindex $I where rownum<=20;   查询结果在此省略。可以看到,该表中保存的其实就是Oracle 分析你的文档后,生成的term记录在这里,包括term出现的位置、次数、hash值等。当文档的内容改变后,可以想见这个I表的内容也应该相应改变,才能保证Oracle在做全文检索时正确检索到内容(因为所谓全文检索,其实核心就是查询这个表)。那么如何维护该表的内容,不能每次数据改变都重新建立索引,这就要用到sync 和 optimize了。   同步(sync):将新的term 保存到I表;   优化(optimize):清除I表的垃圾,主要是将已经被删除的term从I表删除。   Oracle提供了一个所谓的ctx server来做这个同步和优化的工作,只需要在后台运行这个进程,它会监视数据的变化,及时进行同步。另外,也可以用以下的job来完成(该job要建在和表同一个用户下): create or replace procedure sync is begin execute immediate alter index myindex rebuild online || parameters ( \sync\ ) ; execute immediate alter index myindex rebuild online || parameters ( \optimize full maxtime unlimited\ ) ; end sync; / Set ServerOutput on declare v_job number; begin Dbms_Job.Submit ( job => v_job, what => sync;, next_date => sysdate, /* default */ interval => sysdate + 1/720 /* = 1 day / ( 24 hrs * 30 min) = 2 mins */ ); Dbms_Job.Run ( v_job ); Dbms_Output.Put_Line ( Submitted as job # || to_char ( v_job ) ); end; /   job的SYSDATE + (1/720)是指每隔2分钟同步一次。具体的时间间隔,可以根据自己的应用的需要而定。   8 小结   文本对于各种规模的公司、机构组织来说,都是包含众多丰富信息的最有效载体,Oracle Text的推出,标志着Oracle提供了一套崭新的技术,可以便捷安全的用于管理企业的文本信息。Oracle Text使应用程序开发者可以透明地将全文检索能力加入到基于SQL的应用程序中,Oracle Text也是其他Oracle产品的核心组件,比如Oracle9iAS Portal,Oracle eBusiness Suite,Oracle Ultra Search和Oracle Internet File System等。灵活运用Oracle Text提供的全文检索技术,就可以使自己的应用具备强大的全文检索能力。 <淘宝热门商品:
 

 

【广州商盟】意外金喜服装◎抵制暴利低价有好货◎收藏小店有惊喜

 

118.00 元 

【冲皇冠】八心八箭瑞士钻石六爪经典钻戒指


来源:程序员网

小小豆叮

JBoss 4应用服务器指南文档发布

近日,开源组织JBoss发布了J2EE应用服务器JBoss 4.0的应用指南文档。JBoss用户可以在以下地址下载这份文档: http://docs.jboss.org/jbossas/jboss4guide/r1/html/ 目前这份文档尚未最终正式定稿,可以在JBoss文档论坛提出意见和建议。 JBoss 4.0是业界领先的开源J2EE应用服务器,也是唯一一个全面基于AOP思想设计的应用服务器产品,因此受到Java开发者的广泛关注。 <淘宝热门商品:
 

3C数码配件 

:麒麟光电

 

165.00 元  

小S推荐 第二代升级版 纤の瘦纤体胶囊


来源:程序员网

小小豆叮

教你如何成为一名Java初级程序员

目前,JAVA是开发人员的热宠,很多论坛都有不少热爱JAVA的开发人员,也有不少想成为JAVA程序员,但苦于不知道该如何学习,也不清楚该学些什么知识才能成为一个JAVA程序员。本人在这里抛砖引玉,和大家讨论成为一个JAVA初级程序员应该具有的知识,与大家共享。   个人认为想成为一个合格的JAVA初级程序员应该具备如下知识:   一、面向对象的知识:JAVA是一个面向对象的开发语言,因此熟悉面向对象对学习JAVA很有必要,您要了解:什么是对象,什么是类;什么是封装,什么是多态,什么是继承;什么是抽象类,什么是接口。了解了概念后,您还需要这些概念是如何体现的,如类和对象有什么区别?类是如何封装的?   二、JAVA语法:如果您已经有了开发经验,恭喜您,您学习JAVA语法来将比较容易。如果您有C++等面向对象语言的开发经验,您只需简单的翻看一下介绍JAVA的相关书籍就可以了。如果您是新手,没有关系,您下些工夫,好好研究一本JAVA初级教程之类的书就可以了。   学习了JAVA语法,加上面向对象的知识,只有您用心,您就可以写出来比较好的JAVA代码了。如果您再抽出时间熟悉一下JAVA编程规范,您代码的水平就应该不俗了。   三、JSP和HTML:在我国的绝大多数公司,做JAVA程序员都少不了和JSP以及HTML打交道。因此,想成为JAVA程序员就不可避免的要熟悉JSP和HTML,您最好能知道JSP的几个内置对象,如Session,Request,Reponse,,以及常用的JSP标签,如include,userBean等。尽管一些工具会帮您生成HTML代码,但您还是要熟悉比如title,,,,等。如果您再熟悉一下JS和CSS就更好了,那会使您制作的页面更友好。   四、WebServer:熟悉了以上三种,可以肯定的说您已经可以制作出来JSP页面了,您也可以在您的页面里使用自己开发的JAVA类(JAVABEAN)了,但您的页面总要跑起来才能看到您要的效果,这就要求您必须熟悉一种WebServer,比如:TOMCAT,RESIN等。您要熟悉如何发布您的应用,如何利用WebServer的数据库资源等。   五、开发工具:大家都知道,开发工具可以帮助您更好更快地开发,因此熟悉几种开发工具很有必要。目前JAVA的开发工具比较流行的有JBuilder,IDEA,Eclipse,HTML的开发工具有Dreamweaver等。   六、熟悉一种框架:熟悉一种框架其实是成为JAVA程序员的一种可选知识,但目前开发B/S结构的应用的开发小组,都差不多会采用一种框架来构建自己的应用系统。框架都会有许多可重用的代码,良好的层次关系和业务控制逻辑,基于框架的开发使你可以省出很多的开发成本。目前比较流行的框架有Struts和WAF等。 <淘宝热门商品:
 

198.00 元 

BENEFIT特配丰胸组合 天然丰胸食品_海量顾客反馈

 

 

自然美人 红酒面膜及口碑护理产品


来源:程序员网

小小豆叮

SCJP考试题310-025(第二套<3>)51-91/147

这是第2套题中的51-90题,只因为上网时间不多!所以只有借个地方粘贴出来!因为题确实太多,所以想要全部题目的给我的邮箱huiwu917@gmial.com 发个信息!写明SCJP考试试题第2套! 310-025 Leading the way in IT testing and certification tools, www.testking.com Question No 51 Exhibit: 1. import java.io.IOException; 2. public class ExceptionTest( 3. public static void main (String[]args) 4. try ( 5. methodA(); 6. ) catch (IOException e) ( 7. system.out.printIn(“Caught IOException”); 8. ) catch (Exception e) ( 9. system.out.printIn(“Caught Exception”); 10. ) 11. ) 12. public void methodA () { 13. throw new IOException (); 14. ) 15. ) What is the result? A. The code will not compile. B. The output is caught exception. C. The output is caught IOException. D. The program executes normally without printing a message. Answer: A Question No 52 Exhibit: 1. public class test { 2. public static string output = “” 3. 4. public static void foo(int i) { 5. try { 6. if(i= =1) { 7. throw new Exception (); 8. } 9. output += “1”; 10. ) 11. catch(Exception e) { 12. output += “2”; 13. return; 14. ) 15. finally ( 16. output += “3”; 17. ) 18. output += “4”; 19. ) 20. 21. public static void main (string args[]) ( 22. foo(0); 23. foo(1); 24. 25. ) 26. ) What is the value of the variable output at line 24? Answer: 13423 Question No 53 Given: 1. public class Foo implements Runnable ( 2. public void run (Thread t) { 3. system.out.printIn(“Running.”); 4. } 5. public static void main (String[] args) { 6. new thread (new Foo()).start(); 7. ) 8. ) What is the result? A. An exception is thrown. B. The program exists without printing anything. C. An error at line 1 causes compilation to fail. D. An error at line 2 causes the compilation to fail. E. “Running” is printed and the program exits. Answer: D Question No 54 Which statement is true? A. If only one thread is blocked in the wait method of an object, and another thread executes the modify on that same object, then the first thread immediately resumes execution. B. If a thread is blocked in the wait method of an object, and another thread executes the notify method on the same object, it is still possible that the first thread might never resume execution. C. If a thread is blocked in the wait method of an object, and another thread executes the notify method on the same object, then the first thread definitely resumes execution as a direct and sole consequence of the notify call. D. If two threads are blocked in the wait method of one object, and another thread executes the notify method on the same object, then the first thread that executed the wait call first definitely resumes execution as a direct and sole consequence of the notify call. Answer: B Question No 55 Which two CANNOT directly cause a thread to stop executing? (Choose Two) A. Calling the yield method. B. Calling the wait method on an object. C. Calling the notify method on an object. D. Calling the notifyAll method on an object. E. Calling the start method on another Thread object. Answer: C, D Question No 56 Which two can be used to create a new Thread? (Choose Two) A. Extend java.lang.Thread and override the run method. B. Extend java.lang.Runnable and override the start method. C. Implement java.lang.thread and implement the run method. D. Implement java.lang.Runnable and implement the run method. E. Implement java.lang.Thread and implement the start method. Answer: A, D Question No 54 Which statement is true? A. If only one thread is blocked in the wait method of an object, and another thread executes the modify on that same object, then the first thread immediately resumes execution. B. If a thread is blocked in the wait method of an object, and another thread executes the notify method on the same object, it is still possible that the first thread might never resume execution. C. If a thread is blocked in the wait method of an object, and another thread executes the notify method on the same object, then the first thread definitely resumes execution as a direct and sole consequence of the notify call. D. If two threads are blocked in the wait method of one object, and another thread executes the notify method on the same object, then the first thread that executed the wait call first definitely resumes execution as a direct and sole consequence of the notify call. Answer: B Question No 55 Which two CANNOT directly cause a thread to stop executing? (Choose Two) A. Calling the yield method. B. Calling the wait method on an object. C. Calling the notify method on an object. D. Calling the notifyAll method on an object. E. Calling the start method on another Thread object. Answer: C, D Question No 56 Which two can be used to create a new Thread? (Choose Two) A. Extend java.lang.Thread and override the run method. B. Extend java.lang.Runnable and override the start method. C. Implement java.lang.thread and implement the run method. D. Implement java.lang.Runnable and implement the run method. E. Implement java.lang.Thread and implement the start method. Answer: A, D Question No 57 Given: 1. public class SyncTest ( 2. private int x; 3. private int y; 4. private synchronized void setX (int i) (x=1;) 5. private synchronized void setY (int i) (y=1;) 6. public void setXY(int 1)(set X(i); setY(i);) 7. public synchronized Boolean check() (return x !=y;) 8. ) Under which conditions will check () return true when called from a different class? A. Check() can never return true. B. Check() can return true when setXY is called by multiple threads. C. Check() can return true when multiple threads call setX and setY separately. D. Check() can only return true if SyncTest is changed to allow x and y to be set separately. Answer: B Question No 58 Exhibit: 1. class A implements runable ( 2. int i; 3. public void run () ( 4. try ( 5. thread.sleep(5000); 6. i= 10; 7. ) catch(InterruptedException e) {} 8. ) 9. ) 10. 11. public class Test { 12. public static void main (string args[]) ( 13. try ( 14. A a = new A (); 15. Thread t = new Thread (a); 16. t.start(); 17. 18. int j= a.i; 19. 20. ) catch (Exception e) {} 21. ) 22. ) Which statement al line 17 will ensure that j=10 at line 19? A. a.wait(); B. t.wait(); C. t.join(); D. t.yield(); E. t.notify(); F. a.notify(); G. t.interrupt(); Answer: C Question No 59 Exhibit: 1. public class X implements Runnable ( 2. private int x; 3. private int y; 4. 5. public static void main(String [] args) ( 6. X that = new X(); 7. (new Thread(that)) . start( ); 8. (new Thread(that)) . start( ); 9. ) 10. 11. public synchronized void run( ) ( 12. for (;;) ( 13. x++; 14. y++; 15. System.out.printIn(“x = “ + x + “, y = “ + y); 16. ) 17. ) 18. ) What is the result? A. An error at line 11 causes compilation to fail. B. Errors at lines 7 and 8 cause compilation to fail. C. The program prints pairs of values for x and y that might not always be the same on the same line (for example, “x=2, y=1”) D. The program prints pairs of values for x and y that are always the same on the same line (for example, “x=1, y=1”. In addition, each value appears twice (for example, “x=1, y=1” followed by “x=1, y=1”) E. The program prints pairs of values for x and y that are always the same on the same line (for example, “x=1, y=1”. In addition, each value appears twice (for example, “x=1, y=1” followed by “x=2s, y=2”) Answer: E QUESTION NO: 60 Which two CANNOT directly cause a thread to stop executing? (Choose Two) A. Existing from a synchronized block. B. Calling the wait method on an object. C. Calling notify method on an object. D. Calling read method on an InputStream object. E. Calling the SetPriority method on a Thread object. Answer: A, C QUESTION NO: 61 Exhibit 1. public class SyncTest{ 2. public static void main(String[] args) { 3. final StringBuffer s1= new StringBuffer(); 4. final StringBuffer s2= new StringBuffer(); 5. new Thread () { 6. public void run() { 7. synchronized(s1) { 8. s2.append(“A”); 9. synchronized(s2) { 10. s2.append(“B”); 11. System.out.print(s1); 12. System.out.print(s2); 13. } 14. } 15. } 16. }.start(); 17. new Thread() { 18. public void run() { 19. synchronized(s2) { 20. s2.append(“C”); 21. synchronized(s1) { 22. s1.append(“D”); 23. System.out.print(s2); 24. System.out.print(s1); 25. } 26. } 27. } 28. }.start(); 29. } 30. } Which two statements are true? (Choose Two) A. The program prints “ABBCAD” B. The program prints “CDDACB” C. The program prints “ADCBADBC” D. The output is a non-deterministic point because of a possible deadlock condition. E. The output is dependent on the threading model of the system the program is running on. Answer: D, B QUESTION NO: 62 Which method in the Thread class is used to create and launch a new thread of execution? A. Run(); B. Start(); B. Execute(); C. Run(Runnable r); D. Start(Runnable r); E. Execute(Thread t); Answer: B - QUESTION NO: 63 Given: 5. String foo = “base”; 6. foo.substring(0,3); 7. foo.concat(“ket”) 8. Type the value of foo at line 8. Answer: BASE QUESTION NO: 64 Which code determines the int value foo closest to, but not greater than, a double value bar? A. Int foo = (int) Math.max(bar); B. Int foo = (int) Math.min(bar); C. Int foo = (int) Math.abs(bar); D. Int foo = (int) Math.ceil(bar); E. Int foo = (int) Math.floor(bar); F. Int foo = (int) Math.round(bar); Answer: E QUESTION NO: 65 Which statement is true? A. A flow layout can be used to position a component that should resize horizontally when the container is resized. B. A grid layout can be used to position a component tat should maintain a constant size even when the container is resized. C. A border layout can be used to position component that should maintain a constant size even when the container is resized. D. The grid bag layout can be used to give a grid-like layout which differs from the normal grid in that individual rows and columns can have unique sizes. E. If two components are placed in the same column of a grid bag layout, and one component resizes horizontally, then the other component must resize horizontally. Answer: D QUESTION NO: 66 Given an ActionEvent, which method allows you to identify the affected Component? A. Public class getClass() B. Public Object getSource() C. Public Component getSource() D. Public Component getTarget() E. Public Component getComponent() F. Public Component getTargetComponent() Answer: B QUESTION NO: 67 Exhibit: 1. import java.awt.*; 2. 3. public class Test extends Frame { 4. public Test() { 5. add(new Label(“Hello”) ); 6. add(new TextField(“Hello”) ); 7. add(new Button(“Hello”) ); 8. pack(); 9. show(); 10. } 11. 12. public static void main(String args[]) { 13. new Test (); 14. } 15. ) What is the result? A. The code will not compile. B. A Window will appear containing only a Button. C. An IllegalArgumentException is thrown at line 6. D. A Window button will appear but will not contain the Label, TextField, or Button. E. A Window will appear containing a Label at the top, a TextField below the Label, and a Button below the TextField. F. A Window will appear containing a Label on the left, a TextField to the right of the Label, and a button to the right of the TextField. Answer: B QUESTION NO: 68 Exhibit: 1. class A { 2. public int getNumber(int a) { 3. return a + 1; 4. } 5. } 6. 7. class B extends A { 8. public int getNumber (int a) { 9. return a + 2 10. } 11. 12. public static void main (String args[]) { 13. A a = new B(); 14. System.out.printIn(a.getNumber(0)); 15. } 16. } What is the result? A. Compilation succeeds and 1 is printed. B. Compilation succeeds and 2 is printed. C. An error at line 8 causes compilation to fail. D. An error at line 13 causes compilation to fail. E. An error at line 14 causes compilation to fail. Answer: B QUESTION NO: 69 Given: 1. class BaseClass{ 2. private float x= 1.0f; 3. protected void setVar (float f) {x = f;} 4. } 5. class SubClass exyends BaseClass { 6. private float x = 2.0f; 7. //insert code here 8. } Which two are valid examples of method overriding? (Choose Two) A. Void setVar(float f) {x = f;} B. Public void setVar(int f) {x = f;} C. Public void setVar(float f) {x = f;} D. Public double setVar(float f) {x = f;} E. Public final void setVar(float f) {x = f;} F. Protected float setVar() {x=3.0f; return 3.0f; } Answer: C, E QUESTION NO: 70 Which statement about static inner classes is true? A. An anonymous class can be declared as static. B. A static inner class cannot be a static member of the outer class. C. A static inner class does not require an instance of the enclosing class. D. Instance members of a static inner class can be referenced using the class name of the static inner class. Answer: C QUESTION NO: 71 Exhibit: 1. class A { 2. public byte getNumber () { 3. return 1; 4. } 5. } 6. 7. class B extends A { 8. public short getNumber() { 9. return 2; 10. } 11. 12. public static void main (String args[]) { 13. B b = new B (); 14. System.out.printIn(b.getNumber()) 15. } 16. } What is the result? A. Compilation succeeds and 1 is printed. B. Compilation succeeds and 2 is printed. C. An error at line 8 causes compilation to fail. D. An error at line 14 causes compilation to fail. E. Compilation succeeds but an exception is thrown at line 14. Answer: C QUESTION NO: 72 Given: AnInterface is an interface. AnAdapter0 is a non-abstract, non-final class with a zero argument constructor. AnAdapter1 is a non-abstract, non-final class without a zero argument constructor, but with a constructor that takes one int argument. Which two construct an anonymous inner class? (Choose Two) F. AnAdapter1 aa=new AnAdapter1(){} G. AnAdapter0 aa=new AnAdapter0(){} H. AnAdapter0 aa=new AnAdapter0(5){} I. AnAdapter1 aa=new AnAdapter1(5){} J. AnInterface a1=new AnInterface(5){} Answer: B, D QUESTION NO: 73 Which two statements are true? (Choose Two) A. An inner class may be declared as static. B. An anonymous inner class can be declared as public. C. An anonymous inner class can be declared as private. D. An anonymous inner class can extend an abstract class. E. An anonymous inner class can be declared as protected. Answer: A, D QUESTION NO: 74 Exhibit: 1. public class Mycircle { 2. public double radius; 3. public double diameter; 4. 5. public void setRadius(double radius) 6. this.radius = radius; 7. this.diameter= radius * 2; 8. } 9. 10. public double getRadius() { 11. return radius; 12. } 13. } Which statement is true? A. The Mycircle class is fully encapsulated. B. The diameter of a given MyCircle is guaranteed to be twice its radius. C. Lines 6 and 7 should be in a synchronized block to ensure encapsulation. D. The radius of a MyCircle object can be set without affecting its diameter. Answer: B QUESTION NO: 75 You want to limit access to a method of a public class to members of the same class. Which access modifier accomplishes this objective? A. Public B. Private C. Protected D. Transient E. No access modifier is required Answer: B QUESTION NO: 76 Exhibit: ClassOne.java 1. package com.abc.pkg1; 2. public class ClassOne { 3. private char var = ‘a’; 4. char getVar() {return var;} 5. } ClassTest.java 1. package com.abc.pkg2; 2. import com.abc.pkg1.ClassOne; 3. public class ClassTest extends ClassOne { 4. public static void main(String[]args) { 5. char a = new ClassOne().getVar(); 6. char b = new ClassTest().getVar(); 7. } 8. } What is the result? A. Compilation will fail. B. Compilation succeeds and no exceptions are thrown. C. Compilation succeeds but an exception is thrown at line 5 in ClassTest.java. D. Compilation succeeds but an exception is thrown at line 6 in ClassTest.java. Answer: B QUESTION NO: 77 Given: 1. public class ArrayTest { 2. public static void main (String[]args) { 3. float f1[], f2[]; 4. f1 = new float [10]; 5. f2 = f1; 6. System.out.printIn (“f2[0]=” + f2[0]); 7. } 8. } What is the result? A. It prints f2[0] = 0.0 B. It prints f2[0] = NaN C. An error at line 5 causes compile to fail. D. An error at line 6 causes compile to fail. E. An error at line 6 causes an exception at runtime. Answer: A QUESTION NO: 78 Which two statements are true regarding the creation of a default constructor? (Choose Two) A. The default constructor initializes method variables. B. The compiler always creates a default constructor for every class. C. The default constructor invokes the no-parameter constructor of the superclass. D. The default constructor initializes the instance variables declared in the class. E. When a class has only constructors with parameters, the compiler does not create a default constructor. Answer: D, E QUESTION NO: 79 Exhibit: 1. class super { 2. public int getLength() {return 4;} 3. } 4. 5. public class Sub extends Super { 6. public long getLength() {return 5;} 7. 8. public static void main (String[]args) { 9. super sooper = new Super (); 10. Sub sub = new Sub(); 11. System.out.printIn( 12. sooper.getLength()+ “,” + sub.getLength() }; 13. } 14. } What is the output? A. 4, 4 B. 4, 5 C. 5, 4 D. 5, 5 E. The code will not compile. Answer: E QUESTION NO: 80 Given: 1. public abstract class Test { 2. public abstract void methodA(); 3. 4. public abstract void methodB() 5. { 6. System.out.printIn(“Hello”); 7. } 8. } Which three changes (made independently) allow the code to compile? (Choose Three) A. Add a method body to methodA. B. Replace lines 5-7 with a semicolon (“.”) C. Remove the abstract qualifier from the declaration of Test. D. Remove the abstract qualifier from the declaration of methodB. E. Remove the abstract qualifier from the declaration of methodA. F. Remove methodB in its entirely and change class o interface in line 1. Answer: B, D, F QUESTION NO: 81 Which determines if “prefs” is a directory and exists on the file system? A. Boolean exists=Directory.exists (“prefs”); B. Boolean exists=(new File(“prefs”)).isDir(); C. Boolean exists=(new Directory(“prefs”)).exists(); D. Boolean exists=(new File(“prefs”)).isDirectory(); E. Boolean exists=true; Try{ Directory d = new Directory(“prefs”); } catch (FileNotFoundException e) { exists = false; } Answer: D QUESTION NO: 82 Which two create an InputStream and open file the “file.txt” for reading? (Choose Two) A. InputStream in=new FileReader(“file.txt”); B. InputStream in=new FileInputStream(“file.txt”); C. InputStream in=new InputStreamFileReader (“file.txt”, “read”); D. FileInputStream in=new FileReader(new File(“file.txt”)); E. FileInputStream in=new FileInputStream(new File(“file.txt”)); Answer: B, E QUESTION NO 83 Which two construct an OutputSream that appends to the file “file.txt”? (Choose Two) A. OutputStream out=new FileOutputStream(“file.txt”); B. OutputStream out=new FileOutputStream(“file.txt”, “append”); C. FileOutputStream out=new FileOutputStream(“file.txt”, true); D. FileOutputStream out=new FileOutputStream(new file(“file.txt”)); E. OutputStream out=new FileOutputStream(new File(“file.txt”)true); Answer: C, E QUESTION NO: 84 Which constructs a BufferedIputStream? A. New BufferedInputStream(“in.txt”); B. New BufferedInputStream(new File(“in.txt”)); C. New BufferedInputStream(new Writer(“in.txt”)); D. New BufferedInputStream(new Writer(“in.txt”)); E. New BufferedInputStream(new InputStream(“in.txt”)); F. New BufferedInputStream(new FileInputStream(“in.txt”)); Answer: F QUESTION NO: 85 Which is a valid identifier? A. false B. default C. _object D. a-class Answer: C QUESTION NO: 86 Exhibit: 1. package foo; 2. 3. import java.util.Vector; 4. 5. private class MyVector extends Vector { 6. int i = 1; 7. public MyVector() { 8. i = 2; 9. } 10. } 11. 12. public class MyNewVector extends MyVector { 13. public MyNewVector () { 14. i = 4; 15. } 16. public static void main (String args []) { 17. MyVector v = new MyNewVector(); 18. } 19. } The file MyNewVector.java is shown in the exhibit. What is the result? A. Compilation will succeed. B. Compilation will fail at line 5. C. Compilation will fail at line 6. D. Compilation will fail at line 14. E. Compilation will fail at line 17. Answer: B QUESTION NO: 87 Given: 1. public class Test { 2. public static void main (String[]args) { 3. String foo = args[1]; 4. String bar = args[2]; 5. String baz = args[3]; 6. System.out.printIn(“baz = ” + baz); 7. } 8. } And the output: Baz = 2 Which command line invocation will produce the output? A. Java Test 2222 B. Java Test 1 2 3 4 C. Java Test 4 2 4 2 D. Java Test 4 3 2 1 Answer: C QUESTION NO: 88 Given: 8. int index = 1; 9. String [] test = new String[3]; 10. String foo = test[index]; What is the result? E. Foo has the value “” B. Foo has the value null C. An exception is thrown D. The code will not compile Answer: B QUESTION NO: 89 Given: 1. public interface Foo{ 2. int k = 4; 3. } Which three are equivalent to line 2? (Choose Three) A. Final int k = 4; B. Public int k = 4; C. Static int k = 4; D. Private int k = 4; E. Abstract int k = 4; F. Volatile int k = 4; G. Transient int k = 4; H. Protected int k = 4; Answer: A, B, C QUESTION NO: 90 Given: 310-025 Leading the way in IT testing and certification tools, www.testking.com - 48 - 1. public class foo { 2. static String s; 3. public static void main (String[]args) { 4. system.out.printIn (“s=” + s); 5. } 6. } What is the result? A. The code compiles and “s=” is printed. B. The code compiles and “s=null” is printed. C. The code does not compile because string s is not initialized. D. The code does not compile because string s cannot be referenced. E. The code compiles, but a NullPointerException is thrown when toString is called. Answer: B QUESTION NO: 91 Which two valid declarations of a char? (Choose Two) A. Char ch = “a”; B. Char ch = ‘\’ ‘; C. Char ch = ‘cafe’; D. Char ch = “cafe”; E. Char ch = ‘\ucafe’; F. Char ch = ‘\u10100’; G. Char ch = (char) true; Answer: B, E <淘宝热门商品:
 

98.00 元 

08新款 日式V领子二件套+黑色领带假二件套 本店热销款

 

网络游戏点卡 

网游点卡武汉移动话费自动充专卖店


来源:程序员网

小小豆叮

SCJP考试题310-025(第二套<2>)18-50/147

我在网上见到很多关于SCJP考试的说法,很多人说他简单!确实是这样的!但是这种说法只是当你拿到拿仅有的一套题的时候,你可以这样说!有人说他考的相当全面,确实是这样的,当你看到这一两百套题给你的时候,你就会有此感悟!呵呵!头晕啊!它考的好多地方都是你在看资料的时候不留心的地方你得不时的翻箱倒柜的找资料!这第2套题有147道题,你可以将它收集起来!当你留心看的时候,你的心就宛如一团乱麻,天那,这考的什么?想学真本事,就静下心,仔细研究吧!!!这是18-50题! 310-025 Leading the way in IT testing and certification tools, www.testking.com Question No 19 Given: 8. int index = 1; 9. boolean[] test = new Boolean[3]; 10. boolean foo= test [index]; What is the result? A. Foo has the value of 0. B. Foo has the value of null. C. Foo has the value of true. D. Foo has the value of false. E. An exception is thrown. F. The code will not compile. Answer: D Question No 20 Given: 1. public class test( 2. public static void main(string[]args){ 3. string foo = args [1]; 4. string foo = args [2]; 5. string foo = args [3]; 6. } 7. } And command line invocation: Java Test red green blue What is the result? A. Baz has the value of “” B. Baz has the value of null C. Baz has the value of “red” D. Baz has the value of “blue” E. Bax has the value of “green” F. The code does not compile. G. The program throws an exception. Answer: G Question No 21 Given: 8. int index = 1; 9. int [] foo = new int [3]; 10.int bar = foo [index]; 11.int baz = bar + index; What is the result? A. Baz has the value of 0 B. Baz has the value of 1 C. Baz has the value of 2 D. An exception is thrown. E. The code will not compile. Answer: B Question No 22 Given: 1. public class foo { 2. public static void main (String[]args) { 3. String s; 4. system.out.printIn (“s=” + s); 5. } 6. } What is the result? A. The code compiles and “s=” is printed. B. The code compiles and “s=null” is printed. C. The code does not compile because string s is not initialized. D. The code does not compile because string s cannot be referenced. E. The code compiles, but a NullPointerException is thrown when toString is called. Answer: C Question No 23 Which will declare a method that forces a subclass to implement it? A. Public double methoda(); B. Static void methoda (double d1) {} C. Public native double methoda(); D. Abstract public void methoda(); E. Protected void methoda (double d1){} Answer: D Question No 24 You want subclasses in any package to have access to members of a superclass. Which is the most restrictive access modifier that will accomplish this objective? A. Public B. Private C. Protected D. Transient E. No access modifier is qualified Answer: C Question No 25 Given: 1. abstract class abstrctIt { 2. abstract float getFloat (); 3. ) 4. public class AbstractTest extends AbstractIt { 5. private float f1= 1.0f; 6. private float getFloat () {return f1;} 7. } What is the result? A. Compilation is successful. B. An error on line 6 causes a runtime failure. C. An error at line 6 causes compilation to fail. D. An error at line 2 causes compilation to fail. Answer: C Question No 26 Exhibit: 1. public class test( 2. public int aMethod()[ 3. static int i=0; 4. i++; 5. return I; 6. ) 7. public static void main (String args[]){ 8. test test = new test(); 9. test.aMethod(); 10.int j = test.aMethod(); 11.System.out.printIn(j); 12.] 13.} What is the result? A. Compilation will fail. B. Compilation will succeed and the program will print “0” C. Compilation will succeed and the program will print “1” D. Compilation will succeed and the program will print “2” Answer: D Question No 27 Given: 1. class super { 2. public float getNum() {return 3.0f;} 3. ) 4. 5. public class Sub extends Super { 6. 7. ) Which method, placed at line 6, will cause a compiler error? A. Public float getNum() {return 4.0f; } B. Public void getNum () { } C. Public void getNum (double d) { } D. Public double getNum (float d) {retrun 4.0f; } Answer: B Question No 28 Which declaration prevents creating a subclass of an outer class? A. Static class FooBar{} B. Private class FooBar{} C. Abstract public class FooBar{} D. Final public class FooBar{} E. Final abstract class FooBar{} Answer: D Question No 29 Given: 1. byte [] arry1, array2[]; 2. byte array3 [][]; 3. byte[][] array4; If each array has been initialized, which statement will cause a compiler error? A. Array2 = array1; B. Array2 = array3; C. Array2 = array4; D. Both A and B E. Both A and C F. Both B and C Answer: F Question No 30 Exhibit: 1. class super ( 2. public int I = 0; 3. 4. public super (string text) ( 5. I = 1 6. ) 7. ) 8. 9. public class sub extends super ( 10. public sub (string text) ( 11. i= 2 12. ) 13. 14. public static void main (straing args[]) ( 15. sub sub = new sub (“Hello”); 16. system.out. PrintIn(sub.i); 17. ) 18. ) What is the result? A. Compilation will fail. B. Compilation will succeed and the program will print “0” C. Compilation will succeed and the program will print “1” D. Compilation will succeed and the program will print “2” Answer: A Question No 31 Given: 1. public class returnIt ( 2. returnType methodA(byte x, double y) ( 3. return (short) x/y * 2; 4. ) 5. ) What is the valid returnType for methodA in line 2? A. Int B. Byte C. Long D. Short E. Float F. Double Answer: F Question No 32 Given the ActionEvent, which method allows you to identify the affected component? A. GetClass. B. GetTarget. C. GetSource. D. GetComponent. E. GetTargetComponent. Answer: C Question No 33 Which is a method of the MouseMotionListener interface? A. Public void mouseMoved(MouseEvent) B. Public boolean mouseMoved(MouseEvent) C. Public void mouseMoved(MouseMotionEvent) D. Public boolean MouseMoved(MouseMotionEvent) E. Public boolean mouseMoved(MouseMotionEvent) Answer: A Question No 34 Exhibit: 1. import java.awt*; 2. 3. public class X extends Frame ( 4. public static void main(string []args) ( 5. X x = new X (); 6. X.pack(); 7. x.setVisible(true); 8. ) 9. 10. public X () ( 11. setlayout (new GridLayout (2,2)); 12. 13. Panel p1 = new panel(); 14. Add(p1); 15. Button b1= new Button (“One”); 16. P1.add(b1); 17. 18. Panel p2 = new panel(); 19. Add(p2); 20. Button b2= new Button (“Two”); 21. P2.add(b2); 22. 23. Button b3= new Button (“Three”); 24. add(b3); 25. 26. Button b4= new Button (“Four”); 27. add(b4); 28. ) 29. ) Which two statements are true? (Choose Two) A. All the buttons change height if the frame height is resized. B. All the buttons change width if the Frame width is resized. C. The size of the button labeled “One” is constant even if the Frame is resized. D. Both width and height of the button labeled “Three” might change if the Frame is resized. Answer: C, D Question No 35 You are assigned the task of building a panel containing a TextArea at the top, a label directly below it, and a button directly below the label. If the three components are added directly to the panel. Which layout manager can the panel use to ensure that the TextArea absorbs all of the free vertical space when the panel is resized? A. GridLayout. B. CardLayout. C. FlowLayout. D. BorderLayout. E. GridBagLayout. Answer: E Question No 36 Which gets the name of the parent directory file “file.txt”? A. String name= File.getParentName(“file.txt”); B. String name= (new File(“file.txt”)).getParent(); C. String name = (new File(“file.txt”)).getParentName(); D. String name= (new File(“file.txt”)).getParentFile(); E. Directory dir=(new File (“file.txt”)).getParentDir(); String name= dir.getName(); Answer: B Question No 37 Which can be used to encode charS for output? A. Java.io.OutputStream. B. Java.io.OutputStreamWriter. C. Java.io.EncodeOutputStream. D. Java.io.EncodeWriter. E. Java.io.BufferedOutputStream. Answer: B Question No 38 The file “file.txt” exists on the file system and contsins ASCII text. Given: 38. try { 39. File f = new File(“file.txt”); 40. OutputStream out = new FileOutputStream(f, true); 41. } 42. catch (IOException) {} What is the result? A. The code does not compile. B. The code runs and no change is made to the file. C. The code runs and sets the length of the file to 0. D. An exception is thrown because the file is not closed. E. The code runs and deletes the file from the file system. Answer: A Question No 39 Which constructs a DataOutputStream? A. New dataOutputStream(“out.txt”); B. New dataOutputStream(new file(“out.txt”)); C. New dataOutputStream(new writer(“out.txt”)); D. New dataOutputStream(new FileWriter(“out.txt”)); E. New dataOutputStream(new OutputStream(“out.txt”)); F. New dataOutputStream(new FileOutputStream(“out.txt”)); Answer: F Question No 40 What writes the text “” to the end of the file “file.txt”? A. OutputStream out= new FileOutputStream (“file.txt”); Out.writeBytes (“/n”); B. OutputStream os= new FileOutputStream (“file.txt”, true); DataOutputStream out = new DataOutputStream(os); out.writeBytes (“/n”); C. OutputStream os= new FileOutputStream (“file.txt”); DataOutputStream out = new DataOutputStream(os); out.writeBytes (“/n”); D. OutputStream os= new OutputStream (“file.txt”, true); DataOutputStream out = new DataOutputStream(os); out.writeBytes (“/n”); Answer: B Question No 41 Given: 1. public class X ( 2. public object m () { 3. object o = new float (3.14F); 4. object [] oa = new object [1]; 5. oa[0]= o; 6. o = null; 7. return oa[0]; 8. } 9. } When is the float object created in line 3, eligible for garbage collection? A. Just after line 5 B. Just after line 6 C. Just after line 7 (that is, as the method returns) D. Never in this method. Answer: D Question No 42 Given: 3. string foo = “ABCDE”; 4. foo.substring(3); 5. foo.concat(“XYZ”); 6. Type the value of foo at line 6. Answer: ABCDE Question No 43 Which method is an appropriate way to determine the cosine of 42 degrees? A. Double d = Math.cos(42); B. Double d = Math.cosine(42); C. Double d = Math.cos(Math.toRadians(42)); D. Double d = Math.cos(Math.toDegrees(42)); E. Double d = Math.cosine(Math.toRadians(42)); Answer: C Question No 44 You need to store elements in a collection that guarantees that no duplicates are stored and all elements can be accessed in natural order. Which interface provides that capability? A. Java.util.Map. B. Java.util.Set. C. Java.util.List. D. Java.util.StoredSet. E. Java.util.StoredMap. F. Java.util.Collection. Answer: D Question No 45 Which statement is true for the class java.util.HashSet? A. The elements in the collection are ordered. B. The collection is guaranteed to be immutable. C. The elements in the collection are guaranteed to be unique. D. The elements in the collection are accessed using a unique key. E. The elements in the collections are guaranteed to be synchronized. Answer: C Question No 46 Given: 1. public class IfTest ( 2. public static void main(string[]args) { 3. int x = 3; 4. int y = 1; 5. if (x = y) 6. system.out.printIn(“Not equal”); 7. else 8. system.out.printIn(“Equal”); 9. } 10. ) What is the result? A. The output is “Equal” B. The output in “Not Equal” C. An error at line 5 causes compilation to fall. D. The program executes but does not print a message. Answer: C Question No 47 Exhibit: 1. public class test ( 2. public static void main(string args[]) { 3. int 1= 0; 4. while (i) { 5. if (i==4) { 6. break; 7. ) 8. ++i; 9. ) 10. 11. ) 12. ) What is the value of i at line 10? A. 0 B. 3 C. 4 D. 5 E. The code will not compile. Answer: E Question No 48 Given: 3. int i= 1, j= 10 ; 4. do ( 5. if (i++> --j) continue; 6. ) while (i<5); After execution, what are the values for I and j? A. i = 6 and j= 5 B. i = 5 and j= 5 C. i = 6 and j= 4 D. i = 5 and j= 6 E. i = 6 and j= 6 Answer: D Question No 49 Given: 1. switch (i) { 2. default: 310-025 Leading the way in IT testing and certification tools, www.testking.com - 27 - 3. System.out.printIn(“Hello”); 4. ) What are the two acceptable types for the variable i? (Choose Two) A. Char B. Byte C. Float D. Double E. Object Answer: A, B Question No 50 Given: 1. public class foo { 2. public static void main (string[]args) 3. try {return;} 4. finally {system.out.printIn(“Finally”);} 5. } 6. ) What is the result? A. The program runs and prints nothing. B. The program runs and prints “Finally” C. The code compiles, but an exception is thrown at runtime. D. The code will not compile because the catch block is missing. Answer: B <淘宝热门商品:
 

 

皇冠舒友阁 顶级特效美容护肤 效果才是硬道理

 

7.20元  

:529M网络购物机构-江、浙、沪满百包快递


来源:程序员网

小小豆叮

深入浅出Java堆的管理--垃圾回收

引言   java的堆是一个运行时数据区,类的实例(对象)从中分配空间。java虚拟机(jvm)的堆中储存着正在运行的应用程序所建立的所有对象,这些对象通过new、newarray、anewarray和multianewarray等指令建立,但是它们不需要程序代码来显式地释放。一般来说,堆的是由垃圾回收 来负责的,尽管jvm规范并不要求特殊的垃圾回收技术,甚至根本就不需要垃圾回收,但是由于内存的有限性,jvm在实现的时候都有一个由垃圾回收所管理的堆。垃圾回收是一种动态存储管理技术,它自动地释放不再被程序引用的对象,按照特定的垃圾收集算法来实现资源自动回收的功能。   垃圾收集的意义   在c 中,对象所占的内存在程序结束运行之前一直被占用,在明确释放之前不能分配给其它对象;而在java中,当没有对象引用指向原先分配给某个对象的内存时,该内存便成为垃圾。jvm的一个系统级线程会自动释放该内存块。垃圾收集意味着程序不再需要的对象是无用信息,这些信息将被丢弃。当一个对象不再被引用的时候,内存回收它占领的空间,以便空间被后来的新对象使用。事实上,除了释放没用的对象,垃圾收集也可以清除内存记录碎片。由于创建对象和垃圾收集器释放丢弃对象所占的内存空间,内存会出现碎片。碎片是分配给对象的内存块之间的空闲内存洞。碎片整理将所占用的堆内存移到堆的一端,jvm将整理出的内存分配给新的对象。   垃圾收集能自动释放内存空间,减轻编程的负担。这使java 虚拟机具有一些优点。首先,它能使编程效率提高。在没有垃圾收集机制的时候,可能要花许多时间来解决一个难懂的存储器问题。在用java语言编程的时候,靠垃圾收集机制可大大缩短时间。其次是它保护程序的完整性, 垃圾收集是java语言安全性策略的一个重要部份。   垃圾收集的一个潜在的缺点是它的开销影响程序性能。java虚拟机必须追踪运行程序中有用的对象, 而且最终释放没用的对象。这一个过程需要花费处理器的时间。其次垃圾收集算法的不完备性,早先采用的某些垃圾收集算法就不能保证100%收集到所有的废弃内存。当然随着垃圾收集算法的不断改进以及软硬件运行效率的不断提升,这些问题都可以迎刃而解。   垃圾收集的算法分析   java语言规范没有明确地说明jvm使用哪种垃圾回收算法,但是任何一种垃圾收集算法一般要做2件基本的事情:(1)发现无用信息对象;(2)回收被无用对象占用的内存空间,使该空间可被程序再次使用。   大多数垃圾回收算法使用了根集(root set)这个概念;所谓根集就量正在执行的java程序可以访问的引用变量的集合(包括局部变量、参数、类变量),程序可以使用引用变量访问对象的属性和调用对象的方法。垃圾收集首选需要确定从根开始哪些是可达的和哪些是不可达的,从根集可达的对象都是活动对象,它们不能作为垃圾被回收,这也包括从根集间接可达的对象。而根集通过任意路径不可达的对象符合垃圾收集的条件,应该被回收。下面介绍几个常用的算法。   1、引用计数法(reference counting collector)   引用计数法是唯一没有使用根集的垃圾回收得法,该算法使用引用计数器来区分存活对象和不再使用的对象。一般来说,堆中的每个对象对应一个引用计数器。当每一次创建一个对象并赋给一个变量时,引用计数器置为1。当对象被赋给任意变量时,引用计数器每次加1。当对象出了作用域后(该对象丢弃不再使用),引用计数器减1,一旦引用计数器为0,对象就满足了垃圾收集的条件。   基于引用计数器的垃圾收集器运行较快,不会长时间中断程序执行,适宜地必须 实时运行的程序。但引用计数器增加了程序执行的开销,因为每次对象赋给新的变量 ,计数器加1,而每次现有对象出了作用域生,计数器减1。   2、tracing算法(tracing collector)   tracing算法是为了解决引用计数法的问题而提出,它使用了根集的概念。基于tracing算法的垃圾收集器从根集开始扫描,识别出哪些对象可达,哪些对象不可达,并用某种方式标记可达对象,例如对每个可达对象设置一个或多个位。在扫描识别过程中,基于tracing算法的垃圾收集也称为标记和清除(mark-and-sweep)垃圾收集器.   3、compacting算法(compacting collector)   为了解决堆碎片问题,基于tracing的垃圾回收吸收了compacting算法的思想,在清除的过程中,算法将所有的对象移到堆的一端,堆的另一端就变成了一个相邻的空闲内存区,收集器会对它移动的所有对象的所有引用进行更新,使得这些引用 在新的位置能识别原来 的对象。在基于compacting算法的收集器的实现中,一般增加句柄和句柄表。   4、coping算法(coping collector)   该算法的提出是为了克服句柄的开销和解决堆碎片的垃圾回收。它开始时把堆分成 一个对象 面和多个空闲面, 程序从对象面为对象分配空间,当对象满了,基于coping算法的垃圾 收集就从根集中扫描活动对象,并将每个 活动对象复制到空闲面(使得活动对象所占的内存之间没有空闲洞),这样空闲面变成了对象面,原来的对象面变成了空闲面,程序会在新的对象面中分配内存。   一种典型的基于coping算法的垃圾回收是stop-and-copy算法,它将堆分成对象面和空闲区域面,在对象面与空闲区域面的切换过程中,程序暂停执行。   5、generation算法(generational collector)   stop-and-copy垃圾收集器的一个缺陷是收集器必须复制所有的活动对象,这增加了程序等待时间,这是coping算法低效的原因。在程序设计中有这样的规律:多数对象存在的时间比较短,少数的存在时间比较长。因此,generation算法将堆分成两个或多个,每个子堆作为对象的一代(generation)。由于多数对象存在的时间比较短,随着程序丢弃不使用的对象,垃圾收集器将从最年轻的子堆中收集这些对象。在分代式的垃圾收集器运行后,上次运行存活下来的对象移到下一最高代的子堆中,由于老一代的子堆不会经常被回收,因而节省了时间。   6、adaptive算法(adaptive collector)   在特定的情况下,一些垃圾收集算法会优于其它算法。基于adaptive算法的垃圾收集器就是监控当前堆的使用情况,并将选择适当算法的垃圾收集器。   透视java垃圾回收   1、命令行参数透视垃圾收集器的运行   使用system.gc()可以不管jvm使用的是哪一种垃圾回收的算法,都可以请求java的垃圾回收。在命令行中有一个参数-verbosegc可以查看java使用的堆内存的情况,它的格式如下: java -verbosegc classfile   可以看个例子: class testgc {  public static void main(string[] args)  {   new testgc();   system.gc();   system.runfinalization();  } }   在这个例子中,一个新的对象被创建,由于它没有使用,所以该对象迅速地变为可达,程序编译后,执行命令: java -verbosegc testgc 后结果为: [full gc 168k->97k(1984k), 0.0253873 secs]   机器的环境为,windows 2000 jdk1.3.1,箭头前后的数据168k和97k分别表示垃圾收集gc前后所有存活对象使用的内存容量,说明有168k-97k=71k的对象容量被回收,括号内的数据1984k为堆内存的总容量,收集所需要的时间是0.0253873秒(这个时间在每次执行的时候会有所不同)。   2、finalize方法透视垃圾收集器的运行   在jvm垃圾收集器收集一个对象之前 ,一般要求程序调用适当的方法释放资源,但在没有明确释放资源的情况下,java提供了缺省机制来终止化该对象心释放资源,这个方法就是finalize()。它的原型为: protected void finalize() throws throwable   在finalize()方法返回之后,对象消失,垃圾收集开始执行。原型中的throws throwable表示它可以抛出任何类型的异常。   之所以要使用finalize(),是由于有时需要采取与java的普通方法不同的一种方法,通过分配内存来做一些具有c风格的事情。这主要可以通过固有方法来进行,它是从java里调用非java方法的一种方式。c和c 是目前唯一获得固有方法支持的语言。但由于它们能调用通过其他语言编写的子程序,所以能够有效地调用任何东西。在非java代码内部,也许能调用c的malloc()系列函数,用它分配存储空间。而且除非调用了free(),否则存储空间不会得到释放,从而造成内存漏洞的出现。当然,free()是一个c和c 函数,所以我们需要在finalize()内部的一个固有方法中调用它。也就是说我们不能过多地使用finalize(),它并不是进行普通清除工作的理想场所。   在普通的清除工作中,为清除一个对象,那个对象的用户必须在希望进行清除的地点调用一个清除方法。这与c 破坏器的概念稍有抵触。在c 中,所有对象都会破坏(清除)。或者换句话说,所有对象都应该破坏。若将c 对象创建成一个本地对象,比如在堆栈中创建(在java中是不可能的),那么清除或破坏工作就会在结束花括号所代表的、创建这个对象的作用域的末尾进行。若对象是用new创建的(类似于java),那么当程序员调用c 的delete命令时(java没有这个命令),就会调用相应的破坏器。若程序员忘记了,那么永远不会调用破坏器,我们最终得到的将是一个内存漏洞,另外还包括对象的其他部分永远不会得到清除。   相反,java不允许我们创建本地(局部)对象--无论如何都要使用new。但在java中,没有delete命令来释放对象,因为垃圾收集器会帮助我们自动释放存储空间。所以如果站在比较简化的立场,我们可以说正是由于存在垃圾收集机制,所以java没有破坏器。然而,随着以后学习的深入,就会知道垃圾收集器的存在并不能完全消除对破坏器的需要,或者说不能消除对破坏器代表的那种机制的需要(而且绝对不能直接调用finalize(),所以应尽量避免用它)。若希望执行除释放存储空间之外的其他某种形式的清除工作,仍然必须调用java中的一个方法。它等价于c 的破坏器,只是没后者方便。   下面这个例子向大家展示了垃圾收集所经历的过程,并对前面的陈述进行了总结。 class chair {  static boolean gcrun = false;  static boolean f = false;  static int created = 0;  static int finalized = 0;  int i;  chair() {   i = created;   if(created == 47)    system.out.println(created 47);  }  protected void finalize() {   if(!gcrun) {    gcrun = true;    system.out.println(beginning to finalize after created chairs have been created);   }   if(i == 47) {    system.out.println(finalizing chair #47, setting flag to stop chair creation);    f = true;   }   finalized ;   if(finalized >= created)    system.out.println(all finalized finalized);  } } public class garbage {  public static void main(string[] args) {   if(args.length == 0) {    system.err.println(usage: n java garbage beforen or:n java garbage after);    return;   }   while(!chair.f) {    new chair();    new string(to take up space);   }   system.out.println(after all chairs have been created:n total created = chair.created , total finalized = chair.finalized);   if(args[0].equals(before)) {     system.out.println(gc():);     system.gc();     system.out.println(runfinalization():);     system.runfinalization();   }   system.out.println(bye!);   if(args[0].equals(after))    system.runfinalizersonexit(true);  } }   上面这个程序创建了许多chair对象,而且在垃圾收集器开始运行后的某些时候,程序会停止创建chair。由于垃圾收集器可能在任何时间运行,所以我们不能准确知道它在何时启动。因此,程序用一个名为gcrun的标记来指出垃圾收集器是否已经开始运行。利用第二个标记f,chair可告诉main()它应停止对象的生成。这两个标记都是在finalize()内部设置的,它调用于垃圾收集期间。另两个static变量--created以及finalized--分别用于跟踪已创建的对象数量以及垃圾收集器已进行完收尾工作的对象数量。最后,每个chair都有它自己的(非static)int i,所以能跟踪了解它具体的编号是多少。编号为47的chair进行完收尾工作后,标记会设为true,最终结束chair对象的创建过程。(关于这个例子的更具体的分析和说明请参看《java编程思想》的第四章)   关于垃圾收集的几点补充   经过上述的说明,可以发现垃圾回收有以下的几个特点:   (1)垃圾收集发生的不可预知性:由于实现了不同的垃圾收集算法和采用了不同的收集机制,所以它有可能是定时发生,有可能是当出现系统空闲cpu资源时发生,也有可能是和原始的垃圾收集一样,等到内存消耗出现极限时发生,这与垃圾收集器的选择和具体的设置都有关系。   (2)垃圾收集的精确性:主要包括2 个方面:(a)垃圾收集器能够精确标记活着的对象;(b)垃圾收集器能够精确地定位对象之间的引用关系。前者是完全地回收所有废弃对象的前提,否则就可能造成内存泄漏。而后者则是实现归并和复制等算法的必要条件。所有不可达对象都能够可靠地得到回收,所有对象都能够重新分配,允许对象的复制和对象内存的缩并,这样就有效地防止内存的支离破碎。 (3)现在有许多种不同的垃圾收集器,每种有其算法且其表现各异,既有当垃圾收集开始时就停止应用程序的运行,又有当垃圾收集开始时也允许应用程序的线程运行,还有在同一时间垃圾收集多线程运行。   (4)垃圾收集的实现和具体的jvm 以及jvm的内存模型有非常紧密的关系。不同的jvm 可能采用不同的垃圾收集,而jvm 的内存模型决定着该jvm可以采用哪些类型垃圾收集。现在,hotspot 系列jvm中的内存系统都采用先进的面向对象的框架设计,这使得该系列jvm都可以采用最先进的垃圾收集。   (5)随着技术的发展,现代垃圾收集技术提供许多可选的垃圾收集器,而且在配置每种收集器的时候又可以设置不同的参数,这就使得根据不同的应用环境获得最优的应用性能成为可能。   针对以上特点,我们在使用的时候要注意:   (1)不要试图去假定垃圾收集发生的时间,这一切都是未知的。比如,方法中的一个临时对象在方法调用完毕后就变成了无用对象,这个时候它的内存就可以被释放。   (2)java中提供了一些和垃圾收集打交道的类,而且提供了一种强行执行垃圾收集的方法--调用system.gc(),但这同样是个不确定的方法。java 中并不保证每次调用该方法就一定能够启动垃圾收集,它只不过会向jvm发出这样一个申请,到底是否真正执行垃圾收集,一切都是个未知数。   (3)挑选适合自己的垃圾收集器。一般来说,如果系统没有特殊和苛刻的性能要求,可以采用jvm的缺省选项。否则可以考虑使用有针对性的垃圾收集器,比如增量收集器就比较适合实时性要求较高的系统之中。系统具有较高的配置,有比较多的闲置资源,可以考虑使用并行标记/清除收集器。   (4)关键的也是难把握的问题是内存泄漏。良好的编程习惯和严谨的编程态度永远是最重要的,不要让自己的一个小错误导致内存出现大漏洞。   (5)尽早释放无用对象的引用。大多数程序员在使用临时变量的时候,都是让引用变量在退出活动域(scope)后,自动设置为null,暗示垃圾收集器来收集该对象,还必须注意该引用的对象是否被监听,如果有,则要去掉监听器,然后再赋空值。   结束语   一般来说,java开发人员可以不重视jvm中堆内存的分配和垃圾处理收集,但是,充分理解java的这一特性可以让我们更有效地利用资源。同时要注意finalize()方法是java的缺省机制,有时为确保对象资源的明确释放,可以编写自己的finalize方法。 <淘宝热门商品:
 

12.00 元  

最新奇的负离子手表,减压手表

 

 

大芬村油画网上订购【画师联盟】纯手绘油画无框画装饰画四钻信誉


来源:程序员网

小小豆叮

SCJP考试题310-025(第一套)

这是SCJP的考试原题,是1999-2000期间的!提供给想考SCJP的参考! 我这还有其他的一些,如果全部打印可能100多页(双面)的样子!我将陆续的在这里粘贴出来!(如果可以的话),一共分为几套!这第一套只有19题,其他的几套有点多,300多题的都有,我归纳的,我同事说看完了它,考试就没问题,所以我就搜集了这么多,我也看的头大,所以发出来给大伙分享,敬请关注!! 1. Which statement are characteristics of the >> and >>> operators. A. >> performs a shift B. >> performs a rotate C. >> performs a signed and >>> performs an unsigned shift D. >> performs an unsigned and >>> performs a signed shift E. >> should be used on integrals and >>> should be used on floating point types C. 2. Given the following declaration String s = "Example"; Which are legal code? A. s >>> = 3; B. s[3] = "x"; C. int i = s.length(); D. String t = "For " + s; E. s = s + 10; CDE. 3. Given the following declaration String s = "hello"; Which are legal code? A. s >> = 2; B. char c = s[3]; C. s += "there"; D. int i = s.length(); E. s = s + 3; CDE. 4. Which statements are true about listeners? A. The return value from a listener is of boolean type. B. Most components allow multiple listeners to be added. C. A copy of the original event is passed into a listener method. D. If multiple listeners are added to a single component, they all must all be friends to each other. E. If the multiple listeners are added to a single component, the order [in which listeners are called is guaranteed]. BC. 5. What might cause the current thread to stop executing. A. An InterruptedException is thrown. B. The thread executes a wait() call. C. The thread constructs a new Thread. D. A thread of higher priority becomes ready. E. The thread executes a waitforID() call on a MediaTracker. ABDE. 6. Given the following incomplete method. 1. public void method(){ 2. 3. if (someTestFails()){ 4. 5. } 6. 7.} You want to make this method throw an IOException if, and only if, the method someTestFails() returns a value of true. Which changes achieve this? A. Add at line 2: IOException e; B. Add at line 4: throw e; C. Add at line 4: throw new IOException(); D. Add at line 6: throw new IOException(); E. Modify the method declaration to indicate that an object of [type] Exception might be thrown. CE. 7. Which modifier should be applied to a method for the lock of the object this to be obtained prior to executing any of the method body? A. final B. static C. abstract D. protected E. synchronized E. 8. Which are keywords in Java? A. NULL B. true C. sizeof D. implements E. instanceof DE. 9. Consider the following code: Integer s = new Integer(9); Integer t = new Integer(9); Long u = new Long(9); Which test would return true? A. (s==u) B. (s==t) C. (s.equals(t)) D. (s.equals(9)) E. (s.equals(new Integer(9)) CE. 10. Why would a responsible Java programmer want to use a nested class? A. To keep the code for a very specialized class in close association with the class it works with. B. To support a new user interface that generates custom events. C. To impress the boss with his/her knowledge of Java by using nested classes all over the place. AB. 11. You have the following code. Which numbers will cause "Test2" to be printed? switch(x){ case 1: System.out.println("Test1"); case 2: case 3: System.out.println("Test2"); break; } System.out.println("Test3"); } A. 0 B. 1 C. 2 D. 3 E. 4 BCD. 12. Which statement declares a variable a which is suitable for referring to an array of 50 string objects? A. char a[][]; B. String a[]; C. String []a; D. Object a[50]; E. String a[50]; F. Object a[]; BCF. 13. What should you use to position a Button within an application frame so that the width of the Button is affected by the Frame size but the height is not affected. A. FlowLayout B. GridLayout C. Center area of a BorderLayout D. East or West of a BorderLayout E. North or South of a BorderLayout E. 14. What might cause the current thread to stop executing? A. An InterruptedException is thrown B. The thread executes a sleep() call C. The thread constructs a new Thread D. A thread of higher priority becomes ready (runnable) E. The thread executes a read() call on an InputStream ABDE. Non-runnable states: * Suspended: caused by suspend(), waits for resume() * Sleeping: caused by sleep(), waits for timeout * Blocked: caused by various I/O calls or by failing to get a monitor's lock, waits for I/O or for the monitor's lock * Waiting: caused by wait(), waits for notify() or notifyAll() * Dead: Caused by stop() or returning from run(), no way out 15. Consider the following code: String s = null; Which code fragments cause an object of type NullPointerException to be thrown? A. if((s!=null) & (s.length()>0)) B. if((s!=null) &&(s.length()>0)) C. if((s==null) | (s.length()==0)) D. if((s==null) || (s.length()==0)) AC. 16. Given the following method body: { if (sometest()) { unsafe(); } else { safe(); } } The method "unsafe" might throw an IOException (which is not a subclass of RunTimeException). Which correctly completes the method of declaration when added at line one? A. public void methodName() throws Exception B. public void methodname() C. public void methodName() throw IOException D. public void methodName() throws IOException E. public IOException methodName() AD. 17. What would be the result of attempting to compile and run the following piece of code? public class Test { static int x; public static void main(String args[]){ System.out.println("Value is " + x); } } A. The output "Value is 0" is printed. B. An object of type NullPointerException is thrown. C. An "illegal array declaration syntax" compiler error occurs. D. A "possible reference before assignment" compiler error occurs. E. An object of type ArrayIndexOutOfBoundsException is thrown. A. 18. What would be the result of attempting to compile and run the following piece of code? public class Test { public int x; public static void main(String args[]){ System.out.println("Value is " + x); } } A. The output "Value is 0" is printed. B. Non-static variable x cannot be referenced from a static context.. C. An "illegal array declaration syntax" compiler error occurs. D. A "possible reference before assignment" compiler error occurs. E. An object of type ArrayIndexOutOfBoundsException is thrown. B. 19. What would be the result of attempting to compile and run the following piece of code? public class Test { public static void main(String args[]){ int x; System.out.println("Value is " + x); } } A. The output "Value is 0" is printed. B. An object of type NullPointerException is thrown. C. An "illegal array declaration syntax" compiler error occurs. D. A "possible reference before assignment" compiler error occurs. E. An object of type ArrayIndexOutOfBoundsException is thrown. D. <淘宝热门商品:
 

58.00 元  

忆草 中药去印平疤活肤霜 去痘印去

 

288.00 元 

【原装正品】韩国恋人1.6米大抱熊


来源:程序员网

小小豆叮

SCJP考试题310-025(第二套<1>)18/147

这都是考试原题,有心人可以收集收集,会让你收益匪浅!因为这一套较多所以我分<1><2><3><4>.....将他罗列出来!18/147意思是这里罗列147里的前18题!!以后的请继续关注!! 310-025 Leading the way in IT testing and certification tools, www.testking.com Question No: 1 Given: 1. public class test ( 2. public static void main (String args[]) { 3. int i = 0xFFFFFFF1; 4. int j = ~i; 5. 6. } 7. ) What is the decimal value of j at line 5? A. 0 B. 1 C. 14 D. –15 E. An error at line 3 causes compilation to fail. F. An error at line 4 causes compilation to fail. Answer: C Question No: 2 Given: Integer i = new Integer (42); Long 1 = new Long (42); Double d = new Double (42.0); Which two expressions evaluate to True? (Choose Two) A. (i ==1) B. (i == d) C. (d == 1) D. (i.equals (d)) E. (d.equals (i)) F. (i.equals (42)) Answer: D, E Question No: 3 Exhibit : 1. public class test ( 2. private static int j = 0; 3. 4. private static boolean methodB(int k) ( 5. j += k; 6. return true; 6. ) 7. 8. public static void methodA(int i) { 9. boolean b: 10. b = i < 10 | methodB (4); 11. b = i < 10 || methodB (8); 12. ) 13. 14. public static void main (String args[] } ( 15. methodA (0); 16. system.out.printIn(j); 17. ) 18. ) What is the result? A. The program prints “0” B. The program prints “4” C. The program prints “8” D. The program prints “12” E. The code does not complete. Answer: B Question No: 4 Given 1. Public class test ( 2. Public static void main (String args[]) ( 3. System.out.printIn (6 ^ 3); 4. ) 5. ) What is the output? Answer: 5 Question No: 5 Given: 1. public class Foo { 2. public static void main (String [] args) { 3. StringBuffer a = new StringBuffer (“A”); 4. StringBuffer b = new StringBuffer (“B”); 5. operate (a,b); 6. system.out.printIn{a + “,” +b}; 7. ) 8. static void operate (StringBuffer x, StringBuffer y) { 9. x.append {y}; 10. y = x; 11. ) 12. } What is the result? A. The code compiles and prints “A,B”. B. The code compiles and prints “A,A”. C. The code compiles and prints “B,B”. D. The code compiles and prints “AB,B”. E. The code compiles and prints “AB,AB”. F. The code does not compile because “+” cannot be overloaded for StringBuffer. Answer: D Question No: 6 Exhibit: 1. Public class test ( 2. Public static void stringReplace (String text) ( 3. Text = text.replace (‘j’ , ‘i’); 4. ) 5. 6. public static void bufferReplace (StringBuffer text) ( 7. text = text.append (“C”) 8. ) 9. 10. public static void main (String args[]} ( 11. String textString = new String (“java”); 12. StringBuffer text BufferString = new StringBuffer (“java”); 13. 14. stringReplace (textString); 15. BufferReplace (textBuffer); 16. 17. System.out.printIn (textString + textBuffer); 18. } 19. ) What is the output? Answer: JAVAJAVA Question No: 7 Exhibit: 1. public class test { 2. public static void add3 (Integer i) } 3. int val = i.intValue ( ); 4. val += 3; 5. i = new Integer (val); 6. } 7. 8. public static void main (String args [ ] ) { 9. Integer i = new Integer (0); 10. add3 (i); 11. system.out.printIn (i.intValue ( ) ); 12. } 13. ) What is the result? A. Compilation will fail. B. The program prints “0”. C. The program prints “3”. D. Compilation will succeed but an exception will be thrown at line 3. Answer: B Question No: 8 Given: 1. public class ConstOver { 2. public ConstOver (int x, int y, int z) { 3. } 4. } Which two overload the ConstOver constructor? (Choose Two) A. ConstOver ( ) { } B. Protected int ConstOver ( ) { } C. Private ConstOver (int z, int y, byte x) { } D. Public Object ConstOver (int x, int y, int z) { } E. Public void ConstOver (byte x, byte y, byte z) { } Answer: A, C Question No: 9 Given: 1. public class MethodOver { 2. public void setVar (int a, int b, float c) { 3. } 4. } Which two overload the setVar method? (Choose Two) A. Private void setVar (int a, float c, int b) { } B. Protected void setVar (int a, int b, float c) { } C. Public int setVar (int a, float c, int b) (return a;) D. Public int setVar (int a, int b, float c) (return a;) E. Protected float setVar (int a, int b, float c) (return c;) Answer: A, C Question No: 10 Given: 1. class BaseClass { 2. Private float x = 1.0f ; 3. protected float getVar ( ) ( return x;) 4. } 5. class Subclass extends BaseClass ( 6. private float x = 2.0f; 7. //insert code here 8. ) Which two are valid examples of method overriding? (Choose Two) A. Float getVar ( ) { return x;} B. Public float getVar ( ) { return x;} C. Float double getVar ( ) { return x;} D. Public float getVar ( ) { return x;} E. Public float getVar (float f ) { return f;} Answer: B, D Question No: 11 Which two demonstrate an “is a” relationship? (Choose Two) A. public interface Person { } public class Employee extends Person { } B. public interface Shape { } public class Employee extends Shape { } C. public interface Color { } public class Employee extends Color { } D. public class Species { } public class Animal (private Species species;) E. interface Component { } Class Container implements Component ( Private Component[ ] children; ) Answer: D, E Question No: 12 Which statement is true? A. An anonymous inner class may be declared as final. B. An anonymous inner class can be declared as private. C. An anonymous inner class can implement multiple interfaces. D. An anonymous inner class can access final variables in any enclosing scope. E. Construction of an instance of a static inner class requires an instance of the enclosing outer class. Answer: D Question No 13 Given: 1. package foo; 2. 3. public class Outer ( 4. public static class Inner ( 5. ) 6. ) Which statement is true? A. An instance of the Inner class can be constructed with “new Outer.Inner ()” B. An instance of the inner class cannot be constructed outside of package foo. C. An instance of the inner class can only be constructed from within the outer class. D. From within the package bar, an instance of the inner class can be constructed with “new inner()” Answer: A Question No 14 Exhibit: 1. public class enclosingone ( 2. public class insideone{} 3. ) 4. public class inertest( 5. public static void main (string[]args)( 6. enclosingone eo= new enclosingone (); 7. //insert code here 8. ) 9. ) Which statement at line 7 constructs an instance of the inner class? A. InsideOnew ei= eo.new InsideOn(); B. Eo.InsideOne ei = eo.new InsideOne(); C. InsideOne ei = EnclosingOne.new InsideOne(); D. EnclosingOne.InsideOne ei = eo.new InsideOne(); Answer: D Question No 15 Exhibit: 1. interface foo { 2. int k = 0; 3. ] 4. 5. public class test implements Foo ( 6. public static void main(String args[]) ( 7. int i; 8. Test test = new test (); 9. i= test.k; 10.i= Test.k; 11.i= Foo.k; 12.) 13.) 14. What is the result? A. Compilation succeeds. B. An error at line 2 causes compilation to fail. C. An error at line 9 causes compilation to fail. D. An error at line 10 causes compilation to fail. E. An error at line 11 causes compilation to fail. Answer: A Question No 16 Given: 1. //point X 2. public class foo ( 3. public static void main (String[]args) throws Exception { 4. printWriter out = new PrintWriter (new 5. java.io.outputStreamWriter (System.out), true; 6. out.printIn(“Hello”); 7. } 8. ) Which statement at PointX on line 1 allows this code to compile and run? A. Import java.io.PrintWriter; B. Include java.io.PrintWriter; C. Import java.io.OutputStreamWriter; D. Include java.io.OutputStreamWriter; E. No statement is needed. Answer: A Question No 17 Which two statements are reserved words in Java? (Choose Two) A. Run B. Import C. Default D. Implement Answer: B, C Question No 18 Which three are valid declarations of a float? (Choose Three) A. Float foo = -1; B. Float foo = 1.0; C. Float foo = 42e1; D. Float foo = 2.02f; E. Float foo = 3.03d; F. Float foo = 0x0123; Answer: A, D, F <淘宝热门商品:
 

 

【北京商盟】风の轩杂货铺 小美贵族瘦身

 

52.00 元  

【卡盟在线】

皇冠在线充|QQ黑钻腾讯黑钻地下城与勇士(DNF)黑钻3月


来源:程序员网

小小豆叮

Java数据对象(JDO)的前世今生

1 Java与数据库应用,JDBC   Java发明以来,在短短的几年之间,迅速占领了从桌面应用(J2SE)到服务器(J2EE),再到小型设备嵌入式系统(J2ME)的应用开发市场,其语言吸取了SmallTalk的一切皆对象的理念,摆脱了C++的历史累赘,简洁、自由的风格赢得了很多开发者的喜爱。从JDK1.1开始,Java成为实用的语言,而不是被人观望的新品秀;再经过JDK1.2的大量增强(尤其是Collection Framework),JDK1.3的虚拟机效率提升(HotSpot),JDK1.4的融合百家之长(Logging、RegExp、NewIO等),现在已经是成熟稳重,颇显大家风范。   在企业级市场上,大部分的应用建立在数据库基础上,数据是企业的生命,传统开发语言,包括面向过程的C、面向对象的C++、变种Pascal的Delphi(非常棒的语言,我用过四年),面向数据的PowerBuilder等等,先后在数据库开发的舞台上展现风姿。Java当然不会放过这些,于是,出现了JDBC。在JDBC的帮助下,Java也迅速渗入数据库开发的市场,尤其是面向企业服务器的应用开发。   今天要谈的JDO,与JDBC有非常密切的关系,尽管JDO并不是只面向JDBC的数据对象包装规范。下面先简单地介绍一下JDBC。   1.1 关系数据库之百家争鸣,ODBC   关系数据库的历史一言难尽,我只能从我的接触经历和所见所闻,简单地叙述一下。最早的时候,计算机还只在一些大型的研究机关露面,并不是普罗大众可以涉及的。苹果电脑将个人电脑引入民间,再随着IBM的PC标准开放,个人电脑逐步普及开来,加上微软的DOS操作系统,以及Borland的Turbo系列语言开发环境,老百姓发现原来电脑可以做这么多事!后来,出现了DBASE,一个简单的关系数据库系统,和SQL语言。后来,Borland看到了数据库的市场前景,推出了Paradox(也是当今Delphi和C++Builder中仍然使用的Paradox),一举占领了民用数据库的大部分江山,之后,Borland干脆收购了Dbase,后来又购买了InterBase,将数据库市场的领先优势一直保持到Windows3.0出现。这时候,微软在Windows1.0和2.0被人痛骂之后顽强地推出3.0,以及更稳定的3.1和Win32API,造就了个人电脑桌面操作系统的霸主地位,在Borland未警觉的情况下,购买了同样具有类Dbase数据库技术的Fox公司,并迅速将其易用化,形成了FoxBase,后来演变成FoxPro,逐渐超过了Borland,成为个人电脑数据库的大户。微软再接再励,为简单易用而低负荷要求的数据库应用开发了Access,赢得了广大开发人员的心。当然,同期的Oracle、Sybase、Informix等商用数据库凭专注于企业级数据库技术成为高端的几位领军人物。微软当然也想成为高端数据库供应商之一,于是自行开发一套面向企业级应用的数据库,不过很快项目夭折,微软不甘心,购买了Sybase的底层TDS技术,包装成了SQL Server,凭微软的高度易用性的特点,也占领了不少市场。   当市场上出现众多的数据库产品之后,Borland和微软都发现自己拥有的数据库产品挺多,市场也不小,不同的产品给用户带来不同的配置任务,不利于所有产品的推广,于是,两者纷纷开始制定数据库访问的规范,微软推出了ODBC,其面向开发人员的亲和性,逐步获得了认可,同时,Borland纠集了IBM和Novell也推出了IDAPI数据库接口规范,也就是今天BDE的核心,不过后来Novell和IBM先后退出,只剩Borland独力支撑。不过Borland是一个技术实力雄厚的公司,其技术一向领先于微软,BDE的性能比初期的ODBC不知道要好多少倍,后来微软偷师学艺,把连接池等技术加到ODBC中,在Delphi3.0及其BDE在市场上风光无限的时候,逐步赶了上来并有超过。直到今天,BDE仍是Borland的产品线上的数据库访问标准,而微软如果不是将ODBC和多数数据库的客户端内嵌进Windows的话,估计BDE仍是市场的赢家。不过,微软是玩弄市场的老手,通过对操作系统的垄断,其数据库产品和ODBC标准终究占据了多数开发市场。   1.2 从optional pack到JDK的标准API   Java开始涉及数据库应用后,Sun就极力制定Java的数据库规范,JDBC API就是类似ODBC一样,对数据库访问的底层协议进行最基本的包装,然后形成一套统一的数据访问接口,数据库连接、SQL语句句柄、结果集,都带有ODBC的影子。以方便配置为目的,Sun极力推荐完全瘦客户端的TYPE 4型JDBC驱动,这是一个不需要安装数据库客户端的驱动规范,是现在使用最多的。当然,为了保持与旧的数据库兼容,JDBC规范中包括了专用于连接ODBC的TYPE 1驱动和需要安装数据库客户端的TYPE 2驱动,以及可以由厂商在数据库服务端专门提供面向JDBC的服务的TYPE 3驱动。   JDBC最早出现时,还不属于标准JDK的一部分,而是作为一个额外包提供下载。后来,随着Java编写的数据库应用的的增多,和JDBC规范本身的逐渐成熟,JDBC终于成为JDK1.1的一部分。   JDBC目前最新的是3.0版本,还有正在讨论中的4.0版本。实际上,在开发中使用得最多的还是1.0中的API,2.0中主要增加了可双向滚动的结果集、更新批处理等提高可用性和性能的API,3.0主要增加了连接池、可更新的结果集等特性。4.0将在可管理性、连接池规范化等方面再做改进。   2 面向对象与数据库   现在的程序员,没有不知道面向对象的。作为接近真实客观世界的开发概念,面向对象使程序代码更易读、设计更合理。在普遍存在的数据库应用领域,开发人员对面向对象的追求从未停止过。从八十年代开始,就有很多公司和研究机构在进行着面向对象与数据库结合的研究。   2.1 SmallTalk、C与C++、Delphi-Object Pascal、Java   面向对象的语言最早有好几种雏形,IBM的SmallTalk是其中最为流行的,在SmallTalk中,一切都是对象,一切都是类,它将面向对象的概念发挥到了极致。面向对象的编程比起传统的面向过程的方式挺进了一大步,使人们认识到:原来软件可以这样写。不过,由于计算机基本结构与底层硬件体系和系统软件的限制,SmallTalk还不能在理想的性能前提下推广到普通的应用上,这一点暂时限制了SmallTalk的发展,接着,C语言的面向对象版C++出现了,由于使用C语言的人很多,C++很快成为面向对象编程的主流语言。不过,为了保证与C的兼容,C++保留了很多面向过程的痕迹,比如恶心的指针、全局变量等等。Pascal的改进版Object Pascal相对来说安全许多,后来Borland干脆将Object Pascal换了个名字,叫Delphi,从此开创了一片面向对象编程的新世界, Delphi的严谨语法和快速编译吸引了众多的应用开发者,加上Borland的完美的VCL组件体系,比起MFC来方便而容易,另外,Delphi完整的数据库组件,也将数据库开发变得简单而容易,Delphi再次成为成熟的面向对象开发语言。微软当然不会放过这些,通过将MFC内置到操作系统中,微软的VC++也抢回一些市场。这也是为什么Delphi开发的应用程序编译后会比VC、VB开发的程序大的原因。   1995年,Sun的一个开发小组本来为了小型嵌入式系统开发OAK语言,结果无心插柳柳成荫,发展出了Java语言,它是一个完全摆脱了传统语言的各种负担的面向对象的语言,当然,也保留了一些非面向对象的核心(原始类型)以保证速度。现在Java也为最流行的面向对象语言之一。当然,微软同样不会放过它,擅于模仿的微软立即弄出一个C#来与之竞争,并在C#中保留了一些变种的指针(指代)以吸引传统的C开发者。关于这些语言的各自特点,这里就不一一赘述了。   2.2 数据库与数据对象化   数据库是企业级应用不可缺少的,因此,在面向对象流行的时候,数据库厂商也在进行着数据对象化的研究。这些研究在上个世纪八十年代就初现端倪。   数据库的对象化一般有两个方向:一个是在主流的关系数据库的基础上加入对象化特征,使之提供面向对象的服务,但访问语言还是基于SQL;另一个方向就是彻底抛弃关系数据库,用全新的面向对象的概念来设计数据库,这就是对象数据库ODBMS。   2.2.1 关系数据库对象化、SQL99与JDBC3.0   随着许多关系数据库厂商开始提供对象化服务,各自的接口开始互不兼容,在经历一些麻烦之后,关系数据库厂商感觉到规范化的必要,因为当初关系数据库雄霸天下时SQL92标准起了很大作用,大家可以按照统一的编程方式来访问高性能的商用数据库。   关系数据库厂商集中起来,重新将对象化服务规范起来,形成了SQL99规范,将其中的对象结构等内容规范起来,开始一个崭新的面向对象的关系数据库(ORDBMS)的历程。   JDBC3.0就是在这种情况下出台的,它将对关系数据库中的对象服务的访问API规范起来,为Java平台提供了访问ORDBMS的标准方式。当然,JDBC3.0对传统的SQL操作也进行了很多功能增强。   Oracle是一个传统的关系数据库厂商,在对象化的道路上,Oracle当然采取追加对象化特征的道路,以侵入数据对象化的市场,保持Oracle在数据库领域的领导地位。如果说Oracle7.4使Oracle走向全盛的话,从Oracle8开始,Oracle就成为关系数据库加对象类型的先驱。在Oracle8中,我们可以定义一些数据结构(Record),将普通的类型包装在其中成为数据元素,然后可以在客户端按Record结构进行访问,初步提供了面向对象的数据库服务。   2.2.2 对象数据库   对象数据库就是采用全新的面向对象概念来设计数据库的全新数据库类型。在这方面,主要以一些大学研究机构进行设计和开发,有些也形成了产品,不过由于市场方面的原因(主要是关系数据库的容易上手和市场绝对领导地位)和ODBMS先天的一些弱点(比如查询引擎很难优化),使ODBMS没有象关系数据库那样流行起来。   不过对象数据库的对象化特点还是令人割舍不下,目前还是有一些很好的产品在市场上,从商用的到免费的都用。目前在ODBMS领域占据领导地位的是Versant、FastObjects和ObjectStore等几大厂商,并且,市场份额也在逐步扩展。免费的产品包括C++编写的Ozone、纯Java的db4o等等。还有一些研究机构开发一些底层的面向对象数据库引擎,但只提供一些底层的API,不提供管理方面的功能,以及一些算法提供开放式接口,让厂商去选择和实现。比如美国威斯康新大学计算机系数据库组的SHORE引擎,就是一个非常出色的面向对象数据库引擎,现在还在积极的更新中,一些其它研究机构和数据库厂商采用它完成了自己的特别的对象数据库,比如专用于地理信息的数据库、专用于宇宙空间数据研究的数据库等等。   目前对象数据库最大的障碍是缺乏统一的规范,各个数据库厂商有各自的访问接口。对象数据库比起关系数据库来,不只是基本的几种数据类型那么简单,它还涉及继承处理、多态等一大堆面向对象特征的实现,规范化道路当然困难重重。这也是对象数据库无法普及的一个重要原因。   也有一些机构提出了一些建议的规范,比如制定Corba标准的OMG小组的一个分组ODMG提出的ODMG规范,目前已经是3.0版本,其中的OQL对象查询语言相当具有吸引力。还有一些中立的机构提出了其它的一些标准化的对象访问API,也可算是面向对象数据库的规范之一。象前面提到的FastObjects和Ozone就是符合ODMG3.0规范的。 3 Java对象映射   话说回来,在一般的开发人员眼中,数据库就是指关系数据库,因此,很多应用还是采用简单的JDBC来访问数据库。在开发的过程中,大家逐渐感觉到JDBC的局限性,比如调用复杂、容易产生资源泄漏等等,与面向对象的Java语言有一段距离,因此,很多开发小组开始思考如何将应用中的数据进行对象化建模,然后再想办法与JDBC结合起来,这就是Java数据库开发中的层出不穷的对象包装技术。   3.1 对象包装技术   3.1.1 传统包装与演变   传统包装顾名思义,就是最初出现的包装方式,很多公司都经历过这一步,产生了很多风格各异的包装方法。当然,笔者也有过还算丰富的尝试过程。   举例来说,如果我们有一个用户类: public class User { public int userId; public String name; public java.util.Date birthday; }   我们可以将其当作一个简单的数据类,然后写一些工具方法来实现与JDBC的交互。这些方法,我们可以放到一个另外的工具类中,也可以放到User类中作为静态方法。这些方法包括简单的增、删、改、查(以Oracle为例): public class User { public int userId; public String name; public java.util.Date birthday; public static User addUser(String name, Date birthday) throws SQLException { Connection conn = …; //获取一个JDBC连接 PreparedStatement ps = conn.prepareStatement("…"); // 获取一个序列值来作为用户标识 ResultSet rs = ps.executeQuery(); rs.next(); User user = new User(); user.userId = rs.getInt(1); //读取序列值为新用户标识 user.name = name; user.birthday = birthday; ps = conn.prepareStatement("insert into …."); //插入用户数据记录的SQL ps.setInt(1,user.id); ps.setString(2,user.name); ps.setDate(3,user.birthday); ps.executeUpdate(); rs.close(); ps.close(); conn.close(); return user; } public static void deleteUser(int userId) throws SQLException { Connection conn = ….; //… } public static User getById(int userId) throws SQLException { //… } //… }   以上就是一个简单的数据包装的基本雏形,我们可以看到,这是一个非常简单的JDBC包装,一些代码可以模块化,以实现重用。另外,这段代码还有很大隐患,就是中途如果出现异常的话,就会使系统出现JDBC资源漏洞,因为JDBC分配的资源(conn,ps,rs等)是不能被Java虚拟机的垃圾回收机制回收的。因此,我们的addUser方法就需要改成下面的样子: public static User addUser(String name, Date birthday) throws SQLException { Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; User user = new User(); try { conn = …; //获取一个JDBC连接 ps = conn.prepareStatement("…"); // 获取一个序列值来作为用户标识 rs = ps.executeQuery(); rs.next(); user.userId = rs.getInt(1); //读取序列值为新用户标识 user.name = name; user.birthday = birthday; ps = conn.prepareStatement("insert into …."); //插入用户数据记录的SQL ps.setInt(1,user.id); ps.setString(2,user.name); ps.setDate(3,user.birthday); ps.executeUpdate(); } finally { //这里注意一定要按照创建的顺序关闭JDBC资源: if(rs != null) try { rs.close(); } catch(SQLException ex) { ex.printStackTrace(); } if(ps != null) try { ps.close(); } catch(SQLException ex) { ex.printStackTrace(); } if(conn != null) try { conn.close(); } catch(SQLException ex) { ex.printStackTrace(); } } return user; }   所有的数据库访问方法都必须进行这样的包装,当我们的数据类达到一定的数量后(比如十几个,几十个),这些方法占据了大量的代码,维护困难、出现BUG机会增多,并且不易排错,尤其是资源漏洞这种容易引起服务器稳定性问题的BUG。   为了保持数据类的纯洁,我们可以将JDBC操作方法集中到一个公共工具类中去完成,这样,这个工具类会非常庞大,但每个数据类会变得很简单,这种方式,可以称作是DataAccessObject模式,相当于EJB中的ValueObject,是脱离数据库细节的纯对象模型。   这些都是最基本的存储处理,在基本增删改查(这里的查指按关键字查找对象)的基础上,我们还需要进行复杂的匹配查询(SQL),这使得我们的存储处理代码进一步复杂化。简单地,我们可以写一个类似的方法: public static Collection findBy(String sql) throws SQLException { //… (这里获取JDBC连接) Collection col = new Vector(); ps = conn.prepareStatement(sql); rs = ps.executeQuery(); while(rs.next()) { User user = new User(); user.userId = rs.getInt(1); user.name = rs.getString(2); user.birthday = rs.getDate(3); col.add(user); } return col; //… (同前,这里是清理JDBC资源的代码) }   这就是一个查询接口的基本定义,查询采用的语言仍是SQL。   如果我们需要将参数从SQL串中独立出来以节省数据库的解析时间并规范化,我们还需要将查询条件作为参数传递到这个方法中去,方法的接口改为: public static Collection findBy(String sql, Object[] params) throws SQLException { //… ps = conn.prepareStatement(sql); for(int i = 0; i < params.length; i++) ps.setObject(i+1,params[i]); //… }   调用的时候sql参数中会包含一些"?"号,如: select ID,NAME,BIRTHDAY from USER where … = ? and … > ? and …   当然,也有一些开发团队喜欢将所有可能的查询都写死成一个个的专用查询方法,在其中完成对应的SQL操作,这一点类似于EJBQL,只不过是将EJBQL中容器实现的功能通过手工编码来实现。这样做使得查询受到限制,但可以提供更保险的接口。 还有一些开发人员看到每个类中写这样一些查询方法使得这个类的代码变得庞大,维护麻烦,便将所有的查询方法放到一个公共的工具类中去,只是在方法中再加入一个参数:Class cls来表示需要查询哪个对象,使得每个数据类变得紧凑一些。当然,这样的结果是那个公共类变得异常庞大,谁维护谁倒霉,可以说是牺牲一人,幸福团队。不过如果这个人心理素质不够好、压力承受能力不强的话,一些对数据类的改动可能会受到他的阻碍,这时候就是"一夫当关,万夫莫开"。   现在,我们已经实现了基本对象的包装,现在才能开始考虑更多的问题。首先,我们可能会从规范化的角度出发,给每一个属性加上读写访问器getter/setter,在前面的User类中,可能我们会将基本属性部分写为: public class User { private int userId; private String name; private Date birthday;   //以下是针对以上属性的getter/setter,一般可以用IDE工具生成 public int getUserId() { return userId; } public void setUserId(int value) { userId = value; } public String getName() { return name; } public void setName(String value) { name = value; } public Date getBirthday() { return birthday; } public void setBirthday(Date value) { birthday = value}; //… }   这样,一个比较规范的数据类包装就算完成了。   另外,我们知道,面向对象概念中,一个属性可以是另一个对象,也就是说,对象之间是存在着引用关系的,这种关系还分为一对一、一对多、多对多等几种情况。从一个既定对象出发,其某个属性可以是另一个对象,也可以是包含另一组对象的集合。那么,在我们的数据包装里面,当然最好也能方便地处理对象之间的关系。假定现在我们又有一个数据类Group: public class Group { public int grouId; public String groupName; public Set users; //set of User }   这里为了简单表明含义,暂不采用getter/setter。   而User对所属的Group有一个引用: public Group belongTo;   在这里,User.belongTo和Group.users就是一个一对多的关系。   在我们的数据类中,如何才能实现数据库的存取呢?就算是不考虑Group.users这个反向关系,光是User.belongTo就是一件头疼的事。如果我们在取出一个User对象时同时将其Group对象也取出来,可以保证不会在访问某个用户的组时得到一个null。不过这样有几个缺点:   1. 数据类的存取处理(JDBC)变得复杂,需要执行很多SQL读取才行,有时候只需要访问User的基本属性时浪费时间和资源;尤其是对集合型属性的预读取,更加可怕   2. 如果按这个逻辑,双向的关系处理变得危险,很容易陷入死循环,如果要避免,必须在类代码中加入一些特别的机制,也是很麻烦的事   3. 如果对象之间的关系是更复杂的情况下,比如三个、四个对象之间互相关联,那就是一场噩梦,对代码的编写和维护都异常艰难   于是,很多开发人员自然而然地退后一步,在User类中只保留一个groupId,并不保存Group对象,这样,可以将User.belongTo属性变成int类型,而另外写一个getter方法: public Group getBelongTo() { return Group.findById(belongTo); }   而在Group类中,干脆将users属性去掉,只保留一个方法: public Set getUsers() { return new HashSet(User.findBy("select … from USER where BELONG_TO=?",new Object[]{ new Integer(groupId) })); }   也许细心一点的读者已经看出来了,这里的几个方法都没有将SQLException捕捉,也没有在方法中声明,也就是说是有语法错误的,因为SQLException不是一个RuntimeException。不错,确实是这样,不过我们这里为了简单明了起见,省掉这些处理,以更直接清楚地表达意思。   这样,实际上,我们的对象关系包装已经名存实亡,在类的内部有很多用于访问所引用对象的复杂代码,这些已经违背了我们将对象关系保持的初衷。有些开发人员甚至不在类中保留访问关系对象的方法,而是在客户调用时再去访问另一对象类的读取方法,如: … User user = User.getById(…); //对user对象进行一些访问,如显示其姓名等等 Group group = Group.findById(user.belongTo); //对group对象进行一些访问,如显示组名等等 …   在这样的代码里,实际上我们已经从根本上退回了关系数据库的出发点,这与直接访问数据表有多大区别呢?只不过是在表上面套了一层貌似面向对象的皮而已。不幸的是,这种方式还存在于很多应用之中。   从前面提到的这些面向对象包装的细节问题,我们可以看到这种传统包装方式的一些主要的缺陷:   3.1.1.1 数据库命名与对象设计命名的一致性问题   很多时候,我们兴致勃勃地设计好一个类图,并且经过评审之后,开始对它进行数据库包装,这时候,发现有些属性名在具体的数据库中与该数据库的关键字冲突,不能用作表名或字段名,必须在数据表设计时采用另外的名称,或者很麻烦地加上引号来使用。于是,写数据库处理代码的人有意见了,他必须很清楚地记得一个属性在类中是什么属性名,在表中又是什么字段名,在编写的类逐渐增多后,尤其是一个类经过历次变动之后,或者经过很长时间又需要改动,并去处理这些JDBC代码时,代码维护人员简单要发疯了!   3.1.1.2 对象的查询仍局限于SQL   这一点也是这种简单的包装方法最不能摆脱关系数据库的地方。上面也已经说过,一些命名冲突带来了很多维护工作量,代码中必须还保留数据表的命名体系,而不是对象类的命名体系。这将使调用人员仍需要清楚记得两套命名体系,无论时间经过多久,或者开发人员是否有流动。   此外,对于普遍需要用到的连表查询,也给应用开发带来困难,这些地方仍不能突破SQL的限制。   3.1.1.3 SQL资源占用多   在处理对象集合访问或者处理集合类型属性时,往往我们只能在同一个Connection中处理一切事务,这就要求一次性地将集合中的对象全部读入,如果集合很大的话,容易造成数据库拥塞,使得性能大打折扣,适得其反。这方面的优化也是很多开发人员一直在努力改进的。   3.1.1.4 对象关系处理复杂   前面提过,对象之间的关系处理上,普通的包装技术是一种表面上的处理,在访问时调用者仍需要用大量的代码进行处理,并且,这还只是读取,在写入关系属性时会有更多的细节问题需要处理。   3.1.1.5 面向对象特色只能应用一小部分   面向对象的包装到前面所说的为止,都还只是很基本的处理,而面向对象的精华:继承和多态,在这里得不到任何帮助。我们放弃了很多合理的设计来迁就数据库的包装。   以上就是基本数据包装的主要缺陷,还有更多的小问题也需要额外的处理。   不过,有责任心的开发人员当然不会就此善罢甘休,他们冥思苦想,可能会用更好的方式来实现对象之间关系的处理,而且还会加入一些延迟访问的机制,将对象之间的引用在需要用的时候才去连接数据库取数据,另外,在类的继承上,他们也试图去在数据库包装上得到体现。   值得感谢的是,一些富有经验的团队在经历若干改进之后,毫不吝惜将他们的成果贡献出来,并将其独立化,成为可复用的组件。这也就是后来出现的对象包装产品,包括商用的和免费的。   3.1.2 产品化包装中间件   面向对象的包装产品化后,逐步推广开来,称作关系/对象映射:O/R Mapping。并且,在产品化的过程中,产品提供者在产品中逐渐提供了更多的功能。先是一些自动命名转换器得以应用,将客户代码中的类名、属性名在内部处理的时候自动地转换到对应的数据库结构命名空间上,这样,应用开发的时候不再关心具体的数据库结构,不再需要记忆不同地命名体系,只需要一心一意地根据类图来进行开发。在此之后,这些O/R Mapping产品的开发团队又向前迈了一大步:引入了词法分析器,提供面向对象的查询语言!很多对象关系的查询使应用开发变得非常方便,使O/R Mapping产品上了一个新的台阶。   3.1.2.1 TopLink   TopLink是一个非常早期的产品,最初面向C++,后来也实现了Java的映射。TopLink性能优异,功能强大,并且提供了独特的查询过滤器机制,以及对关系的处理和查询都非常有效,于是,TopLink逐渐从商用化O/R Mapping产品中胜出,成为市场上的最出色的映射产品。也正因为这一点,最大的关系数据库厂商Oracle将其收购,成为提供最强数据库和最强对象映射中间件的厂商。   3.1.2.2 Castor、Hibernate   TopLink虽然强大,但太强大的东西免不了得意忘形,TopLink开始将用户锁死到自己的产品上,查询方式是最突出的。它的查询体系含有很多别扭的概念(在我看来是如此),但为达到一般O/R产品不能达到的功能,开发者只能接受这些。慢慢地,也产生积怨,再加上其高昂的价格,让很多新老用户望而却步。于是,免费的产品开始崛起。   免费的O/R Mapping工具有很多种,这里只提其中最有影响力的两种:Castor和Hibernate。   Castor是Exolab组织开发的面向Java的包装工具,它最大的特色就是实现了大部分的ODMG OQL规范,在查询上,可以象完全使用一个对象数据库一样类图进行查询(后面会有介绍)。它的原理是通过Java反射API去实现属性的设置和读取。不过由于各种原因,Castor后来的版本更新越来越慢,最终停步在1.0之前,成为至今未出到1.0正式版的O/R Mapping产品。不管怎么样,它还是一个相当不错的产品。 Hibernate是一个现在很火热的O/R Mapping产品,目前已经出到2.0版,它功能一样强大,同样使用Java反射API进行对象的设置,但它的查询语言就是一套比较独特的体系,这一点有点类似TopLink,但Hibernate更具有亲和力,对关系的查询更方便,只不过比起Castor来,在方便性和规范性上还是稍逊一筹。就目前状况而言,Hibernate的用户量和技术支持要强一些。 3.2 面向对象的数据库查询   在对数据库进行面向对象研究的过程中,软件世界的开发人员和设计人员们发现:对数据库能够进行对象化的查询,才是对数据库进行彻底的面向对象化。这体现在我们使用一种全新的数据库查询语言,能够很简洁易懂地对数据库中的对象进行查询。一个典型的例子如下: 假设我们已经有前面提到的两个数据类:User和Group,它们之间有一对多的关系:User.belongTo和Group.users。在数据库中已经存在很多这两个类的实例,以及相互之间的关系。我们可以使用下面的对象式查询语言来查询符合条件的User对象: select * from User where User.belongTo.name=GROUP1      或者 select userId,name from User where User.belongTo.name=GROUP2   等等。从中我们可以看出,通过使用面向对象中的成员属性指定符".",可以让我们达到SQL中的连表的效果,实际上,第一个句查询的SQL等价版本是: select a.* from USER a, GROUP b where a.BELONG_TO = b.GROUP_ID and b.NAME = GROUP1   由此可见,对象式的查询语言,比起实现同样功能的SQL语言来说,简单了很多,意义也更明确,更符合使用者的思维习惯。在类图比较复杂、查询涉及的类又比较多的时候,这种新型的查询语言体现出绝对的优势。   3.2.1 ODMG,OQL,Java Binding   在面向对象式查询语言的研究过程中,开发人员们逐渐实现了相似的查询语言,然后互想取长补短,最终在ODMG组织(www.odmg.org)的统一下,形成了规范化的语言:ODMG OQL,这是一种完全面向对象的数据库查询语言,语法与前面提到的类似,不过考虑了更广泛的情况,语句更加简洁而严谨。   OQL并不是针对某种语言的,它可以被应用到很多种开发语言中,它不象SQL那样只是纯字符串式的查询语句,因为面向对象查询中还必须提供相关类的信息,所以OQL需要在编程语言中实现一些特定的API。   目前,ODMG的OQL已经被规范化地应用到SmallTalk、Java、C++这些面向对象的程序设计语言当中,在ODMG的规范中,这几个模块被称作SmallTalk Binding、Java Binding和C++ Binding。   不过,由于历史原因,ODMG并没有象想象中地那样得到广泛应用,现有的十几个面向对象数据库中,采用ODMG OQL规范的少之又少,目前也只有FastObjeccts、Ozone这些产品采纳了这个规范,而象Versant这样的大厂商还没有采取OQL来查询数据库,而是自己定义了自己的一套API,称作VQL(Versant Query Lanaguage)。   在JDO之前的O/R Mapping产品中,也有一些产品使用OQL(有时候是其子集),比如Castor、Apache的Jakarta小组开发的OJB等等。   3.2.2 第三方协议   软件世界是一个多姿多彩的世界,总有那么一些好事之士不断地冒出新奇的想法。还有一些开发面向对象数据库的组织制定了自己的一套对象式数据库查询语言,自己的规范。   不过这些规范相对来说,影响力小得多。比起ODMG来,可以说应用范围太小,更不用说与SQL这样广泛应用的标准进行比较了。   3.2.3 EJBQL   Sun为了使Java应用在企业级数据库应用中,不遗余力地推广J2EE,在2001年的时候,推出了EJB2.0规范,其中包含了富有特色的面向CMP方式的EntityBean的查询语言:EJBQL,功能类似于ODMG OQL,只不过只能在EJB发布时静态地存在于应用描述符中,不能在程序中动态地使用。这是EJBQL最大的弱点,也许EJB3.0规范会将其动态化,但到了那一天,世界多半已经不是现在的样子了。   3.2.4 JDO   JDO中有最近规定的一个对象式查询语言规范,称作JDOQL,比起OQL来,JDOQL将查询语言中的很多元素与Java语言紧密地结合在一起,有的人觉得麻烦,有些人觉得规范,评论各不相同。从笔者个人的角度来看,这样有利于没写过数据库应用、没用过SQL的新手很快地习惯JDOQL,但实际上,有多少人会在没写过SQL,没了解过关系数据库的情况下去用JDO写数据库应用呢?毕竟市场说明了一切。个人认为,JDO中对数据库对象的查询多少显得有些累赘,如果能更简化一点,那将更吸引使用传统SQL的开发人员。   4 JDO历程与主要产品   说起JDO,其来由还有一段特殊的背景。Java语言在JDK1.1达到比较实用的目的后,企业级数据库应用也正是软件开发市场中的重要组成部分,Sun看到这一点后,也希望通过Java这个强大的武器在数据库开发市场攻占市场份额。JDK1.2推出后,Sun同时推出了面向企业应用的EJB,对基于java的中间件服务器框架进行了规范化定义,这就是J2EE。不过在JDK1.2时,Java的速度还是不能与传统的C/C++和Delphi这样一些应用开发语言相比。为了防止业界对Java的激情因此而消退,Sun宣布将在JDK中加入强大的虚拟机技术HotSpot,其中包含更先进的垃圾收集算法和更优化的Java字节代码再编译技术(相当于JIT,Java即时编译技术)。HotSpot引起了Java关注者的极大兴趣,但Sun的HotSpot一拖再拖,最后包含在JDK1.3中出来时,性能也没有象预期的那样好,比起C++编译生成的代码来还是有一段距离。   这个时候,大家开始对Sun心存怀疑,而Sun深知这一点,于是将公众的注意力赶紧转移到EJB上,从EJB1.0到EJB1.1,再到EJB2.0,业界又开始关注J2EE中间件技术上来。很快,开发人同发现用EJB来编写数据库应用还是有很大的难度,虽然在分布式技术上EJB确实有很大的价值。在这个时候,Sun决定推出JDO技术作为轻量级的Java数据库访问规范,而这一点也受到很多传统O/R Mapping市场的欢迎。为了与传统O/R Mapping有所区别,Sun一开始就高姿态地将JDO定位成不只是面向关系数据库的Java规范,而是针对所有的存储技术,包括面向对象数据库和其它类型的存储体系(如文件),就象EJB EntityBean一样,虽然。就笔者的角度,这个做法使第一版的JDO抛弃了很多传统O/R Mapping提供的面向关系数据库的功能,可以算是一个失策。   4.1 规范提出、JSR   JDO最早是由Sun召集众多的O/R Mapping开发团队集中起来共同提出的,首先是通过会议确定了JDO需要包括的内容,然后正式提出一个Java规范请求(JSR-12),正式开始了JDO规范的制定。下面是主要的进展里程碑。 JSR #000012 approved in July 1999   1999-8组建的专家小组:包括Sun、Apple、BEA、IBM、Oracle、SAP、WebGain等 2000-5 完成公开评论草案 2000-6 在JavaOne上引入 2001-3 最终草案0.93 2001-5 最终草案0.96公布 2001-6 在JavaOne上启动 2001-11 最终草案0.98 2002-4 1.0版正式公布 2002-8 1.0.1修正版 2003-8 2.0规范启动 …   4.2 Oracle与JDO   作为JDO专家组的重要成员,同时作为最大的关系数据库厂商的Oracle地位显然非同一般。在JDO规范中,Oracle也可说是立下汗马功劳,很多API的形成,Oracle都提供了很重要的参考意见,最终的投票Oracle也是毫不犹豫。   可是,世间的事总是变化莫测的,就在JDO1.0快出台之时,Oracle收购了TopLink,这一点使Oracle的身份变得特殊而复杂。TopLink是一个商业产品,是以商业利益为目标的,而Oracle也是追求利益最大化的典型商家,这一点与JDO的开放精神背道而驰。因此,我们看到后期Oracle对JDO的不积极态度,甚至在前一阵的JavaOne大会上有人从Oracle的角度非正式地攻击JDO。   4.3 主要产品以及各自特点   在JDO规范制定的同时,出现了几个主要的JDO产品,有美国的基于对象数据库的FastObjects j1、法国的支持Versant对象数据库、文件数据库、主流RDBMS的LiDO、南非的JDOGenie、德国的JRelay等等,这些都是很不错的JDO产品。下面列举一下我对主要的几个产品的印象:   LiDO(法国LibeLis公司)   我对JDO的认识主要是通过LiDO这个产品,它在2002年3月的一份图文并茂的教程中简要解说了JDO的使用和优点。这个教程可以在这里下载:http://www.objectweb.org/conference/JDO.pdf。LiDO的特色是大而全,支持文件型数据库、RDBMS、ODBMS,甚至是XML数据库。不过配置较麻烦。最新版本是2.0RC。   KodoJDO(美国SolarMetrics公司)   Kodo是JDO的中流砥柱之一,在JDO1.0还未最后通过的时候,它就是一个比较成熟的产品了,其特点是注重性能和稳定性,目前最新版本是2.5.0,是客户最多的产品。   JDOGenie(南非HemSphere公司)   这是目前我最推荐的产品,最新版本是1.4.7,性能也不错,稳定性还有待验证,但它有一个最大的特点:集成性好,最易学,其公司的CTO David Tinker也是一个善解人意的年轻人,采纳了很多网友的意见对产品进行改进,主要是在配置上非常方便,有一个专门的图形界面工具,可以进行配置、数据库生成、对象查询等等很实用的功能。   JRelay(德国ObjectIndustries公司)   这也是一个出现得比较早的产品,也有一个GUI工具用于配置,曾几何时,这个工具还是相对很方便的,但一年多过去了,好象没什么进展,最新版本是2.0,我试过一段时间,后来就没有再跟进了。   FrontierSuite for JDO (美国ObjectFrontier)   这个产品与JRelay、Kodo一起,可算是早期的JDO三个主要产品,它支持正向开发和反向开发(Reverse Engineer)。它的特色是反向工程(从表结构生成数据类)比较方便,与UML的结合也很强,不过真正运行起来的时候,配置复杂。   TJDO(一群跨国界的有志之士)   这是一个在Sun提供的参考产品(Reference Implementation)的基础上加入一些扩展功能而形成的一个免费产品,目前最新版本是2.0beta3,不过进展也缓慢,这个版本已经出现好几个月了没有进一步的更新。   5 目前状况与未来展望   从2002年4月JDO1.0规范正式公布以来,各个产品层出不穷,从商业到免费的层次,都有不错的产品推出。象Kodo、Lido、JDOGenie等产品都已经比较成熟,可以考虑投入开发使用。在2002年8月,JDO又推出1.0.1修正版,修正了1.0版规范中的一些文字错误,以及轻微地改进了部分异常定义,不过改动都不大。从现在的情形来看,除了Kodo有一些大学的项目用到外,好象还没看到多少使用JDO作开发的应用。   JDO毕竟是一个新技术,从概念上到实际应用上对其掌握的用户还不多,而这些产品在配置、使用上的方便性易用性还有待大幅度改进,因此,真正用JDO来开发项目的用户还廖廖无几,至少我还不知道有哪些项目使用了JDO。我自己也尝试使用JDO来开发项目,但由于一些JDO1.0版本中还不够完善的一些硬伤(比如不支持关系数据库统计功能),使我对JDO仍处于观望阶段。   在八月中旬进行的JDO2.0规划会议中,来自各国的各个JDO产品厂商、JDO技术咨询公司、JDO研究机构的代表汇聚一堂,将各自收集到的用户对JDO2.0的需求总结起来,提出一个个的新的议题,并且确定了每个议题的JDO规范撰写负责人,比如高级fetchGroup特性由目前实现得最好的JDOGenie的CTO David Tinker负责,关于managed-relationship特性由Kodo的产品总监负责,用户要求最多的JDO对象与PersistenceManager的脱钩/重挂钩特性由Sun的Craig Russell亲自操刀,等等。   最具有吸引力的JDO2.0议题,笔者个人认为是专门为关系数据库设立的子规范JDO/R,这也是我一直以来最关心的,这将使目前JDBC的开发将可以被JDO完全取代,并且保证开发过程保持面向对象的特色。还有一些将一个类映射到多个表之类的特性也在规范化的列表上,这将有利于DBA在不影响应用开发的前提下根据需要更改数据表结构,实现更好的性能。类似的新特性还有很多,粗略地看,这些都规范化起来后,真不知道各个厂商还能做什么样的扩展特性,也许以后厂商之间拼的只能是技术支持服务和产品性能了,当然,最后还有价格的竞争。   说了这么多,我想大家关心的还是JDO2.0到底什么时候能出来,我们什么时候可以用上它,什么时候有中文版产品,价格到底如何。这些问题目前笔者还无法一一回答,只能根据笔者所掌握的信息初步解释一下。据前几天的JDO2.0启动大会上David Jordan的预期,JDO2.0正式版将在18个月后正式完成。那正式完成后厂商什么时候才能提供符合规范的产品呢?这个问题不用担心,因为规范在制定的过程中会不断地公布公众预览版(Public Review),这样,厂商可以先实现其中的功能,等规范正式完成后,也不会有太大的变化,厂商也不会需要太多时间来跟进最终规范。所以,我估计一年之后,我们就可以在JDO2.0上进行开发了。至于价格如何,1.0规范的产品初步印象是每个开发人员需要一个License,一个License大概2000美元。如果JDO2.0产品的价格还保持这么贵的话(至少对中国用户来说),我们也还有很多免费(如JPOX,TJDO)或半免费(如JCredo)产品可以选择。最后一个关于中文版的问题,有待于厂商对中国市场的考察,或者看看是否有国内的JDO产品了。不过,在JDO2.0规范制定的同时,我们可以先集众人之力将其普及,使广大的使用Java语言进行数据库开发的开发人员都来认识JDO,了解JDO,甚至将其用到项目开发之中。   也许,JDO的目标已经吸引了Java世界以外的人,微软发现了这一点,也立即计划在.NET体系中加入一个仿照JDO的中间件,具体是采用ObjectStore的产品,ObjectStore是一个同时做JDO和.NET-DO(姑且使用这个名称)的公司。   在这里,笔者可以大胆地预测,在未来的一两年内,JDO将在Java世界大放光彩!   5.1 一点花絮   在2003年6月举行的JavaOne大会上,JDO备受瞩目,很多开发者或开发组织对其产生了极大的兴趣,在各大网站媒体上也频频曝光,大多对其评价不错,当然,也有一些负面的评价。   不过,网站上的报道也不可尽信,比如服务器领域的权威网站TheServerSide.com上介绍JavaOne大会第二天关于JDO的一次会议的报道就有误导之嫌,从报道的内容来看,好象会议用来答疑与交流的的最后五分钟全被一个好事者占据,这个人拼命鼓吹Oracle的TopLink解决方案和一些易用性的改进,从而攻击JDO的市场前景。后来,我就这一信息与参加会议的JDO专家组的David Jordan交流时,他纠正了我的错误理解,实际情形是:那个好事者是一个积极的JDO拥护者,他花了超过五分钟时间向大家揭露Oracle的TopLink改进实际上也是抄袭JDO的概念而进行的一些API改动!不过有一点是相同的,这个好事者占据了大家的提问时间,使这次会议在意犹未尽中结束。 <淘宝热门商品:
 

¥:59.90 

天使之城外贸服装商行(童装/女装)【双皇冠网店 实体店同步】

双皇冠!韩国安卡米文静米色提花高领毛衣,专柜236元,140码

 

78.00 元 

印疤修复液 消除深浅痘印 改善凹凸疤痕


来源:程序员网

小小豆叮

用ant来执行hibernate所自带sechmaExport的工具

jianglibo 于 2004年 07月27日 发表 既然在eclipse环境下工作,最好所有相关的工作都能在它里面完成。hibernate自带了一个工具schemaExport,可以让你从map文件产生数据库的ddl。 在eclipse project中新建一个目录,schemae,然后新建两个文件。schemae.xml,schema.properties。 schema.properties的内容: neededClassPath=c:/hibernate-2.1.4/hibernate-2.1/hibernate2.jar;c:/hibernate-2.1.4/hibernate-2.1/lib/dom4j-1.4.jar;c:/hibernate-2.1.4/hibernate-2.1/lib/commons-collections-2.1.jar;c:/hibernate-2.1.4/hibernate-2.1/lib/commons-logging-1.0.3.jar;c:/hsqldb_1_7_1/hsqldb/lib/hsqldb.jar;D:/eclipse-SDK-2.1.2-win32/eclipse/workspace/fhjsj/bin/;D:/eclipse-SDK-2.1.2-win32/eclipse/workspace/fhjsj/fhjsj/WEB-INF/classes/ schema.xml的内容: <!-- Copyright (c) 2002 by ObjectLearn. All Rights Reserved. --&rt; <project name="schemaExport" default="schemaexport" basedir="."&rt; <property file="schemae.properties"/&rt; <target name="schemaexport"&rt; <taskdef name="schemaexport" classname="net.sf.hibernate.tool.hbm2ddl.SchemaExportTask" classpath="${neededClassPath}"/&rt; <schemaexport quiet="no" text="true" drop="no" delimiter=";" output="workspace/fhjsj/schemae/schema-export.sql"&rt; <fileset dir="../fhjsj/WEB-INF/classes/"&rt; <include name="**/*.hbm.xml"/&rt; </fileset&rt; </schemaexport&rt; </target&rt; </project&rt; 其它的hibernate.properties和mapping 文件根据web程序的规范放在WEB-INF的classes里面。最后产生的ddl文件放在schemae目录下面。 <淘宝热门商品:
 

 

自然美人 红酒面膜及口碑护理产品

 

网络游戏装备/游戏币/帐号/代练 

无悔于心2006


来源:程序员网

小小豆叮

Java打印程序设计全攻略

前言   在我们的实际工作中,经常需要实现打印功能。但由于历史原因,Java提供的打印功能一直都比较弱。实际上最初的jdk根本不支持打印,直到jdk1.1才引入了很轻量的打印支持。所以,在以前用Java/Applet/JSP/Servlet设计的程序中,较复杂的打印都是通过调用ActiveX/OCX控件或者VB/VC程序来实现的,非常麻烦。实际上,SUN公司也一直致力于Java打印功能的完善,而Java2平台则终于有了一个健壮的打印模式的开端,该打印模式与Java2D图形包充分结合成一体。更令人鼓舞的是,新发布的jdk1.4则提供了一套完整的"Java 打印服务 API" (Java Print Service API),它对已有的打印功能是积极的补充。利用它,我们可以实现大部分实际应用需求,包括打印文字、图形、文件及打印预览等等。本文将通过一个具体的程序实例来说明如何设计Java打印程序以实现这些功能,并对不同版本的实现方法进行分析比较,希望大家能从中获取一些有益的提示。   Java中的打印   1、Java的打印API   Java的打印API主要存在于java.awt.print包中。而jdk1.4新增的类则主要存在于javax.print包及其相应的子包javax.print.event和javax.print.attribute中。其中javax.print包中主要包含打印服务的相关类,而javax.print.event则包含打印事件的相关定义,javax.print.attribute则包括打印服务的可用属性列表等。   2、如何实现打印   要产生一个打印,至少需要考虑两条:   需要一个打印服务对象。这可通过三种方式实现:在jdk1.4之前的版本,必须要实现java.awt.print.Printable接口或通过Toolkit.getDefaultToolkit().getPrintJob来获取打印服务对象;在jdk1.4中则可以通过javax.print.PrintSerivceLookup来查找定位一个打印服务对象。   需要开始一个打印工作。这也有几种实现方法:在jdk1.4之前可以通过java.awt.print.PrintJob(jdk1.1提供的,现在已经很少用了)调用print或printAll方法开始打印工作;也可以通过java.awt.print.PrinterJob的printDialog显示打印对话框,然后通过print方法开始打印;在jdk1.4中则可以通过javax.print.ServiceUI的printDialog显示打印对话框,然后调用print方法开始一个打印工作。   3、打印机对话框   3.1 Printable的打印对话框   开始打印工作之前,可以通过PrinterJob.printDialog来显示一个打印对话框。它给用户一个机会以选择应该打印的页码范围,并可供用户改变打印设置。它是一个本地对话框。   事实上,当从一个Printable对象进行一个打印工作时,打印对象并不知道需要打印多少页。它只是不停地调用print方法。只要print方法返回Printable.PAGE_EXISTS值,打印工作就不停地产生打印页,直到print方法返回Printable.NO_SUCH_PAGE时,打印工作才停止。   由于打印工作只有在打印完成后才进行准确的页数计算,所以在对话框上的页码范围是尚未初始化的[1,9999]。我们可以通过构建一个java.awt.print.Book对象传递给打印对象;也可以通过指定的格式计算需要打印的页数并传递给打印对象,使其准确地知道要打印多少页。   3.2 ServiceUI的打印对话框     与Printable的对话框不同的是,在jdk1.4提供ServiceUI的打印机对话框的缺省行为已经用新的 API 更改了:缺省情况下对话框不显示。我们必须使用ServiceUI类调用printDialog方法创建如下所示的打印对话框。 Java打印程序设计实例   1、打印文本   1.1 应用场景   假设我们需要打印一个窗体的某个文本编辑域(可能只有几行,也可能包含多页)的内容,并且每页最多打印54行,如何实现呢?   1.2 解决方法   基本思路如下:首先我们需要实现Printable接口,然后按照每页最多54行的格式计算共需要打印多少页,当打印文本的按钮被点击时,执行相应的打印动作。打印文本的具体操作可通过Graphics2D的drawString方法来实现。   1) 实现Printable接口 /*Graphic指明打印的图形环境;PageFormat指明打印页格式(页面大小以点为计量单位,1点为1英寸的1/72,1英寸为25.4毫米。A4纸大致为595×842点);page指明页号*/ public int print(Graphics g, PageFormat pf, int page) throws PrinterException {  Graphics2D g2 = (Graphics2D)g;  g2.setPaint(Color.black); //设置打印颜色为黑色  if (page >= PAGES) //当打印页号大于需要打印的总页数时,打印工作结束   return Printable.NO_SUCH_PAGE;  g2.translate(pf.getImageableX(), pf.getImageableY());//转换坐标,确定打印边界  drawCurrentPageText(g2, pf, page); //打印当前页文本  return Printable.PAGE_EXISTS; //存在打印页时,继续打印工作 } /*打印指定页号的具体文本内容*/ private void drawCurrentPageText(Graphics2D g2, PageFormat pf, int page) {  String s = getDrawText(printStr)[page]; //获取当前页的待打印文本内容  //获取默认字体及相应的尺寸  FontRenderContext context = g2.getFontRenderContext();  Font f = area.getFont();  String drawText;  float ascent = 16; //给定字符点阵  int k, i = f.getSize(), lines = 0;  while(s.length() > 0 && lines < 54) //每页限定在54行以内  {   k = s.indexOf(\ ); //获取每一个回车符的位置   if (k != -1) //存在回车符   {    lines += 1; //计算行数    drawText = s.substring(0, k); //获取每一行文本    g2.drawString(drawText, 0, ascent); //具体打印每一行文本,同时走纸移位    if (s.substring(k + 1).length() > 0) {     s = s.substring(k + 1); //截取尚未打印的文本     ascent += i;    }   }   else //不存在回车符   {    lines += 1; //计算行数    drawText = s; //获取每一行文本    g2.drawString(drawText, 0, ascent); //具体打印每一行文本,同时走纸移位    s = ""; //文本已结束   }  } } /*将打印目标文本按页存放为字符串数组*/ public String[] getDrawText(String s) {  String[] drawText = new String[PAGES]; //根据页数初始化数组  for (int i = 0; i < PAGES; i++)   drawText[i] = ""; //数组元素初始化为空字符串  int k, suffix = 0, lines = 0;  while (s.length() > 0) {   if (lines < 54) //不够一页时   {    k = s.indexOf(\ );    if (k != -1) //存在回车符    {     lines += 1; //行数累加     //计算该页的具体文本内容,存放到相应下标的数组元素     drawText[suffix] = drawText[suffix] + s.substring(0, k + 1);     if (s.substring(k + 1).length() > 0)      s = s.substring(k + 1);    }    else    {     lines += 1; //行数累加     //将文本内容存放到相应的数组元素     drawText[suffix] = drawText[suffix] + s;     s = "";    }   }   else //已满一页时   {    lines = 0; //行数统计清零    suffix++; //数组下标加1   }  }  return drawText; }   2) 计算需要打印的总页数 public int getPagesCount(String curStr) {  int page = 0;  int position, count = 0;  String str = curStr;  while(str.length() > 0) //文本尚未计算完毕  {   position = str.indexOf(\ ); //计算回车符的位置   count += 1; //统计行数   if (position != -1)    str = str.substring(position + 1); //截取尚未计算的文本   else    str = ""; //文本已计算完毕  }  if (count > 0)   page = count / 54 + 1; //以总行数除以54获取总页数  return page; //返回需打印的总页数 }   以jdk1.4以前的版本实现打印动作按钮监听,并完成具体的打印操作 private void printTextAction() {  printStr = area.getText().trim(); //获取需要打印的目标文本  if (printStr != null && printStr.length() > 0) //当打印内容不为空时  {   PAGES = getPagesCount(printStr); //获取打印总页数   PrinterJob myPrtJob = PrinterJob.getPrinterJob(); //获取默认打印作业   PageFormat pageFormat = myPrtJob.defaultPage(); //获取默认打印页面格式   myPrtJob.setPrintable(this, pageFormat); //设置打印工作   if (myPrtJob.printDialog()) //显示打印对话框   {    try {     myPrtJob.print(); //进行每一页的具体打印操作    }    catch(PrinterException pe) {     pe.printStackTrace();    }   }  }  else { //如果打印内容为空时,提示用户打印将取消   JOptionPane.showConfirmDialog(null, "Sorry, Printer Job is Empty, Print Cancelled!", "Empty", JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE);  } }   以jdk1.4新版本提供的API实现打印动作按钮监听,并完成具体的打印操作 private void printText2Action() {  printFlag = 0; //打印标志清零  printStr = area.getText().trim();//获取需要打印的目标文本  if (printStr != null && printStr.length() > 0) //当打印内容不为空时  {   PAGES = getPagesCount(printStr); //获取打印总页数   //指定打印输出格式   DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PRINTABLE;   //定位默认的打印服务   PrintService printService = PrintServiceLookup.lookupDefaultPrintService();   //创建打印作业   DocPrintJob job = printService.createPrintJob();   //设置打印属性   PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();   DocAttributeSet das = new HashDocAttributeSet();   //指定打印内容   Doc doc = new SimpleDoc(this, flavor, das);   //不显示打印对话框,直接进行打印工作   try {    job.print(doc, pras); //进行每一页的具体打印操作   }   catch(PrintException pe) {    pe.printStackTrace();   }  }  else { //如果打印内容为空时,提示用户打印将取消   JOptionPane.showConfirmDialog(null, "Sorry, Printer Job is Empty, Print Cancelled!", "Empty", JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE);  } } 打印预览   1、应用场景   大多少商业应用都需要提供打印预览机制,它可以让我们在屏幕上看到页面,这样就不会因为不喜欢的打印结果而浪费纸张。假设我们在打印上一节所说的文本之前,需要先进行打印预览。那么该怎么实现呢? 界面实现图示如下:(Next预览下一页,Preview预览前一页,Close则关闭预览)   2、解决方法   基本思路:虽然Java2平台的打印API并不提供标准的打印预览对话框,但是自己来进行设计也并不复杂。正常情况下,print方法将页面环境绘制到一个打印机图形环境上,从而实现打印。而事实上,print方法并不能真正产生打印页面,它只是将待打印内容绘制到图形环境上。所以,我们可以忽略掉屏幕图形环境,经过适当的缩放比例,使整个打印页容纳在一个屏幕矩形里,从而实现精确的打印预览。   在打印预览的设计实现中,主要需要解决两个问题。   第一,如何将打印内容按合适的比例绘制到屏幕;   第二,如何实现前后翻页。   下面我给出这两个问题的具体实现方法,完整的实现请参看附件中的PrintPreviewDialog.java文件。 /*将待打印内容按比例绘制到屏幕*/ public void paintComponent(Graphics g) {  super.paintComponent(g);  Graphics2D g2 = (Graphics2D)g;  PageFormat pf = PrinterJob.getPrinterJob().defaultPage(); //获取页面格式  double xoff; //在屏幕上页面初始位置的水平偏移  double yoff; //在屏幕上页面初始位置的垂直偏移  double scale; //在屏幕上适合页面的比例  double px = pf.getWidth(); //页面宽度  double py = pf.getHeight(); //页面高度  double sx = getWidth() - 1;  double sy = getHeight() - 1;  if (px/py < sx/sy) {   scale = sy / py; //计算比例   xoff = 0.5 * (sx - scale * px); //水平偏移量   yoff = 0;  }  else {   scale = sx / px; //计算比例   xoff = 0;   yoff = 0.5 * (sy - scale * py); //垂直偏移量  }  g2.translate((float)xoff, (float)yoff); //转换坐标  g2.scale((float)scale, (float)scale);  Rectangle2D page = new Rectangle2D.Double(0, 0, px, py); //绘制页面矩形  g2.setPaint(Color.white); //设置页面背景为白色  g2.fill(page);  g2.setPaint(Color.black);//设置页面文字为黑色  g2.draw(page);  try {   preview.print(g2, pf, currentPage); //显示指定的预览页面  }  catch(PrinterException pe) {   g2.draw(new Line2D.Double(0, 0, px, py));   g2.draw(new Line2D.Double(0, px, 0, py));  } } /*预览指定的页面*/ public void viewPage(int pos) {  int newPage = currentPage + pos; //指定页面在实际的范围内  if (0 <= newPage && newPage < preview.getPagesCount(printStr)) {   currentPage = newPage; //将指定页面赋值为当前页   repaint();  } }   这样,在按下"Next"按钮时,只需要调用canvas.viewPage(1);而在按下"Preview"按钮时,只需要调用canvas.viewPage(-1)即可实现预览的前后翻页。 打印图形   1、应用场景   在实际应用中,我们还需要打印图形。譬如,我们有时需要将一个Java Applet的完整界面或一个应用程序窗体及其所包含的全部组件都打印出来,又应该如何实现呢?   2、解决方法   基本思路如下:在Java的Component类及其派生类中都提供了print和printAll方法,只要设置好属性就可以直接调用这两个方法,从而实现对组件及图形的打印。 /*打印指定的窗体及其包含的组件*/ private void printFrameAction() {  Toolkit kit = Toolkit.getDefaultToolkit(); //获取工具箱  Properties props = new Properties();  props.put("awt.print.printer", "durango"); //设置打印属性  props.put("awt.print.numCopies", "2");  if (kit != null) {   //获取工具箱自带的打印对象   PrintJob printJob = kit.getPrintJob(this, "Print Frame", props);   if (printJob != null) {    Graphics pg = printJob.getGraphics(); //获取打印对象的图形环境    if (pg != null) {     try {      this.printAll(pg); //打印该窗体及其所有的组件     }     finally {      pg.dispose(); //注销图形环境     }    }    printJob.end(); //结束打印作业   }  } }   打印文件   1、应用场景   在很多实际应用情况下,我们可能都需要打印用户指定的某一个文件。该文件可能是图形文件,如GIF、JPEG等等;也可能是文本文件,如TXT、Java文件等等;还可能是复杂的PDF、DOC文件等等。那么对于这样的打印需求,我们又应该如何实现呢?   2、解决方法   基本思路:在jdk1.4以前的版本,要实现这样的打印功能将非常麻烦和复杂,甚至是难以想象的。但幸运的是,jdk1.4的打印服务API提供了一整套的打印文件流的类和方法。利用它们,我们可以非常方便快捷地实现各式各样不同类型文件的打印功能。下面给出一个通用的处理方法。 /*打印指定的文件*/ private void printFileAction() {  //构造一个文件选择器,默认为当前目录  JFileChooser fileChooser = new JFileChooser(SystemProperties.USER_DIR);  int state = fileChooser.showOpenDialog(this); //弹出文件选择对话框  if (state == fileChooser.APPROVE_OPTION) //如果用户选定了文件  {   File file = fileChooser.getSelectedFile(); //获取选择的文件   //构建打印请求属性集   PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();   //设置打印格式,因为未确定文件类型,这里选择AUTOSENSE   DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;   //查找所有的可用打印服务   PrintService printService[] = PrintServiceLookup.lookupPrintServices(flavor, pras);   //定位默认的打印服务   PrintService defaultService = PrintServiceLookup.lookupDefaultPrintService();   //显示打印对话框   PrintService service = ServiceUI.printDialog(null, 200, 200, printService, defaultService, flavor, pras);   if (service != null) {    try {     DocPrintJob job = service.createPrintJob(); //创建打印作业     FileInputStream fis = new FileInputStream(file); //构造待打印的文件流     DocAttributeSet das = new HashDocAttributeSet();     Doc doc = new SimpleDoc(fis, flavor, das); //建立打印文件格式     job.print(doc, pras); //进行文件的打印    }    catch(Exception e) {     e.printStackTrace();    }   }  } }   在上面的示例中,因尚未确定文件的类型,所以将指定文件的打印格式定义为DocFlavor.INPUT_STREAM.AUTOSENSE。事实上,如果在进行打印之前,就已确定地知道文件的格式,如为GIF,就应定义为DocFlavor.INPUT_STREAM.GIF ;如为PDF,就应该定义为DocFlavor.INPUT_STREAM.PDF;如为纯ASCII文件,就可以定义为 DocFlavor.INPUT_STREAM.TEXT_HTML_US_ASCII。等等。 jdk1.4的javax.print.DocFlavor提供了极为丰富的文件流类型,你可以根据具体的应用需求进行合适的选择。具体的API参考文档可见本文的参考资料3。   结束语   以上是本人在两年多J2EE应用开发中,总结的关于用Java进行打印程序设计的一些经验,希望能给大家一些启示和裨益。尽管目前用Java来实现打印功能与用Microsoft的MFC API相比确实有更多的麻烦。但jdk1.4的推出,对Java以前较弱的打印功能是一个极好的补充。相信大家如果能够很好地理解前文所述的打印程序设计实例,并加以应用和拓展,应该可以解决目前大部分应用的实际编程问题。而随着Java的进一步发展和完善,必将更好地充实其基础类库及打印API,相信用Java实现高级打印功能也将越来越不成为我们这些Java痴迷者头痛的问题。 <淘宝热门商品:
 

 

【珠三角商盟】【因为专注→所以专业→天天数码世界】

 

136.00 元  

达人公社 专柜正品 纽巴伦 newbalance 匡威 crocs折扣 店

正品 日版纽巴伦new balance 型号:TK02 深灰黑


来源:程序员网

小小豆叮