ArrayList
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner in =new Scanner(System.in);
ArrayList<String> s = new ArrayList<String>(); //定义两个类型,容器的类型,元素的类型
s.add("Hello"); //向容器里添加元素
s.add("world");
s.add("!");
s.add(1,"the"); //在指定位置中插入元素
int index = in.nextInt();
String p = null,q = null;
if (index<s.size()) {
p = s.get(index); //返回容器中该位置的元素
q = s.remove(index); //删除并返回容器中该位置的元素
}
System.out.println(p+" "+q);
String[] a = new String[s.size()];
s.toArray(a); //将容器转换为数组
System.out.println(Arrays.toString(a));
System.out.println(s); //直接输出容器
System.out.println(s.size()); //容器的大小,里面有多少个元素
}
}
输出为
2 //输入
world world
[Hello, the, !]
[Hello, the, !]
3
HashSet
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner in =new Scanner(System.in);
HashSet<String> s = new HashSet<String>(); //定义两个类型,容器的类型,元素的类型
s.add("Hello"); //向容器里添加元素
s.add("world");
s.add("Hello"); //HashSet中不会出现重复元素,且元素无序
String[] a = new String[s.size()];
s.toArray(a); //将容器转换为数组
System.out.println(Arrays.toString(a));
s.remove("Hello"); //删除容器中的指定元素
System.out.println(s); //直接输出容器
System.out.println(s.size()); //容器的大小,里面有多少个元素
}
}
输出为
[world, Hello]
[world]
1
HashMap
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner in =new Scanner(System.in);
HashMap<Integer, String> h = new HashMap<Integer, String>(); //定义三个类型,容器的类型,键的类型,值的类型
h.put(1,"hello"); //向容器里添加键值对
h.put(2,"the");
h.put(3,"world");
int index = in.nextInt();
if (h.containsKey(index)) { //判断键是否在容器里
String a, b;
a = h.get(index); //得到容器中那个键所对应的值
b = h.remove(index); //删除容器中对应的键值对,并返回键所对应的值
System.out.println(a + " " + b);
}
else{
System.out.println("NOT FOUND");
}
for (int k : h.keySet()){ //将容器中的键单独取出做一个集合
String s = h.get(k);
System.out.println(s);
}
System.out.println(h); //直接输出容器
System.out.println(h.size()); //容器的大小,里面有多少个元素
}
}
输出为
0 //输入
NOT FOUND
hello
the
world
{1=hello, 2=the, 3=world}
3
1
hello hello
the
world
{2=the, 3=world}
2