zoukankan      html  css  js  c++  java
  • Java Collection集合

    集合的分类

    集合是数据容器, 用来存储对象类型, 包装类等; 集合的长度可变

    单列集合: 

    Collection 常用功能

    最顶层的接口, 里边定义了所有单列集合共性的方法

    单列集合子类可使用共性方法:

    • public boolean add(E e): 把给定的对象添加到当前集合中 。

    • public void clear(): 清空集合中所有的元素。

    • public boolean remove(E e): 把给定的对象在当前集合中删除。

    • public boolean contains(E e): 判断当前集合中是否包含给定的对象。

    • public boolean isEmpty(): 判断当前集合是否为空。

    • public int size(): 返回集合中元素的个数。

    • public Object[] toArray(): 把集合中的元素,存储到数组中。

    Iterator 接口

    java.util.Iterator

    获取迭代器对象: 调用集合实现类的 iterator() 方法

    常用成员方法: 

    1. boolean hasNext(): 判读是否有元素可以迭代

    2. E next(): 返回迭代的下一个元素

    demo:

    import java.util.ArrayList;
    import java.util.Collection;
    import java.util.Iterator;
    
    public class Main {
        public static void main(String[] args) {
            Collection<String> coll = new  ArrayList<>();
            coll.add("johny");
            coll.add("anson");
    
            // 获取迭代器对象, 接口Iterator也是有泛型的
            Iterator<String> it = coll.iterator();
            while (it.hasNext()) {
                String s = it.next();
                System.out.println(s);
            }
        }
    }

    foreach (增强for循环)

    简化迭代器的编写 (JDK1.5后边的特性)

    for (元素类型 变量名 : 集合/数组) {

      System.out.println(变量名)

    }

    demo:

    import java.util.ArrayList;
    
    public class Main {
        public static void main(String[] args) {
            ArrayList<String> arrL = new ArrayList<>();
            arrL.add("johny");
            arrL.add("anson");
    
            // foreach
            for (String element : arrL){
                System.out.println(element);
            }
        }
    }

    泛型

    public class ArrayList<E> {

      public boolean add(E e) {}

    ​  public E get(int index) {}

    }

    E 表示未知的类型, 一般在创建对象时, 将未知的类型确定具体的类型. 当没有指定泛型时,默认类型为Object类型

    推荐创建集合时使用泛型, 避免类型转换的麻烦; 把运行期异常, 提升到编译期

    tips: 泛型是数据类型的一部分,我们将类名与泛型合并一起看做数据类型。

    ending ~ 

    每天都要遇到更好的自己.
  • 相关阅读:
    curl 抓取图片
    checkbox 全选
    大文件断点上传 js+php
    php快速排序
    直接插入排序(Straight Insertion Sort)
    选择排序 Selection sort
    57.猴子吃桃问题
    56.一球从100米高度自由落下,每次落地后反跳回原高度的一半;再落下,求它在第10次落地时,共经过多少米?第10次反弹多高?
    55.输入两个正整数m和n,求其最大公约数和最小公倍数
    54.将一个正整数分解质因数。例如:输入90,打印出90=2*3*3*5
  • 原文地址:https://www.cnblogs.com/kaichenkai/p/11798598.html
Copyright © 2011-2022 走看看