day07-常用类-ArrayList-操作练习
This commit is contained in:
@@ -1,8 +1,37 @@
|
|||||||
package com.inmind.arraylist03;
|
package com.inmind.arraylist03;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
|
||||||
/*
|
/*
|
||||||
ArrayList_练习1_指定格式拼接字符串
|
ArrayList_练习1_指定格式拼接字符串
|
||||||
定义以指定格式打印集合的方法(ArrayList类型作为参数),使用@分隔每个元素。
|
定义以指定格式打印集合的方法(ArrayList类型作为参数),使用@分隔每个元素。
|
||||||
格式参照: [元素@元素@元素]。
|
格式参照: [元素@元素@元素]。
|
||||||
*/
|
*/
|
||||||
public class Test11 {
|
public class Test11 {
|
||||||
|
public static void main(String[] args) {
|
||||||
|
ArrayList<String> lists = new ArrayList<>();
|
||||||
|
lists.add("白鹿");
|
||||||
|
lists.add("王宝强");
|
||||||
|
lists.add("杨幂");
|
||||||
|
lists.add("迪丽热巴");
|
||||||
|
|
||||||
|
String result = showArrayList(lists);
|
||||||
|
System.out.println(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String showArrayList(ArrayList<String> list) {
|
||||||
|
String result = "[";
|
||||||
|
for (int i = 0; i < list.size(); i++) {
|
||||||
|
String temp = list.get(i);//集合中的每个元素
|
||||||
|
|
||||||
|
if (i == list.size() - 1) {
|
||||||
|
result = result + temp + "]";
|
||||||
|
} else {
|
||||||
|
// result = result + temp + "@";
|
||||||
|
result += temp + "@";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,7 @@
|
|||||||
package com.inmind.arraylist03;
|
package com.inmind.arraylist03;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
|
||||||
/*
|
/*
|
||||||
常用类_ArrayList_练习2_获取偶数集合
|
常用类_ArrayList_练习2_获取偶数集合
|
||||||
有一个原本的集合,该集合中有正整数,1,3,4,5,8,9
|
有一个原本的集合,该集合中有正整数,1,3,4,5,8,9
|
||||||
@@ -7,4 +10,34 @@ package com.inmind.arraylist03;
|
|||||||
实现方式要有2种:1.创建新集合实现 2.不创建新集合实现
|
实现方式要有2种:1.创建新集合实现 2.不创建新集合实现
|
||||||
*/
|
*/
|
||||||
public class Test12 {
|
public class Test12 {
|
||||||
|
public static void main(String[] args) {
|
||||||
|
ArrayList<Integer> lists = new ArrayList<>();
|
||||||
|
lists.add(1);
|
||||||
|
lists.add(2);
|
||||||
|
lists.add(3);
|
||||||
|
lists.add(3);
|
||||||
|
lists.add(4);
|
||||||
|
//1.创建新集合实现获取偶数
|
||||||
|
ArrayList<Integer> newList = new ArrayList<>();
|
||||||
|
for (int i = 0; i < lists.size(); i++) {
|
||||||
|
Integer temp = lists.get(i);
|
||||||
|
if (temp % 2 == 0) {//判断每个元素是否是偶数,是则添加到新集合
|
||||||
|
newList.add(temp);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
System.out.println(newList);
|
||||||
|
System.out.println("--------------------");
|
||||||
|
//2.不创建新集合实现,将原本的集合中的奇数,删除掉即可!!!
|
||||||
|
for (int i = 0; i < lists.size(); i++) {
|
||||||
|
Integer temp = lists.get(i);//每个元素
|
||||||
|
if (temp % 2 == 1) {
|
||||||
|
//是奇数,就删除
|
||||||
|
lists.remove(i);
|
||||||
|
//在集合删除时,一定要让索引倒退1,才不会漏掉任何一个值
|
||||||
|
i--;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
System.out.println(lists);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user