題目:創建一個只能容納String對象名為names的Arraylist集合,按順序向集合中添加5個字符串對象。對集合進行遍歷,打印出集合中每個元素的位置與內容。首先打印出集合的大小,然后刪除集合中的第三個元素,並顯示刪除的內容,刪除之后,再次顯示現在集合第三個元素的內容,之后再打印出集合的大小。
其實,這個東西我只實現了部分功能,等有空在完善吧,最主要是不知道那個函數名字,有點尷尬了
代碼運行效果:
你們想要的代碼來了,哈哈----------------------------
代碼:
/****
* 創建一個只能容納String對象名為names的Arraylist集合,
* 按順序向集合中添加5個字符串對象。對集合進行遍歷,打印出集合中每個元素的位置與內容。
* 首先打印出集合的大小,然后刪除集合中的第三個元素,並顯示刪除的內容,刪除之后,
* 再次顯示現在集合第三個元素的內容,之后再打印出集合的大小。
* @author yanlong
* 2017/5/9
*/
import java.util.ArrayList;
import java.util.Iterator;
//import java.util.*;
public class test2 {
public static void main(String[] args) {
// 創建集合對象
ArrayList<String> array = new ArrayList<String>();
// 創建並添加元素
array.add("chen");
array.add("yan");
array.add("long");
array.add("ni");
array.add("hao");
// 遍歷集合
// 迭代器
Iterator<String> it = array.iterator();
while (it.hasNext()) {
String s = it.next();
System.out.println(s);
}
System.out.println("------------------");
System.out.println("------ 我很好-------");
System.out.println("------------------");
array.remove(3);
Iterator<String> it1 = array.iterator();
//array.remove(3);
while (it1.hasNext()) {
String s1 = it1.next();
System.out.println(s1);
}
}
}