Java數組擴容算法及Java對它的應用

  Java數組擴容的原理java

  1)Java數組對象的大小是固定不變的,數組對象是不可擴容的。算法

  2)利用數組複製方法能夠變通的實現數組擴容。編程

  3)System.arraycopy()能夠複製數組。數組

  4)Arrays.copyOf()能夠簡便的建立數組副本。性能優化

  5)建立數組副本的同時將數組長度增長就變通的實現了數組的擴容。app

 

  源碼展現:ide

1 public class Arrays {
 2     /**
 3      * @param original: the array to be copied
 4      * @param newLength: the length of the copy to be returned
 5      * @return a copy of the original array, truncated or padded with zeros
 6      *     to obtain the specified length
 7      */
 8     public static int[] copyOf(int[] original, int newLength) {
 9         int[] copy = new int[newLength];
10         System.arraycopy(original, 0, copy, 0,
11                          Math.min(original.length, newLength));
12         return copy;
13     }
14     /**
15      * @param original the array from which a range is to be copied
16      * @param from the initial index of the range to be copied, inclusive
17      * @param to the final index of the range to be copied, exclusive.
18      *     (This index may lie outside the array.)
19      * @return a new array containing the specified range from the original array,
20      *     truncated or padded with zeros to obtain the required length
21      */
22     public static int[] copyOfRange(int[] original, int from, int to) {
23         int newLength = to - from;
24         if (newLength < 0)
25             throw new IllegalArgumentException(from + " > " + to);
26         int[] copy = new int[newLength];
27         System.arraycopy(original, from, copy, 0,
28                          Math.min(original.length - from, newLength));
29         return copy;
30     }
31 }

 

  示例說明:性能

1 import java.util.Arrays;
 2 
 3 /** 數組變長算法! 
 4  * 數組對象長度不可改變
 5  * 可是不少實際應用須要長度可變的數組
 6  * 能夠採用複製爲容量更大的新數組, 替換原數組, 實現變長操做
 7  * */
 8 public class ArrayExpand {
 9     public static void main(String[] args) {
10         //數組變長(擴容)算法! 
11         int[] ary={1,2,3};
12         ary=Arrays.copyOf(ary, ary.length+1);
13         ary[ary.length-1]=4;
14         System.out.println(Arrays.toString(ary));//[1, 2, 3, 4]
15         //字符串鏈接原理
16         char[] chs = { '中', '國' };
17         chs = Arrays.copyOf(chs, chs.length + 1);
18         chs[chs.length - 1] = '北';
19         chs = Arrays.copyOf(chs, chs.length + 1);
20         chs[chs.length - 1] = '京';
21         //字符數組按照字符串打印
22         System.out.println(chs);//中國北京
23         //其餘數組按照對象打印
24         System.out.println(ary);//[I@4f1d0d
25     }
26 }

 

  實現案例:優化

  案例1 : 統計一個字符在字符串中的全部位置.
  字符串: 統計一個字符在字符串中的全部位置
  字符: '字'
  返回: {4,7}ui

1 public class CountCharDemo {
 2     public static void main(String[] args) {
 3         char key = '字';
 4         String str = "統計一個字符在字符串中的全部位置";
 5         int[] count=count(str,key);
 6         System.out.println(Arrays.toString(count));//[4, 7]
 7     }
 8     public static int[] count(String str,char key){
 9         int[] count={};
10         for(int i=0;i<str.length();i++){
11             char c=str.charAt(i);
12             if(c==key){
13                 //擴展數組
14                 count=Arrays.copyOf(count, count.length+1);
15                 //添加序號i
16                 count[count.length-1]=i;
17             }
18         }
19         return count;
20     }
21 }

 

  char[]、String、StringBuilder

  char[]:字符序列, 只有字符數據, 沒有操做, 若是算法優秀, 性能最好。

  String: char[] + 方法(操做, API功能)
  StringBuilder: char[] + 方法(操做char[] 的內容)

  String:內部包含內容不可變的char[],表現爲String對象不可變。String包含操做(API方法),是對char[]操做,但不改變原對象常常返回新的對象,不少String API提供了複雜的性能優化算法,如:靜態字符串池。

  StringBuilder:內部也是一個char[],可是這個數組內容是可變的,而且自動維護擴容算法,由於數據內容可變,因此叫:可變字符串。StringBuilder API方法,是動態維護char[]內容,均可以改變char[]內容。

1 public abstract class AbstractStringBuilder {
 2     /** The value is used for character storage.*/
 3     char value[];
 4     /** The count is the number of characters used.*/
 5     int count;
 6     /** Returns the length (character count).*/
 7     public int length() {
 8         return count;
 9     }
10     
11     public AbstractStringBuilder append(String str) {
12         if (str == null)
13             str = "null";
14         int len = str.length();
15         if (len == 0)
16             return this;
17         int newCount = count + len;
18         if (newCount > value.length)
19             expandCapacity(newCount);
20         str.getChars(0, len, value, count);
21         count = newCount;
22         return this;
23     }
24     
25     /**
26      * 自動實現Java數組擴容
27      */
28     void expandCapacity(int minimumCapacity) {
29         int newCapacity = (value.length + 1) * 2;
30         if (newCapacity < 0) {
31             newCapacity = Integer.MAX_VALUE;
32         } else if (minimumCapacity > newCapacity) {
33             newCapacity = minimumCapacity;
34         }
35         value = Arrays.copyOf(value, newCapacity);
36     }
37 }

 

  字符串數組與String類的原理

1 /** 字符串數組與String類的原理 */
 2 public class CharArrayDemo {
 3     public static void main(String[] args) {
 4         /* Java 能夠將char[]做爲字符串處理 */
 5         char[] ch1={'中','國','北','京'};
 6         char[] ch2={'歡','迎','您'};
 7         System.out.println(ch1);//中國北京
 8         System.out.println(ch2);//歡迎您
 9         /* char[]運算須要編程處理,如鏈接: */
10         char[] ch3=Arrays.copyOf(ch1, ch1.length+ch2.length);
11         System.arraycopy(ch2, 0, ch3, ch1.length, ch2.length);
12         System.out.println(ch3);//中國北京歡迎您
13         /* String API提供了簡潔的鏈接運算: */
14         String str1="中國北京";
15         String str2="歡迎您";
16         String str3=str1.concat(str2);
17         System.out.println(str3);//中國北京歡迎您
18         /* 字符串轉大寫: */
19         char[] ch4={'A','a','c','f'};
20         char[] ch5=Arrays.copyOf(ch4, ch4.length);
21         for(int i=0;i<ch5.length;i++){
22             char c=ch5[i];
23             if(c>='a' && c<='z'){
24                 ch5[i]=(char)(c+('A'-'a'));
25             }
26         }
27         System.out.println(ch5);//AACF, 原數組ch4不變
28         String str4="Aacf";
29         String str5=str4.toUpperCase();//原字符串str4保持不變
30         System.out.println(str5);//AACF
31     }
32 }
相關文章
相關標籤/搜索