天天看點

JAVA之StringBuilder函數 包裝類詳解JAVA函數之StringBuffer 單例

JAVA函數之StringBuffer 單例

Arrays

String[] array = {"sd","wa","er","wqf","yhg"};
Arrays.sort(array);   //對array數組進行排序

System.out.println(Arrays.toString(array));   //輸出array數組中得元素

int[] array = {,,,,,,,,};
int temp = Arrays.binarySearch(array,);   //二分折半查找
System.out.println(temp);
           

單例

單執行個體–設計思想

核心:在整個程式執行期間 有且隻有一個該類的對象存在


音樂(QQ 蝦米 酷狗)
前台播放 背景播放 都是用一個音樂播放器


如何去寫?
如何去保證 程式中有且隻有一個對象
1.不讓外界 來建立對象
2.這個對象我來建立(也不能讓外界通路)
3.需要對外開放通路這個對象的方法
           
//  餓漢式   建立單例對象
//  這個對象随着類的加載而加載
class Single{
    private static  Single single = new Single();
    //  構造方法私有化
    private Single(){

    }
    //  開放一個通路這個對象的方法
    public static Single getSingle(){
        return single;
    }
}


//  懶漢式(隻有當你在調用擷取對象的方法時  才有可能去建立對象)
//  延遲加載
class Single{
    //  建立單例對象 引用
    private static Single single = null;
    //  構造方法私有化
    private Single(){

    }
    //  擷取單例對象的私有方法
    public static Single getSingle(){
    //  判斷 如果沒有這個對象 你就建立 有舊不建立直接傳回
        if(single == null){
            single = new Single();
        }
        return single;
    }
}
           

StringBuffer(字元串緩沖區)

特點

jdk1.5之前 StringBuilder(線程不安全 省資源)
1.StringBuffer相當于一個可變的字元序列(操作的是原字元串)
2.是線程安全的(耗費資源)
           
1.拼接字元串
public static void fun1(){
    StringBuffer stringBuffer = new StringBuffer();
    //  擷取容量(理論)   預設值 16
    System.out.println(stringBuffer.capacity());
    //  擷取長度
    System.out.println(stringBuffer.length());
    //  轉化字元串
    System.out.println(stringBuffer.toString());
    //  拼接字元串
    System.out.println(stringBuffer.append("wanglong"));

}
           
2.插入 修改 字元 字元串
public static void fun2(){
    //  直接使用字元串建立stringBuffer
    StringBuffer stringBuffer = new StringBuffer("wanglong");
    //  插入一個字元 把字元插入到索引的位置
    //  插入boolean類型  就相當于把true或者false插入
    stringBuffer.insert(,'c');
    System.out.println(stringBuffer);  //輸出結果:wacnglong
    stringBuffer.insert(,true);   
    System.out.println(stringBuffer);  //輸出結果:watruecnglong
    //  給索引位置 進行字元修改(替換)
    stringBuffer.setCharAt(,'c');
    System.out.println(stringBuffer);  //輸出結果:wacglong
    //  注意:插入字元和字元修改的時候不能越界
    //  傳入角标 傳回字元
    char c = stringBuffer.charAt();
    System.out.println(c);   //輸出結果:g
    //  stringBuffer 轉字元數組
    //  方法:stringBuffer先轉為字元串再轉為字元數組
    char[] array = stringBuffer.toString().toCharArray();
}
           
3.删除 反轉字元串
public static void fun3(){
    StringBuffer stringBuffer  = new StringBuffer();
    //  删除(删頭不删尾)
    stringBuffer.appeand("wanglong");
    //  删除某一個下标的字元
    stringBuffer.deleteCharAt();
    System.out.println(stringBuffer);  //輸出結果:wanlong
    //  删除某一段字元串  
    //  注意開始下标不能越界   結束下标越界 系統當清空處理
    stringBuffer.delete(,);   //輸出結果:wong
    //  反轉字元串
    stringBuffer.reverse();
    System.out.println(stringBuffer);   //輸出結果:gnolgnaw
}
           
4.從鍵盤輸入一個字元串反轉
public static void fun4(){
    Scanner sc = new Scanner(System.in);
    String string = sc.nextLine();
    StringBuffer stringBuffer = new StringBuffer(string);
    stringBuffer.reverse();
    String str = stringBuffer.toString();
    System.out.println(str);
}
           
5.按要求輸出數組
/*
         * 需求
         * 把int[] array = new int[]{,,,};
         * 輸出 [, , , ];
         * 要求:使用兩種方法(String 和 StringBuffer)
         */
           
public static void fun5(){
    int[] array = new int[]{,,,};
    String string = "[";
    for(int i = ; i < array.length; i++){
        if(i != array.length - ){
            string = string + array[i];
            string = string + ",";
        }else{
            string = string + array[i] + "]";
        }
    }
    System.out.println(string);
}
           
public static void fun6(){
    int[] array = new int[]{,,,};
    StringBuffer stringBuffer = new StringBuffer("[");
    for(int i = ; i < array.length; i++){
        if(i != array.length - ){
            stringBuffer.append(array[i]).append(",");
        }else{
            stringBuffer.append(array[i]).append("]");
        }
    }
    System.out.println(stringBuffer);
}
           
6.替換字元串
public static void fun7(){
    StringBuffer stringBuffer = new StringBuffer();
    stringBuffer.append("wanglong");
    stringBuffer.replace(,,"Li");
    System.out.println(stringBuffer);
}
           

string 和 stringBuffer當參數的差別

測試字元串當參數的方法
字元串當參數的時候 跟基本資料類型作為參數一樣是值得傳遞

StringBuffer作為參數的時候 跟引用資料類型一樣 相當于位址的傳遞
           
public static void fun8(String string){
    string = "wanglong";
}
public static void fun9(StringBuffer stringBuffer){
    stringBuffer.append("znb");
}
public static void main(String[] args){
    String string = "xxxxx";
    fun8(string);
    System.out.println(string);   //結果:xxxxx


    StringBuffer sb = new StringBuffer(string);
    fun9(sb);
    System.out.println(sb);   //結果:xxxxxznb
}
           

總結

StringBuffer 和 StringBuilder 差別
StringBuffer  線程安全 效率低
StringBuilder 線程不安全 效率高(相對于StringBuffer耗費資源少)
StringBuilder  StringBuffer 使用方法一樣
           
string 和 stringBuffer的差別
String是不可變的 線程不安全
StringBuffer是可變的 操作的是對象本身
作為參數的差別
           

包裝類

基本資料類型 包裝類
byte      Byte
short     Short
int       Interger
long      Long
float     Float
double    Double
boolean   Boolean
char      Chracter

為什麼要把基本資料類型 封裝成一個類
在類中可以聲明方法 可以使用對象調用方法
           

Integer類中得方法

public static void fun1(){
    Integer integer1 = new Integer();
    System.out.println(integer1);    //結果:10
    //  把字元串轉化為數字類型
    //  注意是數字格式字元串 才能轉換
    Integer integer2 = new Integer("100");
    System.out.println(integer2);   //結果:100

    int a = ;
    //  轉二進制 轉八進制 轉十六進制
    System.out.println(Integer.toBinaryString(a));   //結果:1010000
    System.out.println(Integer.toOctalString(a);    //結果:120
    System.out.println(Integer.toHexString(a));    //結果:50

    //  int和Integer之間的轉換 靜态方法
    Integer num1 = Integer.valueOf();
    //  把integer類型轉換成int類型
    int num2 = num1.intValue();

    //  string和integer之間的轉換
    Integer num3 =Integer.valueOf("100");
    String string3 = num3.toString();

    //把字元串轉換為int
    int num4 = Integer.parseInt("100");
}
           

裝箱與拆箱

Integer num1 = ;
//  這樣聲明相當于Integer.value()
//  系統會幫你自動裝箱 調用這個方法
//  初值不要給null 避免計算中出現錯誤
Integer num2 = Integer.valueOf();
//如果 num1 =null時 系統會幫你null進行拆箱 轉換回了int類型
//相當于調用了num1.intValue
int rel = num1 + ;
System.out.println(rel);
           

整型相等解析

Integer num3 = ;
Integer num4 = ;
System.out.println(num3 == num4);    //結果為:false

Integer num5 = ;
Integer num6 = ;
System.out.println(num5 == num6);    //結果為:true

Integer num7 = new Integer();     
Integer num8 = new Integer();
System.out.println(num7 == num8);    //結果為:false
           

原因:

當自己沒有手動new一個對象的時候,系統會自動調用Integer.valueOf(num)方法自動幫你裝箱
打開valueOf方法顯示如下代碼

private static class IntegerCache {
        static final int low = -;
        static final int high;
        static final Integer cache[];

        static {
            // high value may be configured by property
            int h = ;
            String integerCacheHighPropValue =
                sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
            if (integerCacheHighPropValue != null) {
                try {
                    int i = parseInt(integerCacheHighPropValue);
                    i = Math.max(i, );
                    // Maximum array size is Integer.MAX_VALUE
                    h = Math.min(i, Integer.MAX_VALUE - (-low) -);
                } catch( NumberFormatException nfe) {
                    // If the property cannot be parsed into an int, ignore it.
                }
            }
            high = h;

            cache = new Integer[(high - low) + ];
            int j = low;
            for(int k = ; k < cache.length; k++)
                cache[k] = new Integer(j++);

            // range [-128, 127] must be interned (JLS7 5.1.7)
            assert IntegerCache.high >= ;
        }

        private IntegerCache() {}
    }

public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
}

由以上代碼可知low的值為-,high的值等于h等于,如果 (i >= IntegerCache.low && i <= IntegerCache.high),
這時會傳回cache數組中的一個對象,否則會建立一個新的對像傳回去,如果系統封裝的兩個相等數,
且都在IntegerCache.low=- 與 IntegerCache.high=範圍内,這時會傳回Cache數組中相同角标内的内容(對象),
當在這個範圍内時,系統早已存在一個數組,數組長度為(high - low)的值,即^,
根據代碼for(int k = ; k < cache.length; k++){ cache[k] = new 
Integer(j++);},j=low=-,可以看出下标從開始一直到,分别儲存着之-到的對象,即下标
為的數裡儲存的對象的值是,再根據public static Integer valueOf(int 
i)得到i的值,由return IntegerCache.cache[i + (-IntegerCache.low)]可知
傳回去的的數組下标為i + (-IntegerCache.low),假設i是127,則127+(-128)得255
即cache數組的下标為255中的内容,即為要傳回去的内容,内容為 cache[k] = new
Integer(j++),即new Integer();當再封裝一個的時候,傳回的仍然是這個
new Integer(),是以位址相同,即不同引用指向同一個對象,所已結果為true
           

權限修飾符

本類 同包類 同包子類 不同包類 不同包子類
  public    √     √     √        √        √
  private   √     ×     ×        ×        ×
  protected √     √     √        ×        √
  default   √     √     √        ×        ×
           

繼續閱讀