一、数组
1、indexOf
int targetIndex = indexOf(arr, targetValue);
public static int indexOf(int[] arr,int targetValue){
int index = -1;
for(int i = 0; i < arr.length; i++){
if(arr[i] == targetValue){
index = i;
break;
}
}
return index;
}
2、formatArray
public static void formatArray(int[] arr){
for (int i = 0; i < arr.length; i++){
if(i == 0){
System.out.print("[" + arr[i] +",");
}
else if(i != arr.length - 1){
System.out.print(arr[i] + ",");
}else{
System.out.print(arr[i]+"]");
}
}
System.out.println('\n');
}
3、addItem(根据索引)
public static int[] addItem(int[] arr,int index,int value){
System.out.println("将在该数组中的第" + index + "个位置添加" + value);
for(int i = arr.length - 1; i >= index; i--){
arr[i] = arr[i - 1];
}
arr[index - 1] = value;
return arr;
}
4、deleteItem(根据索引)
public static int[] deleteItem(int[] arr,int index){
for(int i = index-1; i<arr.length-1; i++){
arr[i] = arr[i+1];
}
arr[arr.length-1] = 0;
int[] newArr = new int[arr.length-1];
for(int i = 0; i < newArr.length; i++){
newArr[i] = arr[i];
}
return newArr;
}
标签:index,常用,Java,int,arr,更新,System,static,out
From: https://www.cnblogs.com/new-one/p/17817626.html