黑马程序员--------常用集合的遍历方式总结

来源:互联网 发布:电商大数据分析平台 编辑:程序博客网 时间:2024/06/07 10:31

------- 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());}}



0 0
原创粉丝点击