java数组和ArrayList用法

时间:2021-11-26 19:46:59
import java.util.*;

public class ArrayDemo {
public static void main(String arg[]) {
String[] aArray = {"a", "b", "c"};
String[] bArray = new String[]{"d", "e", "f"};

//合并两个数组
String[] cArray = new String[aArray.length + bArray.length ];
System.arraycopy(aArray, 0, cArray, 0, aArray.length);
System.arraycopy(bArray, 0, cArray, aArray.length, bArray.length);

//数组反向排序
Arrays.sort(cArray, Collections.reverseOrder());

//数组正向排序
Arrays.sort(cArray);


//冒泡排序
int[] eArray = {3, 1, 5, 8, 2, 4, 6, 9, 7, 10};
int tmp = 0;
for(int i=0; i< eArray.length;i++){
for(int j=i+1;j<eArray.length;j++){
if(eArray[i] > eArray[j]){
tmp = eArray[i];
eArray[i] = eArray[j];
eArray[j] = tmp;
}
}
}
for (int i : eArray) {
System.out.println(i);
}


//数组转换为数组列表
ArrayList<String> cList = new ArrayList<String>(Arrays.asList(cArray));
//添加元素
cList.add("f");
//设置索引0处的值
cList.set(0, "a0");
// 移除索引1处的值
cList.remove(1);
for (int i=0; i<cList.size(); i++){
System.out.println(cList.get(i));
} //结果:a0 c d e f f

//是否包含指定元素
boolean b = cList.contains("a0");
System.out.println(b); //结果:true

//从前往后查询,反回第一个符合条件的位置
int a1 = cList.indexOf("f");
System.out.println(a1); //结果:4
//从后往前查询,反回第一个符合条件的位置
int a2 = cList.lastIndexOf("f");
System.out.println(a2); //结果:5

//数组列表转换为数组
String[] dArray = new String[cList.size()];
cList.toArray(dArray);
}
}