1.编写程序测试Java集合框架中各种常用类的 基本操作(包括添加元素,删除元素,查找元素,遍历集合元素等)
(1)常用集合类-ArrayList类(内部实现基于数组)
将整型对象元素顺序加入ArrayList中
package yztext07;
import java.util.*;
public class Test {
public static void main(String[] args) {
List al = new ArrayList();
al.add(new Integer(1));
al.add(new Integer(4));
al.add(new Integer(2));
for (int i = 0; i < 3; i++) {
Integer m = (Integer) al.get(i);
System.out.println(m);
}
}
}
运行结果:9
8
7
6
5
4
3
2
1
0
(2)常用集合类-LinkedList类 (内部实现基于链表)
import java.util.*;
public class IntObjectLink{
public static void main(String args[]) {
Integer tem;
try{
List<Integer> lst = new LinkedList<Integer>();
for (int i=0; i<10 ; i++ ){
lst.addFirst(new Integer(i));
}
for (int i=0; i<10; i++ ){
tem = lst.removeFirst();
System.out.println(tem.intValue());
}
}
catch(Exception e){
System.out.println(“error");
}
}
}
(3)常用集合类-ArrayDeque (提供栈结构实现)
import java.util.*;
public class Stacks{
public static void main(String[] args){
Deque<Integer> stk = new ArrayDeque<Integer>();
for(int i=0;i<10;i++)
stk.push(i); //addFirst()
System.out.println("stk="+ stk);
System.out.println("popping elements:");
while(stk.size()!=0)
//removeFirst()
System.out.println(stk.pop());
}
}
运行结果:
stk=[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
popping elements:
9
8
7
6
5
4
3
2
1
0
import java.util.ArrayList;
public class ArrayListDemo1 {
public static void main(String[] args) {
ArrayList<String> arr=new ArrayList<String>();
//public boolean add(E e)将指定元素添加到此集合末尾
arr.add("hello");
arr.add("world");
arr.add("JAVA");
//public void add(int index,E e)
//将指定元素插入指定位置
arr.add(1,"JAVASE");
//public boolean remove(int index)删除指定位置元素
arr.remove(1);
//修改
arr.set(1,"JAVASe");
//返回指定元素
System.out.println(arr.get(1));
//遍历
for(int i=0;i<arr.size();i++){
String S=arr.get(i);
System.out.println(S);
}
System.out.println("arr="+arr);
}
}