【Java】数组知识回顾
程序员文章站
2023-02-09 23:00:12
package another; import java.util.Arrays; import java.util.List; /** * 数组知识回顾 * @author ChristineBassoon */ public class Array { public static void ma ......
package another;
import java.util.arrays;
import java.util.list;
/**
* 数组知识回顾
* @author christinebassoon
*/
public class array {
public static void main(string[] args) {
//1. 新建数组的三种方式
int[] arr1 = new int[3];
int[] arr2 = {3,2,4,1};
int[] arr3 = new int[]{5,7,9,0,3,5};
//填充数组
arrays.fill(arr1, 10);//[10,10,10]
//2. 数组元素默认值
int[] arr_int = new int[3];//[0,0,0]
string[] arr_str = new string[3];//[null,null,null]
//3. 输出数组内容,如:[0,0,0,0]
arrays.tostring(arr1);
/*4. 数组自动排序(从小到大)
* 一、 数组全排序 arrays.sort(t[])
* 二、 特定位置排序 arrays.sort(t[], fromindex, toindex);
*/
arrays.sort(arr2);//[1,2,3,4]
arrays.sort(arr3,1,3);//只排序下标1-3的元素 [5,0,7,9,3,5]
//5. 数组扩容、复制等————基于方法system.arraycopy(src, srcpos, dest, destpos, length);
/*
* (1) 扩容
* arrays.copyof(original, newlength)
* 扩充的元素加至原序列末尾
*/
int[] arr4 = arrays.copyof(arr2, arr2.length+2);//[1,2,3,4,0,0]
/*
* (2) 缩容
* arrays.copyof(original, newlength)
* 根据指定长度,只保留原数组的头部
*
*/
int[] arr5 = arrays.copyof(arr2, 2);// [1,2]
/*
* (3) 截取(同数组中)
* arrays.copyofrange(original, from, to)
* 范围为[from,to),超出则抛illegalargumentexception异常
*/
int[] arr6 = arrays.copyofrange(arr2, 1, 3);//[2,3]
/*
* 用外部数组元素替换本数组指定位置
* system.arraycopy(src, srcpos, dest, destpos, length); length表示需要复制的元素个数
*/
string[] t1 = {"a","b","c","d"};
string[] t2 = {"apple","boy","c","d"};
system.arraycopy(t1, 1, t2, 2, 1);
system.out.println(arrays.tostring(t2));//[apple, boy, b, d]
//数组转换为list类型
list list = arrays.aslist(arr2);
}
}
上一篇: 浪漫的情诗