数组的拷贝
在System类中包含——static void arraycopy(object src,int srcpos,object dest,int destpos,int length)
作用:将src数组中的元素赋值给dest数组的元素,srcpos指定从src的第几个元素开始赋值,length指定将src数组的多少个元素赋值给dest
数组的扩容,数组的删除都是数组的拷贝:
package text;
public class text01 {
public static void main(String[] args) {
testBasicCopy2();
String[] str = {"1","2","3","4","5"};
removeElment(str, 1);
str = extendRange(str);
}
/*
//s1从第二个拷贝到s2的第6个,共三个元素
public static void testBasicCopy(){
String[] s1 = {"aa","bb","cc","dd","ee"};
String[] s2 = new String[10];
System.arraycopy(s1, 2, s2, 6, 3);
for(int i=0;i<s2.length;i++) {
System.out.println(i+"--"+s2[i]);
}
}
*/
//测试从数组中删除某个元素(本质上还是数组的拷贝)——把要删除的后面的元素全部拷贝一遍
public static void testBasicCopy2(){
String[] s1 = {"aa","bb","cc","dd","ee"};
System.arraycopy(s1, 3, s1, 3-1, s1.length-3);
s1[s1.length-1] = null;
for(int i=0;i<s1.length;i++) {
System.out.println(i+"--"+s1[i]);
}
}
//删除数组中指定索引位置的元素,并将原数组返回
//包装成方法
public static String[] removeElment(String[] s, int index){
System.arraycopy(s, inde x+1, s, index, s.length-index-1);
s[s.length-1] = null;
for(int i=0;i<s.length;i++) {
System.out.println(i+"--"+s[i]);
}
return s;
}
//数组的扩容(本质上是:先定义一个更大的数组,
//然后将原数组内容原封不动拷贝到新数组中)
public static String[] extendRange(String[] s1){
String[] s1 = {"aa","bb","cc"};
//把s1进行扩容
String[] s2 = new String[s1.length+10];
//就将s1中所有的元素拷贝到了s2
System.arraycopy(s1, 0, s2, 0, s1.length);
for(String temp:s2){
System.out.println(temp);
}
return s2;
}
}
Arrays工具类
JDK提供的java.util.Arrays类,包含了常用的数组操作——排序,查找,填充,打印内容
package text;
import java.util.Arrays;
public class text01 {
public static void main(String[] args) {
int[] a = {100,20,30,5,150,80,200};
System.out.println(a);
//打印数组内容
System.out.println(Arrays.toString(a));
//[100, 20, 30, 5, 150, 80, 200]
//对数组元素进行排序,由小到大
//对数组元素是引用类型的排序——需要实现comparable接口
Arrays.sort(a);
System.out.println(Arrays.toString(a));
//查找特定元素的下标,不在则返回-1
System.out.println(Arrays.binarySearch(a, 30));
}
}