java study notes 11: StringBuffer and StringBuilder class, Arrays class

First, FIG Mind

Here Insert Picture Description

Second, the specific code implementation

1, StringBuffer add delete function

public class MyTest {
    public static void main(String[] args) {
        //StringBuffer 一个容器,你可以不断的往容器中追加内容
        StringBuffer sb = new StringBuffer();
        // append("年后"); 往容器中追加内容,返回的还是原来这个对象
        sb.append("abc");
        StringBuffer sb2 = sb.append(100).append(true).append('c').append("年后");//输出:abc100truec年后
        //在指定索引出的前面插入内容,返回的还是原来的缓冲区对象
        StringBuffer sb3 = sb2.insert(3, "你好");//输出:abc你好100truec年后
        //删除指定索引的一段字符,含头不含尾
        StringBuffer sb4 = sb3.delete(0,3);//你好100truec年后
        String s = sb.toString(); //StringBuffer重写了toString()方法,把存在容器中的数据,转成字符串类型
        System.out.println(s);
    }
}

2, StringBuffer alternative inversion function

public class MyTest2 {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer("abcdefd");
        StringBuffer sb2 = sb.replace(0, sb.length(), "我爱java!");
        System.out.println(sb2.toString());
        StringBuffer stringBuffer = new StringBuffer();
        StringBuffer sb3 = stringBuffer.append("abcde");
        //reverse() 反转容器中的数据 返回的还是字符串缓冲区本身
        String s = sb3.reverse().toString();
        System.out.println(s);
    }
}

3, StringBuffer intercept function

public class MyTest3 {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer("我爱学习java");
        //根据指定的索引 截取容器中的数据 注意返回的是截取到的字符串,不再是它本身。
        String s = sb.substring(2);
        System.out.println(s);//学习java
        String s1 = sb.substring(0, 4); //含头不含尾
        System.out.println(s1);//我爱学习
    }
}

4, an array of tools to sort of function

public class MyTest3 {
    public static void main(String[] args) {
        Integer[] arr = {101, 20, 302, 405, 507, 600, 702, 80, 90, 100};
        //从小到大
        Arrays.sort(arr);
        System.out.println(Arrays.toString(arr));
        //从大到小
        Arrays.sort(arr, new Comparator<Integer>() {
            @Override
            public int compare(Integer a, Integer b) {
                return -(a - b);
            }
        });
        System.out.println(Arrays.toString(arr));
    }
}
输出:
     [20, 80, 90, 100, 101, 302, 405, 507, 600, 702]
     [702, 600, 507, 405, 302, 101, 100, 90, 80, 20]

5, an array of binary search tools

public class MyTest4 {
    public static void main(String[] args) {
    //二分查找的前提是数组必须有序。
    int[] arr = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100};
        int index = Arrays.binarySearch(arr, 90);//返回查找元素的索引
        System.out.println(index);
   }
}
Published 24 original articles · won praise 11 · views 2056

Guess you like

Origin blog.csdn.net/weixin_43791069/article/details/86836241