数组常用API

数组常用的API

首先import java.util.Arrays;

Arrays.asList()

将数组转换为列表


import java.util.Arrays;
import java.util.List;

public class stringAPi {
    public static void main(String[] args) {
        String[] strArray = {"huhuhu", "lilili", "foxfox"};
        List<String> list = Arrays.asList(strArray);
        // 将字符串打印
        for(int i=0; i<list.size(); i++) {
            System.out.print(list.get(i) + " ");
        }
    }
}

 Arrays.copyOf()



import java.util.Arrays;

//复制长度大于原数组长度时,后面补零
public class copyOf {
    public static void main(String[] args) {
        int[] arr={1,3,5,7};
        int[] copyOne= Arrays.copyOf(arr,3);
        int[] copyTwo=Arrays.copyOf(arr,7);
        //打印
        for(int item:copyOne){
            System.out.println(item + " ");
        }
        for(int item:copyTwo){
            System.out.println(item + " ");
        }
    }

}

Arrays.binarySearch()



import java.util.Arrays;

//对数组进行二分查找
public class binarySearch {
    public static void main(String[] args) {
        int[] arr={1,4,3,6,77,234,52};
        String[] arr2={"sS","ada","wwee"};
        //二分查找之前保证数组的顺序
        Arrays.sort(arr);
        Arrays.sort(arr2);
        int ind1=Arrays.binarySearch(arr,77);
        int ind2=Arrays.binarySearch(arr,1);
        int ind3=Arrays.binarySearch(arr2,"sS");
        int ind4=Arrays.binarySearch(arr2,"wwee");
        System.out.println("数字77的位置" + ind1);
        System.out.println("数字1的位置" + ind2);
        System.out.println("字符sS的位置" + ind3);
        System.out.println("字符wwee的位置" + ind4);
    }
}

 Arrays.hashCode()



import java.util.Arrays;

public class hashCodeTest {
    public static void main(String[] args) {
        int[] a = {1,2,3,4,5,6};
        int[] b = {1,2,3,4,5,6};
        String[] c = {"a", "b", "c"};
        String[] d = {"a", "b", "c"};

        System.out.println("a==b:" + Arrays.equals(a, b));
        System.out.println("a和b的哈希码分别为:" + Arrays.hashCode(a) + "\t" + Arrays.hashCode(b));
        // 字符串
        System.out.println("c==d:" + Arrays.equals(c, d));
        System.out.println("c和d的哈希码分别为:" + Arrays.hashCode(c) + "\t" + Arrays.hashCode(d));

        System.out.println("c==d:" + c.equals(d));
        System.out.println("c和d的哈希码分别为:" + c.hashCode() + "\t" + d.hashCode());
    }
}

Arrays.fill()



import java.util.Arrays;

public class fillTest {
    public static void main(String[] args) {
        int[] a = {1,2,3,4,5,6};
        Arrays.fill(a, 8);//全部填充
        for (int item : a)
            System.out.print(item + " ");
        System.out.println();
        Arrays.fill(a, 1, 3, 0);//指定范围,替换
        for (int item : a)
            System.out.print(item + " ");
    }
}

 

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页