//向arraylist、linkedlist集合中添加元素1、2、3、4、5,增加一个序号为5的元素6,
// 使用foreach方法便历并输出所有元素,最后使用iterator并在遍历过程中删除序号为2的元素。
import java.util.*;
public class Main {
public static void main(String[] args){
// arrayList();
// linkedList();
// hashset();
// linkedhashset();
// treeset();
}
public static void arrayList(){
ArrayList arrayList = new ArrayList();
for (int i=1;i<=5;i++)
arrayList.add(i);
arrayList.add(5,6);
System.out.println("arrayList:");
for (Object obj:arrayList) {
System.out.print(obj+" ");
}
System.out.println();
Iterator it = arrayList.iterator();
int index = 0;
while (it.hasNext()){
Object obj = it.next();
if(index == 2){
it.remove();
}
index++;
}
System.out.println(arrayList);
}
public static void linkedList(){
LinkedList linkedList = new LinkedList();
for (int i=1;i<=5;i++)
linkedList.add(i);
linkedList.add(5,6);
System.out.println("linkedList:");
for (Object obj:linkedList) {
System.out.print(obj+" ");
}
System.out.println();
Iterator it = linkedList.iterator();
int index = 0;
while (it.hasNext()){
Object obj = it.next();
if(index == 2){
it.remove();
}
index++;
}
System.out.println(linkedList);
}
public static void hashset(){
HashSet hset = new HashSet();
hset.add("张三");
hset.add("李四");
hset.add("王五");
hset.add("李四");
Iterator it = hset.iterator();
while(it.hasNext()){
Object obj = it.next();
System.out.println(obj);
}
}
public static void linkedhashset(){
LinkedHashSet set = new LinkedHashSet();
set.add("张三");
set.add("李四");
set.add("王五");
Iterator it = set.iterator();
while(it.hasNext()){
Object obj = it.next();
System.out.println(obj);
}
}
public static void treeset(){
TreeSet ts = new TreeSet();
ts.add(3);
ts.add(29);
ts.add(101);
ts.add(21);
System.out.println("创建的TreeSet是:"+ts);
System.out.println("TreeSet中的首元素:"+ts.first());
System.out.println("TreeSet中的尾元素:"+ts.last());
System.out.println("集合中小于或等于9的最大元素:"+ts.floor(9));
System.out.println("集合中大于10的最小元素:"+ts.higher(10));
System.out.println("集合中大于100的最小元素:"+ts.higher(100));
Object first = ts.pollFirst();
System.out.println("删除的第一个元素:"+first);
System.out.println("删除后为:"+ts);
}
}
java--集合入门
最新推荐文章于 2024-08-30 18:40:43 发布