美文网首页
Java数组算法(实用)

Java数组算法(实用)

作者: 晏子小七 | 来源:发表于2017-12-11 15:42 被阅读10次
    图片.png

    数组知识导图


    数组拷贝:
    public class ShuZuTest {

    //这样拷贝数组间没有隔离性
    public static void test1(){
        String[] ss1 = {"1","2","3"};
        //把ss1对数组的引用传递给变量ss2,两个便令指向的是同一个数组
        String[] ss2 =ss1;
        ss2[0] = "张三";
        System.out.println(ss1[0]);//张三
    }
    
    //推荐
    public static void test2(){
        String[] ss1 = {"1","2","3"};
        //通过new关键字在内存中开辟一块空间,ss2指向的是行的数组对象
        String[] ss2 = new String[ss1.length];
        for(int i = 0;i<ss2.length;i++){
            ss2[0] = "张三";
            System.out.println(ss1[0]);//1
        }
        
    }
    public static void test4(){
        String[] ss1 = {"1","2","3"};
        String[] ss2 =Arrays.copyOf(ss1, ss1.length);
        System.out.println(Arrays.toString(ss2));//[1,2,3]
    }
    
    //=========================================================
    //数组扩容:
    public static void test5(){
        String[] array1 = {"1","2","3"};
        array1 = Arrays.copyOf(array1, array1.length+2);
        System.out.println(Arrays.toString(array1));//[1,2,3,null,null]
    }
    //例子:统计字符的位置
    public static void test6(){
        String str = "统计一个字符串的位置而已";
        int[] ary = countAll(str, '符');//
        System.out.println(Arrays.toString(ary));
    }
    public static int[] countAll(String str,char ch){
        int[] array = {};//创建一个空数组
        for(int i=0;i<str.length();i++){
            if(ch == str.charAt(i)){
                array = Arrays.copyOf(array, array.length+1);
                array[array.length-1] = i;
            }
        }
        return array;
    }
    

    }

    相关文章

      网友评论

          本文标题:Java数组算法(实用)

          本文链接:https://www.haomeiwen.com/subject/bnbiixtx.html