天天看点

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   √     √     √        ×        ×
           

继续阅读