zoukankan      html  css  js  c++  java
  • java 15- 5 List集合


      需求 1:List集合存储字符串并遍历。(步骤跟Collection集合一样,只是最初创建集合对象中的集合类改变了,Collection变成List)
        List集合的特点:
          有序(存储和取出的元素一致),可重复的。
      需求2: 存储自定义对象并遍历
        这里我调用已经写好的Student类
      分析:
        A:创建对象的类(这里我用写好的Student类)
        B:创建list集合对象
        C:创建集合的成员变量
        D:把成员变量放进去集合中
        E:创建迭代器
        F:遍历输出集合

     1 package zl_ObjectTest1;
     2 
     3 import java.util.ArrayList;
     4 import java.util.Iterator;
     5 import java.util.List;
     6 public class ListDemo1 {
     7 
     8 /*
     9 * 这里是需求1的代码
    10 public static void main(String[] args) {
    11 //创建集合对象
    12 List l = new ArrayList();
    13 
    14 //创建成员对象
    15 String s1 = "花花";
    16 String s2 = "草草";
    17 String s3 = "猫猫";
    18 String s4 = "狗狗";
    19 String s5 = "猫猫";
    20 String s6 = "花花";
    21 
    22 //把成员对象放到集合中
    23 l.add(s1);
    24 l.add(s2);
    25 l.add(s3);
    26 l.add(s4);
    27 l.add(s5);
    28 l.add(s6);
    29 
    30 //给list集合创建迭代器
    31 Iterator lt = l.iterator();
    32 
    33 //对list集合进行遍历
    34 while(lt.hasNext()){
    35 String s = (String) lt.next();
    36 System.out.println(s);
    37 }
    38 }
    39 */
    40 
    41 //需求2 存储自定义对象并遍历 的代码:
    42 /*
    43 分析:    
    44 A:创建对象的类(这里我用写好的Student类)
    45 B:创建list集合对象
    46 C:创建集合的成员变量
    47 D:把成员变量放进去集合中
    48 E:创建迭代器
    49 F:遍历输出集合*/
    50 
    51 public static void main(String[] args) {
    52 //创建集合对象
    53 List l = new ArrayList();
    54 
    55 //创建集合的成员变量
    56 Student s1 = new Student("阿猫",20);
    57 Student s2 = new Student("阿狗",18);
    58 Student s3 = new Student("小猫",19);
    59 Student s4 = new Student("小狗",17);
    60 
    61 //把成员变量放进去集合中
    62 l.add(s1);
    63 l.add(s2);
    64 l.add(s3);
    65 l.add(s4);
    66 
    67 //创建list的迭代器
    68 Iterator lt = l.iterator();
    69 
    70 //遍历集合
    71 while(lt.hasNext()){
    72 //向下转型
    73 Student s = (Student)lt.next();
    74 //System.out.println(s);
    75 System.out.println(s.getName()+"	"+s.getAge());
    76 }
    77 }
    78 }
    何事都只需坚持.. 难? 维熟尔。 LZL的自学历程...只需坚持
  • 相关阅读:
    多线程编程(14) 多线程同步之 WaitableTimer (等待定时器对象)
    多线程编程(17) 多线程同步之 WaitableTimer (等待定时器对象)[续三]
    多线程编程(13) 多线程同步之 Event (事件对象)
    一个关于 absolute 关键字的小练习
    [新功能]在个人Blog页面显示最新评论
    asp.net页面中hmtl注释的问题
    [征询意见]博客园准备租用更好的服务器
    [公告]博客园分页浏览功能改进
    [公告]博客园新服务器测试
    [公告]博客园建立了人才求职区
  • 原文地址:https://www.cnblogs.com/LZL-student/p/5894227.html
Copyright © 2011-2022 走看看