zoukankan      html  css  js  c++  java
  • java ArrayList和Iterator

    创建ArrayL对象

    ArrayList a=new ArrayList();

    加入元素

    a.add(E e);

    在指定的位置修改元素

    a.set(1,"world");

    把位置1的元素设为world

    插入元素

    a.add(int index .E e);

    在位置index 插入元素

    remove(int index)  移除指定位置元素

    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;
    
    
    public class ArrayListTest {
       public static void main(String[] args)
       {
          List a=new ArrayList();
           String s1="hello";
           String s2="world";
           a.add(s1);
           a.add(s2);
           a.add(0,"happy");
           a.add(3);
          
            
           for(int i=0;i<a.size();i++)
           {
               System.out.println(i+"  "+a.get(i));
           }
        
           int d=(Integer)a.get(3);
           String s=(String)a.get(0);
           System.out.println("\n"+s);
         
       }
    
    }

    读取对象时,一定要用强制类型转换:

    如果改为 a.get(3)值为3.

    int d= a.get(3); 错误:Type mismatch: cannot convert from Object to int

    注意存进去的类型要与取出来时候的类型相匹配。如果存进去的是Interger, String s=(String)a.get(0);
    会报错:java.lang.Integer cannot be cast to java.lang.String

    当我们直接a.add(1);实际上存进去的是Integer类型的对象。非对象的基本类型的数值可以用数组存储,但是,如果能用对象来表示数值,就可以用ArrayList来存储了。
    Integer n=new Integer(10);
    a.add(n);

    数值的包装对象无法直接进行计算,而必须先用Integer类的intValue方法和Double类的doubleValue方法获得基本类型的hi。
    n.intValue();

    获取ArrayList的元素个数:
    int theSize=arrayList.size();
    不能用length;那是数组用的。

    迭代器应用:
     list l = new ArrayList();
     l.add("aa");
     l.add("bb");
     l.add("cc");
     for (Iterator iter = l.iterator(); iter.hasNext();) {
      String str = (String)iter.next();
      System.out.println(str);
     }
     /*迭代器用于while循环
     Iterator iter = l.iterator();
     while(iter.hasNext()){
      String str = (String) iter.next();
      System.out.println(str);
     }
     */

    我们上面用的迭代器,返回的是一个object,需要typecast

  • 相关阅读:
    Python笔记_第一篇_面向过程_第一部分_5.Python数据类型之字符串类型(string)
    每天一杯C_Visual Studio各个版本的区别和总结
    Python笔记_第一篇_面向过程_第一部分_5.Python数据类型之数字类型(number)
    Python笔记_第一篇_面向过程_第一部分_3.进制、位运算、编码
    Valid Number @python
    正式进驻博客园
    LCT总结
    LCT总结
    bzoj3229 [Sdoi2008]石子合并(非dp的GarsiaWachs算法)
    bzoj3229 [Sdoi2008]石子合并(非dp的GarsiaWachs算法)
  • 原文地址:https://www.cnblogs.com/youxin/p/2710851.html
Copyright © 2011-2022 走看看