天天看點

java學習筆記-數組,對象的拷貝

 數組:

int[] num=new int[3];//聲明num變量在棧記憶體裡,new是在堆記憶體中給對象配置設定了空間

for(int i=0;i<num.length;i++)

{

         System.out.println(num[i]);

}

--------------------------------------------------------------

class Stringtest

{

      public static void main(String[] args)

      {

             Student[] students;

             students=new Student[3];

             students[0]=new Student("lisi",18);

             for(int i=0;i<students.length;i++)

             {

                      System.out.println(students[i]);

             }

class Student

{

      String name;

      int age;

      Student(String name,int age)

      {

             this.name=name;

             this.age=age;

      }

}

  數組的相關操作:

    在Java中,所有的數組都有一個預設的屬性length,用于擷取數組中元素的個數

    數組的複制:System.arraycopy()

        public static void arraycopy(Object src,int srcPos,Object dest,int destPos,int length)  Copies an array from the specified source array, beginning at the specified position, to the specified position of the destination array.

    數組的排序:Arrays.sort()

        在java.util包中。

    在已排序的數組中查找某個元素:Arrays.binarySearch(),傳回值為int型,是要查找的數組的索引

        如果是對對象排序的話sort(Object[] a),All elements in the array must implement the Comparable interface,接口Comparable在java.lang包下

---------------------------------------------------------------------------

import java.util.Arrays;

class ArrayTest1

{

      public static void main(String[] args)

      {

           Student[] ss=new Student[]{new Student("zs",18),

                                      new Student("ls",19),

                                      new Student("ww",20)};

           Arrays.sort(ss);

           int index=Arrays.binarySearch(ss,new Student("ls",19));

           System.out.println("index="+index);

           if (index > -1)

       {

          System.out.println(ss[index]);

       }

           else

    System.out.println("Not Exists");

      }

}

class Student implements Comparable

        int num;

        String name;

        Student(String name,int num)

        {

              this.num=num;

              this.name=name;

        }

        public String toString()

        {

            return "num="+num+","+"name="+name;

        }

        public int compareTo(Object o)

        {

              Student s=(Student)o;

              //int retsult=num>s.num ? 1 : (num==s.num ? 0 : -1);這是第一種比較方法,下面定義了第二種比較方法

              int  result=num>s.num ? 1 : (num==s.num ? 0 : -1);

              if (result==0)

              {

                       result=name.compareTo(s.name);

              }

              return result;

        }

}

------------------------------------------------------------------------------------

  main函數:

    public static void main(String[] args)//String是除了那8中以外的類型,是以是引用數組,一開始args并沒有被配置設定空間,它是用來接受指令行參數的。比如在指令行裡輸入java calssname OtherWords,那麼在args裡就會儲存OtherWords的内容

    注:數組本身就是引用類型     如何交換int x,int y的值,而不利用第三個變量:x=x+y;y=x-y;x=x-y;     函數的調用:在Java中,傳參時,都是以傳值的方法進行。對于基本資料類型,傳遞的數組的拷貝;對于引用類型,傳遞的是引用的拷貝     在列印(System.out.println)一個對象的時候,會自動調用這個對象的toString()方法,原Object類中的toString()方法Returns a string representation of the object.It is recommended that all subclasses override this method.     對象的克隆:

    為了擷取對象的一份拷貝,我們可以利用Object類的clone()方法

    在派生類中覆寫基類的clone()方法,并聲明為public(因為在Object類中該方法是protected)

    在派生類的clone()方法中,調用super.clone()。在運作時刻,Object中的clone()識别出你要複制的是哪一個對象,然後為此對象配置設定空間,并進行對象的複制,将原始對象的内容一一複制到新對象的存儲空間中

    在派生類中實作Cloneable接口(沒有任何抽象方法,隻是為了告訴編譯器這個對象可以克隆),否則調用clone()方法會抛出CloneNotSupportedException異常

    如果被克隆的對象的資料成員中含有對象,那麼就需要作深層次的克隆才能将作為資料成員的對象克隆,否則是把對象變量的值進行了拷貝,即隻是把作為資料成員的對象的引用(位址)進行了拷貝。作深層次的克隆,就是要讓作為資料成員的對象所屬的類也覆寫clone()方法,并且實作Cloneable接口(與被克隆的對象所屬的類中的實作方法同)

class Student implements Cloneable

{

      String name;

      int age;

      Student(String name,int age)

      {

             this.name=name;

             this.age=age;

      }

      public Object clone()

      {

             Object o=null;

             try

             {

             o=super.clone();//super.clone()傳回的是Object類,根據需要可進行強制類型轉換

             }

             catch(CloneNotSupportedException e)

             {

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

             }

             return o;

      }

}

  封裝類:(有時函數參數是引用類型,但我們又要傳遞基本資料類型)

針對八種基本資料類型定義的相應的引用類型——封裝類(在java.lang包中定義的,基本資料類型與封裝類建立對應關系之後,封裝類就是隻讀類,不能改變)          基本資料類型                  封裝類

            boolean                    Boolean

             byte                       Byte

            short                       Short

             int                       Integer

             long                       Long

             char                     Character

             float                      Float

            double                     Double

--------------------------------------------------------------------

class Test

{

    public  static void main(String[] args)

    {

        int i=3;

        Integer in=new Integer(i);//Integer的一個構造函數Integer(int value)

        int j=in.intValue();//int intValue()  Returns the value of this Integer as an int

        System.out.println("j="+j);

        String str=in.toString();//String toString() Returns a String object representing this Integer's value.

        System.out.println("str="+str);

        String str1="134";//String要是數字類型的

        System.out.println(Integer.valueOf(str1));//static Integer valueOf(String s) Returns an Integer object holding the value of the specified String.

        //static int parseInt(String s) Parses the string argument as a signed decimal integer. 

    }  

}

  Class類(在java.lang包中,Instances of the class Class represent classes and interfaces in a running Java application):

    在Java中,每個class都有一個相應的Class對象。也就是說,當我們編寫一個類,編譯完成後,在生成的.class檔案中,就會産生一個Class對象,用于表示這個類的類型資訊

    擷取Class執行個體的三種方式:

      (1)利用對象調用getClass()方法擷取該對象的Class執行個體;

      (2)使用Class類的靜态方法forName(),用類的名字擷取一個Class執行個體(static Class forName(String className)  Returns the Class object associated with the class or interface with the given string name. );

      (3)運用.class的方式來擷取Class執行個體,對于基本資料類型的封裝類,還可以采用.TYPE來擷取相對應的基本資料類型的Class執行個體

    在newInstance()調用類中預設的構造方法 Object newInstance()(可在不知該類的名字的時候,常見這個類的執行個體)  Creates a new instance of the class represented by this Class object.

    在運作期間,如果我們要産生某個類的對象,Java虛拟機(JVM)會檢查該類型的Class對象是否已被加載。如果沒有被加載,JVM會根據類的名稱找到.class檔案并加載它。一旦某個類型的Class對象已被加載到記憶體,就可以用它來産生該類型的所有對象 ----------------------------------------------------------------------------------------------------

//擷取Class執行個體的三種方式:

class ClassTest

{

       public static void main(String[] args)

       {

             Point pt=new Point();

             Class c1=pt.getClass();

             System.out.println(c1.getName());// String getName() Returns the name of the entity (class, interface, array class, primitive type, or void) represented by this Class object, as a String.

             try

             {

                      Class c2=Class.forName("Point");//static Class forName(String className) throws ClassNotFoundException  Returns the Class object associated with the class or interface with the given string name.

                  System.out.println(c2.getName());

             }

             catch(Exception e)

             {

                   e.printStackTrace();

             }

             Class c3=Point.class;

             System.out.println(c3.getName());

             Class c4=int.class;

             System.out.println(c4.getName());

             Class c5=Integer.TYPE;

             System.out.println(c5.getName());

             Class c6=Integer.class;

             System.out.println(c6.getName());

       } 

}

class Point

{

   int x,y; 

}

----------------------------------------------------------------------------

//newInstance()調用類中預設的構造方法:

class anClassTest

{

       public static void main(String[] args)

       {

        if(args.length!=1)

        {

            return;

        }

        try

        {

            Class c=Class.forName(args[0]);

            Point pt=(Point)c.newInstance();

            pt.output();

        }

        catch(Exception e)

        {

            e.printStackTrace();

        }

       }

}

class Point

{

   int x,y;

   void output()

   {

       System.out.println("x="+x+",y="+y); 

   } 

}

class Line

{

   int length,x,y;

   void output()

   {

       System.out.println("length="+length+",x="+x+",y="+y); 

   } 

}

?The Reflection API represents,or reflects,the classes,interfaces,and objects in the current Java Virtual Machine.在java.lang.reflect包裡

  Runtime類(在java.lang包中定義)和Process類

    每一個Java程式都有一個Runtime類的單一執行個體

    通過Runtime.getRuntime()擷取Runtime類的執行個體

    Runtime類是使用單例模式的一個例子 import java.io.*;

class RuntimeTest

{

    public static void main(String[] args)

    {

         Runtime rt=Runtime.getRuntime();

         System.out.println(rt.freeMemory());//long freeMemory():Returns the amount of free memory in the Java Virtual Machine.

         System.out.println(rt.totalMemory());// long totalMemory():Returns the total amount of memory in the Java virtual machine.

         try

         {

                  rt.exec("notepad");//Process exec(String command):Executes the specified string command in a separate process.

                  Process p=rt.exec("java anClassTest Point");//現在p就表示java anClassTest這個子程序。類似這種可做圖形調用工具

                  InputStream is=p.getInputStream();

                  int data;

                  while((data=is.read())!=-1)

                  {

                       System.out.print((char)data); 

                  } 

         }

         catch(Exception e)

        {

            e.printStackTrace();

        }

    }

}

  設計模式:在我們進行程式設計時,逐漸形成了一些典型問題和問題的解決方案,這就是軟體模式。每一個模式描述了一個在我們程式設計中經常發生的問題,以及該問題的解決方案。當我們碰到模式所描述的問題,就可以直接用相應的解決方法去解決這個問題,這就是設計模式

  單例模式:

    (1)一個類隻有一個執行個體,而且自行執行個體化并向這個系統提供這個執行個體,這個類成為單例類

    (2)單例類的一個重要的特點就是類的構造方法是私有的,進而避免了外部利用構造方法直接創造多個執行個體

  單例類的實作(比如設計計數器,還有Runtime這個類):

  class Singleton

  {

       private static final Singleton st=new Singleton();//因為為static final,是以在類加載的時候就構造了這個執行個體

       private Singleton(){};

       public static Singleton getInstance()

       {

               reture st;

       }