6.4.1遍历数组
可以用for或者foreach
int a[][]= {{1},{2,3},{4,5,6}}; for (int[] is : a) { for (int is2 : is) { System.out.print(is2); } System.out.println(); }
6.4.2填充替换数组元素 Arrays.fill()
public static void fill(int[] a, int var)
public static void fill(int[] a, form, to, int var)
- a--数组
- form--替换开始位置(包括)
- to--替换结束位置(不包括)
- var--要替换的值
import java.util.Arrays; int a[]= {1,2,3,4,5,6,7,8}; Arrays.fill(a,8); for (int is : a) { System.out.print(is); } //88888888
public class Test { public static void main(String[] args) { int[] a = new int[]{1,2,3,4,5,6}; System.out.println(Arrays.toString(a)); //{1,2,3,4,5,6} Arrays.fill(a, 0); System.out.println(Arrays.toString(a)); //{0,0,0,0,0,0} int[] b = new int[]{1,2,3,4,5,6}; Arrays.fill(b, 2, 4, 0); System.out.println(Arrays.toString(b)); //{1,2,0,0,5,6} Boolean[] c = {true,false}; System.out.println(Arrays.toString(c)); //{true,false} Arrays.fill(c, false); System.out.println(Arrays.toString(c)); //{false,false} Arrays.fill(c, 0, 1, true); System.out.println(Arrays.toString(c)); //{true,false} String[] d = {"a","b","c","d","e","f"}; System.out.println(Arrays.toString(d)); //{a,b,c,d,e,f} Arrays.fill(d, 1, 2, "HelloWorld"); System.out.println(Arrays.toString(d)); //{a,HelloWorld,c,d,e,f} } }
6.4.3对数组进行排序 Arrays.sort()
int a[]= {1,5,6,7,8,9,3,2,4,0}; Arrays.sort(a); System.out.print(Arrays.toString(a)); //[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
6.4.4复制数组
Arrays.copyOf (需要进行复制的数组,新数组的长度)
int a[]= {1,5,6,7,8,9,3,2,4,0}; int b[] =Arrays.copyOf(a,5); System.out.print(Arrays.toString(b)); //[1, 5, 6, 7, 8]
Arrays.copyOfRange(需要进行复制的数组,开始位置,结束位置)
int a[]= {1,5,6,7,8,9,3,2,4,0}; int b[] =Arrays.copyOfRange(a, 2, 5); System.out.print(Arrays.toString(b)); //[6, 7, 8]
6.4.5数组查询
public static int binarySearch(Object[] a, Object key)
- a 需要被查找的数组
- key 需要查找的值
public static int binarySearch(int[] a, fromIndex,int toIndex,int key)
- a 需要被查找的数组
- fromIndex 开始的索引
- toindex 结束的索引(不包含)
- key 需要查找的值
用二分查找算法在给定数组中搜索给定值的对象(Byte,Int,double等)。数组在调用前必须排序好的。如果查找值包含在数组中,则返回搜索键的索引;否则返回 (-(插入点) - 1)。
int a[]= {1,5,6,7,8,9,3,2,4,0}; int b =Arrays.binarySearch(a,5); System.out.print(b); //1
int a[]= {1,5,6,7,8,9,3,2,4,0}; int b =Arrays.binarySearch(a,2,4,5);//在2到4(不包含)索引处查找 System.out.print(b); //-3(3为插入点)