集合分别是 list map set 三种,这三种的父类都是collection。
需要注意的是 list map set都是接口,所以不能new对象。
1、List
List可分为ArrayList 和LinkList,List的优点是有序、有下标、方便查询。可用加强for循环(foreach)、for循环、while循环来进行遍历。
List最常用的使用方法实例如下(Student类附在文章末尾):
List<Student> list = new ArrayList<Student>();
list.add(s);
list.add(s1);
list.add(s2);
list.add(s3);
list.add(s4);
for(int i=0;i<list.size();i++) {
System.out.println(list.get(i));
}
2、Set
Set最常用的是HashSet ,Set的优点:方便删除、插入集合元素,具有无序性,没有下标。缺点:查询缓慢,可用加强for循环(foreach)、while循环来进行遍历。
Set最常用的使用方法实例如下(Student类附在文章末尾):
Set<Student> set = new HashSet<Student>();
set.add(s);
set.add(s1);
set.add(s2);
set.add(s3);
set.add(s4);
Iterator<Student> it = set.iterator();
while(it.hasNext()) {
System.out.println(it.next());
}
3、Map
Map最常用的是HashMap,Map有key-value键值对,一个键只能有一个值,一个值可以有多个键。 Map相当于一个小型的数据库,可以存储多种类型的信息,可用加强for循环(foreach)、while循环来进行遍历。
Set最常用的使用方法实例如下(Student类附在文章末尾):
Map<Integer,Student> map = new HashMap<Integer,Student>();
map.put(1, s);
map.put(2, s1);
map.put(3, s2);
map.put(4, s3);
map.put(5, s4);
for(Map.Entry<Integer,Student> entry : map.entrySet()) {
System.out.println(entry.getKey());
System.out.println(entry.getValue());
}
Student类如下:
public class Student {
public String Name;
public int Age;
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public int getAge() {
return Age;
}
public void setAge(int age) {
Age = age;
}
public Student(String name, int age) {
super();
Name = name;
Age = age;
}
@Override
public String toString() {
return "Student [Name=" + Name + ", Age=" + Age + "]";
}
}