1 Arrays.asList()
public static void main(String[] args) {
String[] str={"11","22","33","44","55","66"};
List<String> list=Arrays.asList(str);//将数组转换为list集合
//*************************************
//list.remove("11");
//*************************************
if(list.contains("22")){//加入集合中包含这个元素
/*remove这些method时出现java.lang.UnsupportedOperationException异常。
* 这是由于Arrays.asList() 返回java.util.Arrays$ArrayList,
* 而不是ArrayList。Arrays$ArrayList和ArrayList都是继承AbstractList,
* remove,add等method在AbstractList中是默认throw UnsupportedOperationException而且不作任何操作。
* ArrayList override这些method来对list进行操作,
* 但是Arrays$ArrayList没有override remove(),add()等,
* 所以throw UnsupportedOperationException。
*/
//这个时候我们直接移除会报错,所以我们要转换为Arraylist
//list.remove("张三");
List<String> arrayList=new ArrayList<String>(list);//转换为ArrayLsit调用相关的remove方法
arrayList.remove("33");
for(String str1:arrayList ){
System.out.print(str1+",");
}
}
}
2遍历数组
public static void main(String[] args)
{
int[] arr = {0,0,12,1,0,4,6,0};
arr = clearZero(arr);
System.out.println("数组的元素:"+Arrays.toString(arr));
}
public static int[] clearZero(int[] arr){
//统计0的个数
int count = 0; //定义一个变量记录0的个数
for(int i = 0 ; i<arr.length ; i++){
if(arr[i]==0){
count++;
}
}
//创建一个新的数组
int[] newArr = new int[arr.length-count];
int index =0 ; //新数组使用的索引值
//把非的数据存储到新数组中。
for(int i = 0; i<arr.length ; i++){
if(arr[i]!=0){
newArr[index] = arr[i];
index++;
}
}
return newArr;
}
3字符串桥接
public static void main(String[] args) {
int a2[] = { 1, 0, 5,0,6,0,4, 1, 0 };
System.out.println("原数组:");
for (int n : a2)
System.out.print(n + ",");
// 删除元素!
a2 = value(a2, 0);
System.out.println("\n现数组:");
for (int n : a2)
System.out.print(n + ",");
}
private static int[] value(int[] arr, int key) {
StringBuilder str=new StringBuilder();
for (int i = 0; i < arr.length; i++)
if(arr[i]!=key)
str.append(arr[i]);
char[] chs=new String(str).toCharArray();
int[] orr=new int[chs.length];
for (int i = 0; i < orr.length; i++) {
orr[i]=chs[i]-'0';
}
return arr=orr;
}
4 浅复制
public static void main(String[] args) {
int a1[]={1,3,4,5,0,0,9,6,0,5,4,7,6,7,0,5};
//测试第一种办法:
System.out.println("原数组:");
for (int n : a1)
System.out.print(n + ",");
// 删除元素!
a1=volume(a1,0);
System.out.println("\n现数组:");
for (int n : a1)
System.out.print(n + ",");
}
private static int[] volume(int[] arr, int key) {
int count = 0;
for (int i = 0, j = arr.length - 1; i <= j; i++, j--) {
if (arr[i] == key && i != j)
count++;
if (arr[j] == key && i != j)
count++;
if (arr[i] == key && i == j)
count++;
}
//上面就是计算0的个数
int nrr[] = new int[arr.length - count];
count = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] == key)
continue;
else
nrr[count++] = arr[i];
}
return arr = nrr;
}
公众号地址