<rt id="bn8ez"></rt>
<label id="bn8ez"></label>

  • <span id="bn8ez"></span>

    <label id="bn8ez"><meter id="bn8ez"></meter></label>

    tbwshc

    #

    Java調用SQL Server的存儲過程詳解

    1使用不帶參數的存儲過程

      1

      {call procedure-name}

      作為實例,在 SQL Server 2005 AdventureWorks 示例數據庫中創建以下存儲過程:

      CREATE PROCEDURE GetContactFormalNames

      AS BEGIN SELECT TOP 10 Title + ' ' + FirstName + ' ' + LastName AS FormalName

      FROM Person.Contact END

      此存儲過程返回單個結果集,其中包含一列數據(由 Person.Contact 表中前十個聯系人的稱呼、名稱和姓氏組成)。

      在下面的實例中,將向此函數傳遞 AdventureWorks 示例tb數據庫的打開連接,然后使用 executeQuery 方法調用 GetContactFormalNames 存儲過程。

      public static void executeSprocNoParams(Connection con)

      …{

      try …{

      Statement stmt = con.createStatement();

      ResultSet rs = stmt.executeQuery("{call dbo.GetContactFormalNames}");

      while (rs.next())

      …{

      System.out.println(rs.getString("FormalName"));

      }

      rs.close();

      stmt.close();

      }

      catch (Exception e)

      …{

      e.printStackTrace();

      }

      }

      2使用帶有輸入參數的存儲過程

      使用 JDBC 驅動程序調用帶參數的存儲過程時,必須結合 SQLServerConnection 類的 prepareCall 方法使用 call SQL 轉義序列。帶有 IN 參數的 call 轉義序列的語法如下所示:

      {call procedure-name[([parameter][,[parameter]]…)]}http://jie.baijiale.94ibc.com

      構造 call 轉義序列時,請使用 ?(問號)字符來指定 IN 參數。此字符充當要傳遞給該存儲過程的參數值的占位符。可以使用 SQLServerPreparedStatement 類的 setter 方法之一為參數指定值??墒褂玫?setter 方法由 IN 參數的數據類型決定。

      向 setter 方法傳遞值時,不僅需要指定要在參數中使用的實際值,還必須指定參數在存儲過程中的序數位置。例如,如果存儲過程包含單個 IN 參數,則其序數值為 1.如果存儲過程包含兩個參數,則第一個序數值為 1,第二個序數值為 2.

      作為如何調用包含 IN 參數的存儲過程的實例,使用 SQL Server 2005 AdventureWorks 示例數據庫中的 uspGetEmployeeManagers 存儲過程。此存儲過程接受名為 EmployeeID 的單個輸入參數

    posted @ 2013-10-24 17:05 chen11-1 閱讀(636) | 評論 (0)編輯 收藏

    Java中生成文件的10項建議

    1. 記住 - "越少越好"并非總是如此(Keep in Mind – "Less is more" is not always better)。 – 高效率的代碼是件好事,但很多情況下,并非代碼行數越少效率就越高

      2. 不要把簡單事情復雜化(Do not complicate things)。 – 我曾經這么做過,我相信你也一樣。開發者都傾向于采用復雜方式解決簡單問題。我們在一個只有5個用戶的系統中引入EJB,為一個并不需要框架的應用實現一套框架,采用屬性文件、采用面向tb對象解決方案、使用線程,而這些根本用不著。為什么會這么做?一些人可能不知道有更好的解決方案,但另一些人可能故意這樣做來學習新知識,或僅僅是因為有趣。對那些不知道更好解決方案的人,要多聽有經驗程序員的建議。對于那些純粹出于個人目的而將設計復雜化的人,我建議你要更加專業一點。
      3. 不要"硬編碼"(No hard coding please)。 – 由于時間緊迫,開發者總是會忘記或故意忽略這一條。然而另一種可能是,遵循這條戒律,我們就不會陷入"時間緊迫"的困境。定義一個static final 變量,增加一行代碼,又能花多長時間呢?

      4. 為代碼添加注釋(Add comments to your code)。 – 每個人都知道這一點,但不是每個人都會這么做。你有多少次"忘記"添加注釋了?確實,注釋不會為你的程序增加任何函數功能。但是,有多少次,看到2周前寫的代碼,你都記不起它是干什么的?你很幸運,那些未注釋的代碼是你自己寫的,你腦海中還會有殘存的印象。非常不幸,大多時候,代碼是別人寫的,并且那個人很可能已經離開公司了。有句諺語說的好:"有來有往,互惠互利",因此程序員應該體諒彼此(還有你自己),給你的代碼加上注釋。

     

    posted @ 2013-10-24 17:04 chen11-1 閱讀(325) | 評論 (0)編輯 收藏

    針對Java Excel API及詳細教程

    時在java開發中會操作excel表格,其實操作起來也特別簡單。這里把前期操作步驟說一下,本文會簡單的介紹一個開放源碼項目:Java Excel Api,使用它大家就可以方便的操作Excel文件了。

      首先下載好:Java Excel Api,這個文件我已經和 JAVA+Excel+API詳細教程。pdf一并壓縮上傳了,感興趣的朋友可以下載!

      我這里用的開發平臺是Eclipse,這里我把操作簡單說一下:

      1, 建,立java項目,在這個項目在建立一個新的文件夾lib;

      2, 將jxl.jar,即Java Excel Ap,復制到lib

      3,然后右鍵點擊這個java項目,tb選擇Propertieshttp://jie.baijiale.ibc198.com

      4,在左側列表里選中Java Build Path ,右側選中Libraries

      5,點擊Add JARs

      6, 然后去選擇這個項目中lib文件夾中的jxl.jar,點擊確定

      成功后,項目中會多一個文件夾為:Referenced Libraries

      準備工作完成后,就可以去操作excel了,

    posted @ 2013-10-24 17:02 chen11-1 閱讀(287) | 評論 (0)編輯 收藏

    框架Quart在Java中任務調度的使用

      Quartz框架是一個全功能、開源的任務調度服務,可以集成幾乎任何的java應用程序—從小的單片機系統到大型的電子商務系統。Quartz可以執行上千上萬的任務調度。

      核心概念

      Quartz核心的概念:scheduler任務調度、Job任務、Trigger觸發器、JobDetail任務細節

      Job任務:其實Job是接口,其中只有一個execute方法:

      package org.quartz;

      public abstract interface Job

      {

      public abstract void execute(JobExecutionContext paramJobExecutionContext)

      throws JobExecutionException;

      }

      我們開發者只要實現此接口,實現execute方法即可。把我們想做的事情,在execute中執行即可。

      JobDetail:任務細節,Quartz執行Job時,需要新建個Job實例,但是不能直接操作Job類,所以通過JobDetail來獲取Job的名稱、描述信息。

      Trigger觸發器:執行任務的規則;比如每天,每小時等。

      一般情況使用SimpleTrigger,和CronTrigger,這個觸發器實現了Trigger接口。

      對于復雜的時間表達式來說,比如每個月15日上午幾點幾分,使用CronTrigger

      對于簡單的時間來說,比如每天執行幾次,使用SimpleTrigger

      scheduler任務調度:是最核心的概念,需要把JobDetail和Trigger注冊到scheduler中,才可以執行。

      注意:

      不同的版本的jar包,具體的操作不太相同,但是tbw思路是相同的;比如1.8.6jar包中,JobDetail是個類,直接通過構造方法與Job類關聯。SimpleTrigger和CornTrigger是類;在2.0.2jar包中,JobDetail是個接口,SimpleTrigger和CornTrigger是接口

      不同版本測試:

      1.8.6jar包:

      [html]

      package com.test;

      import java.util.Date;

      import org.quartz.Job;

      import org.quartz.JobExecutionContext;

      import org.quartz.JobExecutionException;

      /**

      * 需要執行的任務

      * @author lhy

      *

      */

      public class MyJob implements Job {

      @Override

      //把要執行的操作,寫在execute方法中

      public void execute(JobExecutionContext arg0) throws JobExecutionException {

      System.out.println("測試Quartz"+new Date());

      }

      }

      package com.test;

      import java.util.Date;

      import org.quartz.Job;

      import org.quartz.JobExecutionContext;

      import org.quartz.JobExecutionException;

      /**

      * 需要執行的任務

      * @author lhy

      *

      */

      public class MyJob implements Job {

      @Override

      //把要執行的操作,寫在execute方法中

      public void execute(JobExecutionContext arg0) throws JobExecutionException {

      System.out.println("測試Quartz"+new Date());

      }

      }

      使用SimpleTrigger觸發器

      [html]

      package com.test;

      import java.util.Date;

      import org.quartz.JobDetail;

      import org.quartz.Scheduler;

      import org.quartz.SchedulerException;

      import org.quartz.SchedulerFactory;

      import org.quartz.SimpleTrigger;

      import org.quartz.impl.StdSchedulerFactory;

      /**

      * 調用任務的類

      * @author lhy

      *

      */

      public class SchedulerTest {

      public static void main(String[] args) {

      //通過schedulerFactory獲取一個調度器

      SchedulerFactory schedulerfactory=new StdSchedulerFactory();

      Scheduler scheduler=null;

      try{

      // 通過schedulerFactory獲取一個調度器

      scheduler=schedulerfactory.getScheduler();

      // 創建jobDetail實例,綁定Job實現類

      // 指明job的名稱,所在組的名稱,以及綁定job類

      JobDetail jobDetail=new JobDetail("job1", "jgroup1", MyJob.class);

      // 定義調度觸發規則,比如每1秒運行一次,共運行8次

      SimpleTrigger simpleTrigger=new SimpleTrigger("simpleTrigger","triggerGroup");

      // 馬上啟動

      simpleTrigger.setStartTime(new Date());

      // 間隔時間

      simpleTrigger.setRepeatInterval(1000);

      // 運行次數

      simpleTrigger.setRepeatCount(8);

      // 把作業和觸發器注冊到任務調度中

      scheduler.scheduleJob(jobDetail, simpleTrigger);

      // 啟動調度

      scheduler.start();

      }catch(SchedulerException e){

      e.printStackTrace();

      }

      }

      }

      package com.test;

      import java.util.Date;

      import org.quartz.JobDetail;

      import org.quartz.Scheduler;

      import org.quartz.SchedulerException;

      import org.quartz.SchedulerFactory;

      import org.quartz.SimpleTrigger;

      import org.quartz.impl.StdSchedulerFactory;

      /**

      * 調用任務的類

      * @author lhy

      *

      */

      public class SchedulerTest {

      public static void main(String[] args) {

      //通過schedulerFactory獲取一個調度器

      SchedulerFactory schedulerfactory=new StdSchedulerFactory();

      Scheduler scheduler=null;

      try{

      // 通過schedulerFactory獲取一個調度器

      scheduler=schedulerfactory.getScheduler();

      // 創建jobDetail實例,綁定Job實現類

      // 指明job的名稱,所在組的名稱,以及綁定job類
     JobDetail jobDetail=new JobDetail("job1", "jgroup1", MyJob.class);

      // 定義調度觸發規則,比如每1秒運行一次,共運行8次

      SimpleTrigger simpleTrigger=new SimpleTrigger("simpleTrigger","triggerGroup");

      // 馬上啟動

      simpleTrigger.setStartTime(new Date());

      // 間隔時間

      simpleTrigger.setRepeatInterval(1000);

      // 運行次數

      simpleTrigger.setRepeatCount(8);

      // 把作業和觸發器注冊到任務調度中

      scheduler.scheduleJob(jobDetail, simpleTrigger);

      // 啟動調度

      scheduler.start();

      }catch(SchedulerException e){

      e.printStackTrace();

      }

      }

      } 若使用CornTrigger觸發器:

      [html]

      package com.test;

      import java.util.Date;

      import org.quartz.CronTrigger;

      import org.quartz.JobDetail;

      import org.quartz.Scheduler;

      import org.quartz.SchedulerException;

      import org.quartz.SchedulerFactory;

      import org.quartz.SimpleTrigger;

      import org.quartz.impl.StdSchedulerFactory;

      /**

      * 調用任務的類

      * @author lhy

      *

      */

      public class CronTriggerTest {

      public static void main(String[] args) {

      //通過schedulerFactory獲取一個調度器

      SchedulerFactory schedulerfactory=new StdSchedulerFactory();

      Scheduler scheduler=null;

      try{

      // 通過schedulerFactory獲取一個調度器

      scheduler=schedulerfactory.getScheduler();

      // 創建jobDetail實例,綁定Job實現類

      // 指明job的名稱,所在組的名稱,以及綁定job類

      JobDetail jobDetail=new JobDetail("job1", "jgroup1", MyJob.class);

      // 定義調度觸發規則,每天上午10:15執行

      CronTrigger cornTrigger=new CronTrigger("cronTrigger","triggerGroup");

      // 執行規則表達式

      cornTrigger.setCronExpression("0 15 10 * * ? *");

      // 把作業和觸發器注冊到任務調度中

      scheduler.scheduleJob(jobDetail, cornTrigger);

      // 啟動調度

      scheduler.start();

      }catch(Exception e){

      e.printStackTrace();

      }

      }

      }

      package com.test;

      import java.util.Date;

      import org.quartz.CronTrigger;

      import org.quartz.JobDetail;

      import org.quartz.Scheduler;

      import org.quartz.SchedulerException;

      import org.quartz.SchedulerFactory;

      import org.quartz.SimpleTrigger;

      import org.quartz.impl.StdSchedulerFactory;

      /**

      * 調用任務的類

      * @author lhy

      *

      */

      public class CronTriggerTest {

      public static void main(String[] args) {

      //通過schedulerFactory獲取一個調度器

      SchedulerFactory schedulerfactory=new StdSchedulerFactory();

      Scheduler scheduler=null;

      try{

      // 通過schedulerFactory獲取一個調度器

      scheduler=schedulerfactory.getScheduler();

      // 創建jobDetail實例,綁定Job實現類

      // 指明job的名稱,所在組的名稱,以及綁定job類

      JobDetail jobDetail=new JobDetail("job1", "jgroup1", MyJob.class);

      // 定義調度觸發規則,每天上午10:15執行

      CronTrigger cornTrigger=new CronTrigger("cronTrigger","triggerGroup");

      // 執行規則表達式

      cornTrigger.setCronExpression("0 15 10 * * ? *");

      // 把作業和觸發器注冊到任務調度中

      scheduler.scheduleJob(jobDetail, cornTrigger);

      // 啟動調度

      scheduler.start();

      }catch(Exception e){

      e.printStackTrace();

      }

      }

      }

      對于2.0.2jar包如下:

      其中的job類不變,主要是調度類如下:

      [html]

      package com.test;

      import java.util.Date;

      import org.quartz.CronScheduleBuilder;

      import org.quartz.JobBuilder;

      import org.quartz.JobDetail;

      import org.quartz.Scheduler;

      import org.quartz.SchedulerException;

      import org.quartz.SchedulerFactory;

      import org.quartz.SimpleScheduleBuilder;

      import org.quartz.Trigger;

      import org.quartz.TriggerBuilder;

      import org.quartz.impl.StdSchedulerFactory;

      /**

      * 調用任務的類

      * @author lhy

      *

      */

      public class SchedulerTest {

      public static void main(String[] args) {

      //通過schedulerFactory獲取一個調度器

      SchedulerFactory schedulerfactory=new StdSchedulerFactory();

      Scheduler scheduler=null;

      try{

      // 通過schedulerFactory獲取一個調度器

      scheduler=schedulerfactory.getScheduler();

      // 創建jobDetail實例,綁定Job實現類

      // 指明job的名稱,所在組的名稱,以及綁定job類

      JobDetail job=JobBuilder.newJob(MyJob.class).withIdentity("job1", "jgroup1").build();

      // 定義調度觸發規則

      // 使用simpleTrigger規則

      // Trigger trigger=TriggerBuilder.newTrigger().withIdentity("simpleTrigger", "triggerGroup")

      // .withSchedule(SimpleScheduleBuilder.repeatSecondlyForever(1).withRepeatCount(8))

      // .startNow().build();

      // 使用cornTrigger規則 每天10點42分

      Trigger trigger=TriggerBuilder.newTrigger().withIdentity("simpleTrigger", "triggerGroup")

      .withSchedule(CronScheduleBuilder.cronSchedule("0 42 10 * * ? *"))

      .startNow().build();

      // 把作業和觸發器注冊到任務調度中

      scheduler.scheduleJob(job, trigger);

      // 啟動調度

      scheduler.start();

      }catch(Exception e){

      e.printStackTrace();

      }

      }

      }

      package com.test;

      import java.util.Date;

      import org.quartz.CronScheduleBuilder;

      import org.quartz.JobBuilder;

      import org.quartz.JobDetail;

      import org.quartz.Scheduler;

      import org.quartz.SchedulerException;

      import org.quartz.SchedulerFactory;

      import org.quartz.SimpleScheduleBuilder;

      import org.quartz.Trigger;

      import org.quartz.TriggerBuilder;

      import org.quartz.impl.StdSchedulerFactory;

      /**

      * 調用任務的類

      * @author lhy

      *

      */

      public class SchedulerTest {

      public static void main(String[] args) {

      //通過schedulerFactory獲取一個調度器

      SchedulerFactory schedulerfactory=new StdSchedulerFactory();

      Scheduler scheduler=null;

      try{

      // 通過schedulerFactory獲取一個調度器

      scheduler=schedulerfactory.getScheduler();

      // 創建jobDetail實例,綁定Job實現類

      // 指明job的名稱,所在組的名稱,以及綁定job類

      JobDetail job=JobBuilder.newJob(MyJob.class).withIdentity("job1", "jgroup1").build();

      // 定義調度觸發規則

      // 使用simpleTrigger規則

      // Trigger trigger=TriggerBuilder.newTrigger().withIdentity("simpleTrigger", "triggerGroup")

      // .withSchedule(SimpleScheduleBuilder.repeatSecondlyForever(1).withRepeatCount(8))

      // .startNow().build();

      // 使用cornTrigger規則 每天10點42分

      Trigger trigger=TriggerBuilder.newTrigger().withIdentity("simpleTrigger", "triggerGroup")

      .withSchedule(CronScheduleBuilder.cronSchedule("0 42 10 * * ? *"))

      .startNow().build();

      // 把作業和觸發器注冊到任務調度中

      scheduler.scheduleJob(job, trigger);

      // 啟動調度

      scheduler.start();

      }catch(Exception e){

      e.printStackTrace();

      }

      }

      }

      上述demo下載:1.8版本demo下載

      2.0版本demo下載

      對于CornExpress講解如下:

      字段 允許值 允許的特殊字符

      秒 0-59 , - * /

      分 0-59 , - * /

      小時 0-23 , - * /

      日期 1-31 , - * ? / L W C

      月份 1-12 或者 JAN-DEC , - * /

      星期 1-7 或者 SUN-SAT , - * ? / L C #

      年(可選) 留空, 1970-2099 , - * /

      表達式 意義

      "0 0 12 * * ?" 每天中午12點觸發

      "0 15 10 ? * *" 每天上午10:15觸發

      "0 15 10 * * ?" 每天上午10:15觸發

      "0 15 10 * * ? *" 每天上午10:15觸發

      "0 15 10 * * ? 2005" 2005年的每天上午10:15觸發

      "0 * 14 * * ?" 在每天下午2點到下午2:59期間的每1分鐘觸發

      "0 0/5 14 * * ?" 在每天下午2點到下午2:55期間的每5分鐘觸發

      "0 0/5 14,18 * * ?" 在每天下午2點到2:55期間和下午6點到6:55期間的每5分鐘觸發

      "0 0-5 14 * * ?" 在每天下午2點到下午2:05期間的每1分鐘觸發

      "0 10,44 14 ? 3 WED" 每年三月的星期三的下午2:10和2:44觸發

      "0 15 10 ? * MON-FRI" 周一至周五的上午10:15觸發

      "0 15 10 15 * ?" 每月15日上午10:15觸發

      "0 15 10 L * ?" 每月最后一日的上午10:15觸發

      "0 15 10 ? * 6L" 每月的最后一個星期五上午10:15觸發

      "0 15 10 ? * 6L 2002-2005" 2002年至2005年的每月的最后一個星期五上午10:15觸發

      "0 15 10 ? * 6#3" 每月的第三個星期五上午10:15觸發

      特殊字符 意義

      * 表示所有值;

      ? 表示未說明的值,即不關心它為何值;

      - 表示一個指定的范圍;

      , 表示附加一個可能值;

      / 符號前表示開始時間,符號后表示每次遞增的值;

      L("last") ("last") "L" 用在day-of-month字段意思是 "這個月最后一天";用在 day-of-week字段, 它簡單意思是 "7" or "SAT"。 如果在day-of-week字段里和數字聯合使用,它的意思就是 "這個月的最后一個星期幾" – 例如: "6L" means "這個月的最后一個星期五". 當我們用“L”時,不指明一個列表值或者范圍是很重要的,不然的話,我們會得到一些意想不到的結果。

      W("weekday") 只能用在day-of-month字段。用來描敘最接近指定天的工作日(周一到周五)。例如:在day-of-month字段用“15W”指“最接近這個月第15天的工作日”,即如果這個月第15天是周六,那么觸發器將會在這個月第14天即周五觸發;如果這個月第15天是周日,那么觸發器將會在這個月第16天即周一觸發;如果這個月第15天是周二,那么就在tbw觸發器這天觸發。注意一點:這個用法只會在當前月計算值,不會越過當前月。“W”字符僅能在day-of-month指明一天,不能是一個范圍或列表。也可以用“LW”來指定這個月的最后一個工作日。

      # 只能用在day-of-week字段。用來指定這個月的第幾個周幾。例:在day-of-week字段用"6#3"指這個月第3個周五(6指周五,3指第3個)。如果指定的日期不存在,觸發器就不會觸發。

      C 指和calendar聯系后計算過的值。例:在day-of-month 字段用“5C”指在這個月第5天或之后包括calendar的第一天;在day-of-week字段用“1C”指在這周日或之后包括calendar的第一天

    posted @ 2013-09-17 15:15 chen11-1 閱讀(2024) | 評論 (0)編輯 收藏

    序列化在IO中讀寫對象的使用

        序列化就是一種用來處理對象流的機制,所謂對象流也就是將對象的內容進行流化。可以對流化后的對象進行讀寫操作,也可將流化后的對象傳輸于網絡之間。序列化是為了解決在對對象流進行讀寫操作時所引發的問題。

      序列化的實現:將需要被序列化的類實現Serializable接口,然后使用一個輸出流(如:FileOutputStream)來構造一個ObjectOutputStream(對象流)對象,接著,使用ObjectOutputStream對象的writeObject(Object obj)方法就可以將參數為obj的對象寫出(即保存其狀態),要恢復的話則用輸入流。
     寫對象和讀對象的時候一定要使用序列化:

      import java.io.*;

      class Product implements Serializable {

      private static final long serialVersionUID = 1L;

      private float price;

      private float tax;

      public Product(float price) {

      this.price = price;

      tax = (float)(price*0.20);

      }

      public String toString() {

      return "price:"+price+",tax:"+tax;

      }

      }

      public class CmdDemo {

      public static void main(String[] strtb) throws Exception {

      Product p1 = new Product(100);

      ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream

      ("d:\product.txt"));

      os.writeObject(p1);

      os.close();

      ObjectInputStream is = new ObjectInputStream(new FileInputStream

      ("d:\product.txt"));

      Product p2 = (Product) is.readObject();

      System.out.println(p2.toString());

      }

      }

    posted @ 2013-09-17 15:12 chen11-1 閱讀(276) | 評論 (0)編輯 收藏

    Java數組使用實用的技巧

      本文分享了關于Java數組最頂級的11大方法,幫助你解決工作流程問題,無論是運用在團隊環境或是在私人項目中,你都可以直接拿來用!

    0.  聲明一個數組(Declare an array)
     
    String[] aArray = new String[5];
    String[] bArray = {"a","b","c", "d", "e"};
    String[] cArray = new String[]{"a","b","c","d","e"};

    1.  在Java中輸出一個數組(Print an array in Java)
     
    int[] intArray = { 1, 2, 3, 4, 5 };
    String intArrayString = Arrays.toString(intArray);
     
    // print directly will print reference value
    System.out.println(intArray);
    // [I@7150bd4d
     
    System.out.println(intArrayString);
    // [1, 2, 3, 4, 5]

    2. 從數組中創建數組列表(Create an ArrayList from an array)
     
    String[] stringArray = { "a", "b", "c", "d", "e" };
    ArrayList<String> arrayList = new ArrayList<String>(Arrays.asList(stringArray));
    System.out.println(arrayList);
    // [a, b, c, d, e]

    3. 檢查愛淘寶數組中是否包含特定值(Check if an array contains a certain value)
     
    String[] stringArray = { "a", "b", "c", "d", "e" };
    boolean b = Arrays.asList(stringArray).contains("a");
    System.out.println(b);
    // true
     
    4. 連接兩個數組( Concatenate two arrays)
     
    int[] intArray = { 1, 2, 3, 4, 5 };
    int[] intArray2 = { 6, 7, 8, 9, 10 };
    // Apache Commons Lang library
    int[] combinedIntArray = ArrayUtils.addAll(intArray, intArray2);
    5. 聲明一個數組內鏈(Declare an array inline )
     
    method(new String[]{"a", "b", "c", "d", "e"});
     
    6. 將數組元素加入到一個獨立的字符串中(Joins the elements of the provided array into a single String)

    // containing the provided list of elements
    // Apache common lang
    String j = StringUtils.join(new String[] { "a", "b", "c" }, ", ");
    System.out.println(j);
    // a, b, c
     
    7. 將數組列表轉換成一個數組 (Covnert an ArrayList to an array)
     
    String[] stringArray = { "a", "b", "c", "d", "e" };
    ArrayList<String> arrayList = new ArrayList<String>(Arrays.asList(stringArray));
    String[] stringArr = new String[arrayList.size()];
    arrayList.toArray(stringArr);
    for (String s : stringArr)
        System.out.println(s);
     
    8. 將數組轉換成一個集合(Convert an array to a set)
     
    Set<String> set = new HashSet<String>(Arrays.asList(stringArray));
    System.out.println(set);
    //[d, e, b, c, a]
     
    9. 反向數組(Reverse an array)
     
    int[] intArray = { 1, 2, 3, 4, 5 };
    ArrayUtils.reverse(intArray);
    System.out.println(Arrays.toString(intArray));
    //[5, 4, 3, 2, 1]
     
    10. 刪除數組元素(Remove element of an array)
     
    int[] intArray = { 1, 2, 3, 4, 5 };
    int[] removed = ArrayUtils.removeElement(intArray, 3);
    //create a new array
    System.out.println(Arrays.toString(removed));
     
    One more – convert int to byte array
     
    byte[] bytes = ByteBuffer.allocate(4).putInt(8).array();
     
    for (byte t : bytes) {
       System.out.format("0x%x ", t);
    }

    posted @ 2013-09-17 15:08 chen11-1 閱讀(265) | 評論 (0)編輯 收藏

    Java動態代理設計模式

     所謂動態代理類是在運行時生成的class,在生成它時,你必須提供一組interface給它,則動態代理類就宣稱它實現了這些interface。當然,動態代理類就充當一個代理,你不要企圖它會幫你干實質性的工作,在生成它的實例時你必須提供一個handler,由它接管實際的工作。
      下面通過實例來說明:
      Subject.java 抽象借口:聲明代理對象和真實對象的共同接口
      [java]
      public interface Subject {
      public void doSomething();
      }
      public interface Subject {
      public void doSomething();
      }
      RealSubject.java 真實被tb代理對象
      [java]
      public class RealSubject implements Subject {
      @Override
      public void doSomething() {
      System.out.println("RealSubject.doSomething");
      }
      }
      public class RealSubject implements Subject {
      @Override
      public void doSomething() {
      System.out.println("RealSubject.doSomething");
      }
      }

      DynamicProxy.java 代理對象
      [java]
      import java.lang.reflect.InvocationHandler;
      import java.lang.reflect.Method;
      public class DynamicProxy implements InvocationHandler {
      private Object object;
      public DynamicProxy(Object object) {
      this.object = object;
      }
      @Override
      public Object invoke(Object proxy, Method method, Object[] args)throws Throwable {
      System.out.println("Before Invoke ! method : " + method);
      //我們可以再代理方法調用前后添加功能
      Object result = method.invoke(object, args);
      System.out.println("object : " + object + " result : " + result + " args : " + args);
      System.out.println("After Invoke !");
      return result;
      }
      }
      import java.lang.reflect.InvocationHandler;
      import java.lang.reflect.Method;
      public class DynamicProxy implements InvocationHandler {
      private Object object;
      public DynamicProxy(Object object) {
      this.object = object;
      }
      @Override
      public Object invoke(Object proxy, Method method, Object[] args)throws Throwable {
      System.out.println("Before Invoke ! method : " + method);
      //我們可以再代理方法調用前后添加功能
      Object result = method.invoke(object, args);
      System.out.println("object : " + object + " result : " + result + " args : " + args);
      System.out.println("After Invoke !");
      return result;
      }
      }
      Client.java 測試
      [java]
      import java.lang.reflect.InvocationHandler;
      import java.lang.reflect.Proxy;
      public class Client {
      public static void main(String[] args) throws Exception {
      //創建目標對象,也就是被代理對象
      RealSubject realSubject = new RealSubject();
      //將目標對象交給代理
      InvocationHandler handler = new DynamicProxy(realSubject);
      // Class proxyClass = Proxy.getProxyClass(Subject.class.getClassLoader()
      // , new Class[]{Subject.class});
      // Subject subject = (Subject)proxyClass.getConstructor(new Class[]{InvocationHandler.class})
      // .newInstance(new Object[]{handler});
      //返回代理對象,相當于上面兩句
      Subject subject = (Subject) Proxy.newProxyInstance(handler.getClass().getClassLoader(),
      realSubject.getClass().getInterfaces(),
      handler);
      //叫代理對象去doSomething(),其實在代理對象中的doSomething()中還是會
      //用handler來調用invoke(proxy, method, args) 參數proxy為調用者subject(this),
      //method為doSomething(),tb參數為方法要傳入的參數,這里沒有
      subject.doSomething();
      }
      }
      import java.lang.reflect.InvocationHandler;
      import java.lang.reflect.Proxy;
      public class Client {
      public static void main(String[] args) throws Exception {
      //創建目標對象,也就是被代理對象
      RealSubject realSubject = new RealSubject();
      //將目標對象交給代理
      InvocationHandler handler = new DynamicProxy(realSubject);
      // Class proxyClass = Proxy.getProxyClass(Subject.class.getClassLoader()
      // , new Class[]{Subject.class});
      // Subject subject = (Subject)proxyClass.getConstructor(new Class[]{InvocationHandler.class})
      // .newInstance(new Object[]{handler});
      //返回代理對象,相當于上面兩句
      Subject subject = (Subject) Proxy.newProxyInstance(handler.getClass().getClassLoader(),
      realSubject.getClass().getInterfaces(),
      handler);
      //叫代理對象去doSomething(),其實在代理對象中的doSomething()中還是會
      //用handler來調用invoke(proxy, method, args) 參數proxy為調用者subject(this),
      //method為doSomething(),參數為方法要傳入的參數,這里沒有
      subject.doSomething();
      }
      }
      打印結果:
      Before Invoke ! method : public abstract void Subject.doSomething()
      RealSubject.doSomething
      object : RealSubject@ec6b00 result : null args : null
      After Invoke !
      注意:
      Java動態代理涉及到的兩個類:
      InvocationHandler:該接口中僅定義了一個Object : invoke(Object proxy, Method method, Object[] args);參數proxy指代理類,method表示被代理的方法,args為method中的參數數組,返回值Object為代理實例的方法調用返回的值。這個抽象方法在代理類中動態實現。
      Proxy:所有動態代理類的父類,提供用于創建動態代理類和實例的靜態方法。

    posted @ 2013-09-10 17:08 chen11-1 閱讀(273) | 評論 (0)編輯 收藏

    30條有用的 Java 編程規則

     (1) 類名首字母應該大寫。字段、方法以及對象(句柄)的首字母應小寫。對于所有標識符,其中包含的所有單詞都應緊靠在一起,而且大寫中間單詞的首字 母。例如:
      ThisIsAClassName
      thisIsMethodOrFieldName
      若在定義中出現了常數初始化字符,則大寫static final基本類型標識符中的所有字母。這樣便可標志出它們屬于編譯期的常數。
      Java包(Package)屬于一種特殊情況:它們全都是小寫字母,即便中間的單詞亦是如此。對于域名擴展名稱,如com,org,net或者edu 等,全部都應小寫(這也是Java 1.1和Java 1.2的區別之一)。
      (2) 為了常規用途而創建一個類時,請采取“tb經典形式”,并包含對下述元素的定義:
      equals()
      hashCode()
      toString()
      clone()(implement Cloneable)
      implement Serializable
      (3) 對于自己創建的每一個類,都考慮置入一個main(),其中包含了用于測試那個類的代碼。為使用一個項目中的類,我們沒必要刪除測試代碼。若 進行了任何形式的改動,可方便地返回測試。這些代碼也可作為如何使用類的一個示例使用。
      (4) 應將方法設計成簡要的、功能性單元,用它描述和實現一個不連續的類接口部分。理想情況下,方法應簡明扼要。若長度很大,可考慮通過某種方式將其分割成較短的幾個方法。這樣做也便于類內代碼的重復使用(有些時候,方法必須非常大,但它們仍應只做同樣的一件事情)。 (5) 設計一個類時,請設身處地為客戶程序員考慮一下(類的使用方法應該是非常明確的)。然后,再設身處地為管理代碼的人考慮一下(預計有可能進行哪些形式的修改,想想用什么方法可把它們變得更簡單)。
      (6) 使類盡可能短小精悍,而且只解決一個特定的問題。下面是對類設計的一些建議:
      ■一個復雜的開關語句:考慮采用“多形”機制
      ■數量眾多的方法涉及到類型差別極大的操作:考慮用幾個類來分別實現
      ■許多成員變量在特征上有很大的差別:考慮使用幾個類 。
      (7) 讓一切東西都盡可能地“私有”——private??墒箮斓哪骋徊糠?#8220;公共化”(一個方法、類或者一個字段等等),就永遠不能把它拿出。若強行拿出,就可能破壞其他人現有的代碼,使他們不得不重新編寫和設計。若只公布自己必須公布的,就可放心大膽地改變其他任何東西。在多線程環境中,隱私是特別重要的一個因素——只有private字段才能在非同步使用的情況下受到保護。
      (8) 謹惕“巨大對象綜合癥”。對一些習慣于順序編程思維、且初涉OOP領域的新手,往往喜歡先寫一個順序執行的程序,再把它嵌入一個或兩個巨大的 對象里。根據編程原理,對象表達的應該是應用程序的概念,而非應用程序本身。
      (9) 若不得已進行一些不太雅觀的編程,至少應該把那些代碼置于一個類的內部。
      (10) 任何時候只要發現類與類之間結合得非常緊密,就需要考慮是否采用內部類,從而改善編碼及維護工作(參見第14章14.1.2小節的“用內部 類改進代碼”)。
      (11) 盡可能細致地加上釋,并用javadoc注釋文檔語法生成自己的程序文檔。
      (12) 避免使用“魔術數字”,這些數字很難與代碼很好地配合。如以后需要修改它,無疑會成為一場噩夢,因為根本不知道“100”到底是指“數組大小”還是“其他全然不同的東西”。所以,我們應創建一個常數,并為其使用具有說服力的描述性名稱,并在整個程序中都采用常數標識符。這樣可使程序更易理解以及更易維護。
      (13) 涉及構建器和異常的時候,通常希望重新丟棄在構建器中捕獲的任何異常——如果它造成了那個對象的創建失敗。這樣一來,調用者就不會以為那個 對象已正確地創建,從而盲目地繼續。
      (14) 當客戶程序員用完對象以后,若你的類要求進行任何清除工作,可考慮將清除代碼置于一個良好定義的方法里,采用類似于cleanup()這樣的名字,明確表明自己的用途。除此以外,可在類內放置一個boolean(布爾)標記,指出對象是否已被清除。在類的finalize()方法里,請確定對象已被清除,并已丟棄了從RuntimeException繼承的一個類(如果還沒有的話),從而指出一個編程錯誤。在采取象這樣的方案之前,請確定 finalize()能夠在自己的系統中工作(可能需要調用System.runFinalizersonExit(true),從而確保 這一行為)。
      (15) 在一個特定的作用域內,若一個對象必須清除(非由tb垃圾收集機制處理),請采用下述方法:初始化對象;若成功,則立即進入一個含有 finally從句的try塊,開始清除工作。
      (16) 若在初始化過程中需要覆蓋(取消)finalize(),請記住調用super.finalize()(若Object屬于我們的直接超類,則無此必要)。在對finalize()進行覆蓋的過程中,對super.finalize()的調用應屬于最后一個行動,而不應是第一個行動,這樣可確保在需要基礎類組件的時候它們依然有效。
      (17) 創建大小固定的對象集合時,請將它們傳輸至一個數組(若準備從一個方法里返回這個集合,更應如此操作)。這樣一來,我們就可享受到數組在編 譯期進行類型檢查的好處。此外,為使用它們,數組的接收者也許并不需要將對象“造型”到數組里。
      (18) 盡量使用interfaces,不要使用abstract類。若已知某樣東西準備成為一個基礎類,那么第一個選擇應是將其變成一個 interface(接口)。只有在不得不使用方法定義或者成員變量的時候,才需要將其變成一個abstract(抽象)類。接口主要描述了客戶希望做什么事情,而一個類則致力于(或允許)具體的實施細節。
      (19) 在構建器內部,只進行那些將對象設為正確狀態所需的工作。盡可能地避免調用其他方法,因為那些方法可能被其他人覆蓋或取消,從而在構建過程 中產生不可預知的結果(參見第7章的詳細說明)。
      (20) 對象不應只是簡單地容納一些數據;它們的行為也應得到良好的定義。
      (21) 在現成類的基礎上創建新類時,請首先選擇“新建”或“創作”。只有自己的設計要求必須繼承時,才應考慮這方面的問題。若在本來允許新建的場 合使用了繼承,則整個設計會變得沒有必要地復雜。
      (22) 用繼承及方法覆蓋來表示行為間的差異,而用字段表示狀態間的區別。一個非常極端的例子是通過對不同類的繼承來表示顏色,這是絕對應該避免 的:應直接使用一個“顏色”字段。

      (23) 為避免編程時遇到麻煩,請保證在自己類路徑指到的任何地方,每個名字都僅對應一個類。否則,編譯器可能先找到同名的另一個類,并報告出錯消 息。若懷疑自己碰到了類路徑問題,請試試在類路徑的每一個起點,搜索一下同名的.class文件。
      (24) 在Java 1.1 AWT 中使用事件“適配器”時,特別容易碰到一個陷阱。若覆蓋了某個適配器方法,同時拼寫方法沒有特別講究,最后的結果就是新添加一個方法,而不是覆蓋現成方法。然而,由于這樣做是完全合法的,所以不會從編譯器或運行期系統獲得任何出錯提示——只不過代碼的工作就變得不正常了。
      (25) 用合理的設計方案消除“偽功能”。也就是說,假若只需要創建類的一個對象,就不要提前限制自己使用應用程序,并加上一條“只生成其中一個 ” 注釋。請考慮將其封裝成一個“獨生子”的形式。若在主程序里有大量散亂的代碼,用于創建自己的對象,請考慮采納一種創造性的方案,將些代碼封裝起來。
      (26) 警惕“分析癱瘓”。請記住,無論如何都要提前了解整個項目的狀況,再去考察其中的細節。由于把握了全局,可快速認識自己未知的一些因素,防 止在考察細節的時候陷入“死邏輯”中。
      (27) 警惕“過早優化”。首先讓它運行起來,再考慮變得更快——但只有在自己必須這樣做、而且經證實在某部分代碼中的確存在一個性能瓶頸的時候, 才應進行優化。除非用專門的工具分析瓶頸,否則很有可能是在浪費自己的時間。性能提升的隱含代價是自己的代碼變得難于理解,而且難于維護。
      (28) 請記住,閱讀代碼的時間比寫代碼的時間多得多。思路清晰的設計可獲得易于理解的程序,但注釋、細致的解釋以及一些示例往往具有不可估量的價 值。無論對你自己,還是對后來的人,它們都是相當重要的。如對此仍有懷疑,那么請試想自己試圖從聯機Java文檔里找出有用信息時碰到的挫折,這樣或許能 將你說服。
      (29) 如認為自己已進行了良好的分析、設計或者實施,那么請稍微更換一下思維角度。試試邀請一些外來人士——并不一定是專家,但可以是來自本公司其他部門的人。請他們用完全新鮮的眼光考察你的工作,看看是否能找出你一度熟視無睹的問題。采取這種方式,往往能在最適合修改的階段找出一些關鍵性的問題,避免產品發行后再解決問題而造成的金錢及精力方面的損失。
      (30) 良好的設計能帶來最大的回報。簡言之,對于一個特定的問題,通常會花較長的時間才能找到一種最恰當的解決方案。但一旦找到了正確的方法,以后的工作就輕松多了,再也不用經歷數小時、數天或者數月的痛苦掙扎。我們的努力工作會帶來最大的回報(甚至無可估量)。而且由于自己傾注了大量心血,最終獲得一個出色的設計方案,成功的快感也是令人心動的。堅持抵制草草完工的誘惑——那樣做往往得不償失

    posted @ 2013-08-23 16:56 chen11-1 閱讀(247) | 評論 (0)編輯 收藏

    單多線程Java算法相比較

    1進程和線程的概念
      1.1什么是進程
      一個進程就是在一個運行的程序,它有自己獨立的內存空間,一組系統資源,每個進程的內部數據和狀態都是獨立的,例如在window是同時打開多個記事本,雖然它們所運行的程序代碼都是一樣的,但是所使用的內存空間是獨立的,互不干擾.
      1.2什么是線程
      線程與進程相似,是一段完成某個特定功能的代碼,是程序中單個順序的流控制;但與進程不同的是,同類的多個線程共享一塊內存空間和一組系統資源,而線程本身的數據通常只有微處理器的寄存器數據,以及一個供程序執行時使用的堆棧
      1.3進程與線程的區別
      1. 進程:每個進程都有獨立的代碼和數據空間(進程上下文) ,tb進程切換的開銷大.
      2. 線程:輕量的進程,同一類線程共享代碼和數據空間,每個線程有獨立的運行棧和程序計數器(PC),線程切換的開銷小.
      3. 多進程:在操作系統中,能同時運行多個任務程序.
      4. 多線程:在同一應用程序中,有多個順序流同時執行.
      1.4線程創建的兩種方式
      采用繼承Thread類創建線程
      該方法比較簡單,主要是通過繼承java.lang.Thread類,并覆蓋Thread類的run()方法來完成線成的創建.Thread 類是一個具體的類,即不是抽象類,該類封裝了線程的行為.要創建一個線程,程序員必須創建一個從 Thread 類導出的新類.Thread類中有兩個最重要的函數run()和start().
      通過實現Runnable接口創建線程
      該方法通過生成實現java.lang.Runnable接口的類.該接口只定義了一個方法run(),所以必須在新類中實現它.但是 Runnable 接口并沒有任何對線程的支持,我們還必須創建 Thread 類的實例,這一點通過 Thread 類的構造函數
      public Thread(Runnable target);來實現.
      2 單線程和多線程性能比較
      以使用蒙特卡羅概率算法求π為例,進行單線程和多線程時間比較
      2.1什么是蒙特卡羅概率算法

      蒙特卡羅法(Monte Carlo method)是以概率和統計的理論、方法為基礎的一種計算方法,將所求解的問題同一定的概率模型相聯系,用電子計算機實現統計模擬或抽樣,以獲得問題的近似解,故又稱統計模擬法或統計試驗法. --百度百科
      蒙特卡羅求算法求π
      第一步
      畫正方形和內切圓
      第二步
      變換表達式
      正方形面積As=(2R)^2
      圓的面積Ac=πR^2
      Ac/As=(2R)^2/πR^2
      π=4As/Ac
      令P=As/Sc,則π=4P
      第三步
      重復N次實驗求平均值
      在正方形區域內隨機生成一個點A,若A落在圓區域內,M++
      P=M/N
      π=4P,N的取值越大,π的值越精確
      2.2 java代碼實現算法
      N取值為10000萬,多線程的數為100,每個線程執行100萬次模擬實驗
      線程實現
      import java.util.concurrent.CountDownLatch;
      public class ProModel implements Runnable {
      public int N;//隨機實驗的總次數
      public static int M;//隨機點落在圓中的次數
      private int id;
      private final CountDownLatch doneSignal;
      OBJ semaphore;
      public ProModel(int id,CountDownLatch doneSignal,int N,OBJ semaphore2){
      this.id=id;
      this.doneSignal=doneSignal;
      this.N=N;
      this.semaphore=semaphore2;
      M=0;
      }
      public void run(){
      int tempM=0;
      for(int i=0;i
      if(isInCircle()){
      tempM++;
      }
      }
      synchronized (semaphore) {
      add(tempM);
      }
      doneSignal.countDown();//使end狀態減1
      }
      public void add(int tempM){
      System.out.println(Thread.currentThread().getName());
      M=M+tempM;
      System.out.println(M);
      }
      //隨機產生一個在正方形區域的點,判斷它是否在圓中
      public boolean isInCircle(){
      double x=Math.random();
      double y=Math.random();
      if((x-0.5)*(x-0.5)+(y-0.5)*(y-0.5)<0.25)
      return true;
      else
      return false;
      }
      public static int getTotal(){
      return M;
      }
      }
      多線程Main實現
      import java.util.concurrent.CountDownLatch;
      import java.util.concurrent.ExecutorService;
      import java.util.concurrent.Executors;
      public class MutliThread {
      public static void main(String[] args) throws InterruptedException {
      long begin=System.currentTimeMillis();
      int threadSize=100;
      int N=1000000;
      OBJ semaphore = new OBJ();
      CountDownLatch doneSignal = new CountDownLatch(threadSize);
      ProModel[] pros=new ProModel[threadSize];
      //設置特定的線程池,大小為threadSizde
      System.out.println(“begins!”);
      ExecutorService exe = Executors.newFixedThreadPool(threadSize);
      for(int i=0;i
      exe.execute(new ProModel(i+1,doneSignal,N,semaphore));
      try{
      doneSignal.await(); //等待end狀態變為0, }catch (InterruptedException e) {
      // TODO: handle exception35
      e.printStackTrace();
      }finally{
      System.out.println(“ends!”);
      System.out.println(4*(float)ProModel.getTotal()/(float)(threadSize*N));
      }
      exe.shutdown();
      long end=System.currentTimeMillis();
      System.out.println(“used time(ms):”+(end-begin));
      }
      }
      class OBJ{}
      單線程Main實現
      import java.util.concurrent.CountDownLatch;
      import java.util.concurrent.ExecutorService;
      import java.util.concurrent.Executors;
      public class SingleThread {
      public static void main(String[] args) {
      long begin=System.currentTimeMillis();
      int threadSize=1;
      int N=100000000;
      OBJ semaphore = new OBJ();
      CountDownLatch doneSignal = new CountDownLatch(threadSize);
      ProModel[] pros=new ProModel[threadSize];
      //設置特定的線程池,大小為5
      System.out.println(“begins!”);
      ExecutorService exe = Executors.newFixedThreadPool(threadSize);
      for(int i=0;i
      exe.execute(new ProModel(i+1,doneSignal,N,semaphore));
      try{
      doneSignal.await(); //等待end狀態變為0, }catch (InterruptedException e) {
      // TODO: handle exception35
      e.printStackTrace();
      }finally{
      System.out.println(“ends!”);
      System.out.println(4*(float)ProModel.getTotal()/(float)(threadSize*N));
      }
      exe.shutdown();
      long end=System.currentTimeMillis();
      System.out.println(“used time(ms):”+(end-begin));
      }
      }

    posted @ 2013-08-23 16:54 chen11-1 閱讀(269) | 評論 (0)編輯 收藏

    Arrays.asList方法 學習記錄

    Arrays工具類提供了一些比較實用的方法,比如sort, binarySearch, fill等。其中還有一個asList方法,此方法能夠將一個變長參數或者數組轉換成List。
      但是,這個生成的List,它是固定長度的,如果對其進行add或者remove的操作,會拋出UnsupportedOperationException,為什么會這樣呢?
      帶著疑問,查看一下Arrays的源碼,可以得到問題的結果。
      Java代碼
      /**
      * Returns a fixed-size list backed by the specified array. (Changes to
      * the returned list "write through" to the array.) This method acts
      * as bridge between array-based and collection-based APIs, in
      * combination with Collection.toArray. The returned list is
      * serializable and implements {@link RandomAccess}.
      *
      *
      This method also provides a convenient way to create a fixed-size
      * list initialized to contain several elements:
      *
      * List stooges = Arrays.asList("Larry", "Moe", "Curly");
      *
      *
      * @param a the array by which the list will be backed.
      * @return a list view of the specified array.
      * @see Collection#toArray()
      */
      public static List asList(T... a) {
      return new ArrayList(a);

      方法asList返回的是new ArrayList(a)。但是,這個ArrayList并不是java.util.ArrayList,它是一個Arrays類中的重新定義的內部類。
      具體的實現如下:
      Java代碼
      /**
      * @serial include
      */
      private static class ArrayList extends AbstractList
      implements RandomAccess, java.io.Serializable
      {
      private static final long serialVersionUID = -2764017481108945198L;
      private Object[] a;
      ArrayList(E[] array) {
      if (array==null)
      throw new NullPointerException();
      a = array;
      }
      public int size() {
      return a.length;
      }
      public Object[] toArray() {
      return (Object[])a.clone();
      }
      public E get(int index) {
      return (E)a[index];
      }
      public E set(int index, E element) {
      Object oldValue = a[index];
      a[index] = element;
      return (E)oldValue;
      }
      public int indexOf(Object o) {
      if (o==null) {
      for (int i=0; i
      if (a[i]==null)
      return i;
      } else {
      for (int i=0; i
      if (o.equals(a[i]))
      return i;
      }
      return -1;
      }
      public boolean contains(Object o) {
      return indexOf(o) != -1;
      }
      }
      從這個內部類ArrayList的實現可以看出,它繼承了類AbstractList,但是沒有重寫add和remove方法,沒有給出具體的實現。查看一下AbstractList類中對add和remove方法的定義,如果一個list不支持add和remove就會拋出UnsupportedOperationException。
      Java代碼
      public abstract class AbstractList extends AbstractCollection implements List {
      /**
      * Sole constructor. (For invocation by subclass constructors, typically
      * implicit.)
      */
      protected AbstractList() {
      }
      /**
      * Appends the specified element to the end of this List (optional
      * operation).
      *
      * This implementation calls add(size(), o).
      *
      * Note that this implementation throws an
      * UnsupportedOperationException unless add(int, Object)
      * is overridden.
      *
      * @param o element to be appended to this list.
      *
      * @return true (as per the general contract of
      * Collection.add).
      *
      * @throws UnsupportedOperationException if the add method is not
      * supported by this Set.
      *
      * @throws ClassCastException if the class of the specified element
      * prevents it from being added to this set.
      *
      * @throws IllegalArgumentException some aspect of this element prevents
      * it from being added to this collection.
      */
      public boolean add(E o) {
      add(size(), o);
      return true;
      }
      /**
      * Inserts the specified element at the specified position in this list
      * (optional operation). Shifts the element currently at that position
      * (if any) and any subsequent elements to the right (adds one to their
      * indices).
      *
      * This implementation always throws an UnsupportedOperationException.
      *
      * @param index index at which the specified element is to be inserted.
      * @param element element to be inserted.
      *
      * @throws UnsupportedOperationException if the add method is not
      * supported by this list.
      * @throws ClassCastException if the class of the specified element
      * prevents it from being added to this list.
      * @throws IllegalArgumentException if some aspect of the specified
      * element prevents it from being added to this list.
      * @throws IndexOutOfBoundsException index is out of range (index <
      * 0 || index > size()).
      */
      public void add(int index, E element) {
      throw new UnsupportedOperationException();
      }
      /**
      * Removes the element at the specified position in this list (optional
      * operation). Shifts any subsequent elements to the left (subtracts one
      * from their indices). Returns the element that was removed from the
      * list.
      *
      * This implementation always throws an
      * UnsupportedOperationException.
      *
      * @param index the index of the element to remove.
      * @return the element previously at the specified position.
      *
      * @throws UnsupportedOperationException if the remove method is
      * not supported by this list.
      * @throws IndexOutOfBoundsException if the specified index is out of
      * range (index < 0 || index >= size()).
      */
      public E remove(int index) {
      throw new UnsupportedOperationException();
      }
      }
      至此,為什么Arrays.asList產生的List是不可添加或者刪除,否則會產生UnsupportedOperationException,就可以得到解釋了。
      如果我們想把一個變長或者數據轉變成List, 而且tb期望這個List能夠進行add或者remove操作,那該怎么做呢?
      我們可以寫一個類似的方法,里面直接采用java.util.ArrayList即可。
      比如:
      Java代碼
      import java.util.ArrayList;
      import java.util.Collections;
      import java.util.List;
      public class MyArrays {
      public static List asList(T... a) {
      List list = new ArrayList();
      Collections.addAll(list, a);
      return list;
      }
      }
      測試代碼如下:
      Java代碼
      import java.util.ArrayList;
      import java.util.Arrays;
      import java.util.List;
      public class Test {
      @SuppressWarnings("unchecked")
      public static void main(String[] args) {
      List stooges = Arrays.asList("Larry", "Moe", "Curly");
      print(stooges);
      List> seasonsList = Arrays.asList(retrieveSeasonsList());
      print(seasonsList);
      /*
      * 自己實現一個asList方法,能夠添加和刪除。
      */
      List list = MyArrays.asList("Larry", "Moe", "Curly");
      list.add("Hello");
      print(list);
      }
      private static void print(List list) {
      System.out.println(list);
      }
      private static List retrieveSeasonsList() {
      List seasonsList = new ArrayList();
      seasonsList.add("Spring");
      seasonsList.add("Summer");
      seasonsList.add("Autumn");
      seasonsList.add("Winter");
      return seasonsList;
      }
      }
      輸出結果:
      [Larry, Moe, Curly]
      [[Spring, Summer, Autumn, Winter]]
      [Larry, Moe, Curly, Hello]

    posted @ 2013-07-15 17:08 chen11-1 閱讀(236) | 評論 (0)編輯 收藏

    僅列出標題
    共20頁: 1 2 3 4 5 6 7 8 9 下一頁 Last 
    主站蜘蛛池模板: 亚洲嫩草影院久久精品| 亚洲精品国产成人片| 亚洲一区中文字幕在线电影网| 国产在线精品免费aaa片| 伊伊人成亚洲综合人网7777| 日韩少妇内射免费播放| 亚洲精品无码久久久| 一区二区三区免费视频观看| 亚洲情a成黄在线观看| 污视频网站免费在线观看| 国产一级高清免费观看| 美景之屋4在线未删减免费| 亚洲国产专区一区| 国产免费一级高清淫曰本片| 亚洲色偷偷偷鲁综合| 久久久久久影院久久久久免费精品国产小说| 国产亚洲AV夜间福利香蕉149| 天堂在线免费观看| 亚洲国产精品自在线一区二区| 麻豆高清免费国产一区| 亚洲色大成网站www久久九| 国产成人免费A在线视频| 国产免费A∨在线播放| 亚洲国产日韩一区高清在线| 日韩免费a级毛片无码a∨| 亚洲成AV人片高潮喷水| 在线观看午夜亚洲一区| 69视频在线观看高清免费| 亚洲AV永久无码精品网站在线观看 | 国产精品成人69XXX免费视频| 亚洲AV无码国产精品色午友在线 | 亚洲精品无码专区久久| 亚洲国产成人爱av在线播放| 国产成人免费ā片在线观看老同学 | 亚洲男人的天堂www| 国产在线观看麻豆91精品免费 | 成人免费观看一区二区| 精品亚洲视频在线| 亚洲AV日韩AV鸥美在线观看| 在线免费视频一区二区| 十八禁在线观看视频播放免费|