------- android培訓、java培訓、期待與您交流!
----------
集合的分類:
1.
Collection:
|--list
|--Arraylist 數組結構,線程不安全,有序的
|--Vector 數組結構,線程安全的,有序的
|--LinkedList 鏈表結構,線程不安全的,有序
|--set
|--HashSet 無序的線程不安全
|--TreeSet 帶自動排序功能,線程不安全
|--LinkedHashSet 鏈表結構 有序的 線程不安全
2.
Map
|--HashMap 雙列:鍵值+變量模式
|--TreeMap 帶排序功能的雙列:鍵值+變量模式
下面舉例每種集合的遍歷方式
list和set集合遍歷方式相同 這裏舉例ArrayList的遍歷方式:
public static void main(String[] args) {
// 創建集合
ArrayList<Student> al = new ArrayList<>();
// 添加元素
al.add(new Student("第一天", 66));
al.add(new Student("第二天", 55));
al.add(new Student("第三天", 33));
// 使用toArray()方式
// 這裏要強制類型轉換,toArray()方法返回的是一個Object[]數組取值後要強轉類型
Object[] obj = al.toArray();
for (int i = 0; i < obj.length; i++) {
Student stu = (Student) obj[i];
System.out.println(stu);
}
System.out.println("----------華麗的分割線----------");
// 使用迭代器遍歷
Iterator<Student> it = al.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
System.out.println("----------華麗的分割線----------");
// 使用增強for循環
for (Student s : al) {
System.out.println(s);
}
}
下面這個是Map的遍歷方式 這裏使用TreeMap爲例:
public static void main(String[] args) {
//創建集合
TreeMap<String,Student> tm=new TreeMap<>();
//添加元素
tm.put("001", new Student("第一天",66));
tm.put("002", new Student("第二天",55));
tm.put("003", new Student("第三天",44));
//使用keySet()方法遍歷集合
Set<String> keyset=tm.keySet();
for(String k:keyset){
System.out.println(k+"---"+tm.get(k).toString());
}
System.out.println("----------華麗的分割線----------");
//使用entrySet()方法創建集合
Set<Map.Entry<String, Student>> ks=tm.entrySet();
//使用迭代器
Iterator<Map.Entry<String, Student>> it=ks.iterator();
while(it.hasNext()){
//如果使用了泛型就不用將it.next()強制類型轉換
Map.Entry<String,Student> me=it.next();
System.out.println(me.getKey()+"---"+me.getValue().getName()+"---"+me.getValue().getAge());
}
}