zoukankan      html  css  js  c++  java
  • Java—增强for循环与for循环的区别/泛型通配符/LinkedList集合

    增强for循环

      增强for循环是JDK1.5以后出来的一个高级for循环,专门用来遍历数组和集合的。

      它的内部原理其实是个Iterator迭代器,所以在遍历的过程中,不能对集合中的元素进行增删操作

    //格式:
    for(元素的数据类型 变量 : Collection集合or数组){
    }
    
    for (int n : arr) {//变量n代表被遍历到的数组元素
        System.out.println(n);
    }

      增强for循环和普通的for循环有什么区别?

      注意:for循环必须有被遍历的目标。目标只能是Collection或者是数组。

      建议:遍历数组时,如果仅为遍历,可以使用增强for如果要对数组的元素进行 操作,使用老式for循环可以通过角标操作。

    泛型

      定义格式:修饰符 class 类名<代表泛型的变量> { }

    class ArrayList<E>{
    public boolean add(E e){ }
        public E get(int index){ }
    }

      使用格式:创建对象时,确定泛型的类型

      例如,ArrayList<String> list = new ArrayList<String>();

    //此时,变量E的值就是String类型
    class ArrayList<String>{
    public boolean add(String e){ }
        public String get(int index){ }
    }

    泛型通配符:

      泛型是在限定数据类型,当在集合或者其他地方使用到泛型后,那么这时一旦明确泛型的数据类型,

      那么在使用的时候只能给其传递和数据类型匹配的类型,否则就会报错。

      为了解决这个"无法确定具体集合中的元素类型"问题,java中,为我们提供了泛型的通配符<?>

      例如:

    public static void printCollection(Collection<?> list) {
        Iterator<?> it = list.iterator();
        while (it.hasNext()) {
            System.out.println(it.next());
        }
    }

    泛型的限定:

      

    限定泛型的上限:

      格式:? extends E

       ? 代表接收E类型或者E的子类型的元素

      例如,泛型限定为:? extends Person

      则 ? 代表接收Person类型或者Person子类型的元素

    限定泛型的下限:

      格式:? super E

       ? 代表接收E类型或者E的父类型的元素

      例如,泛型限定为:? super Student

      则 ? 代表接收Student类型或者Student父类型的元素

    LinkedList集合

      LinkedList是List的子类,List中的方法LinkedList都是可以使用。

      LinkedList集合数据存储的结构是链表结构。方便元素添加、删除的集合。

      实际开发中对一个集合元素的添加与删除经常涉及到首尾操作,而LinkedList提供了大量首尾操作的方法。

      

         LinkedList<String> link = new LinkedList<String>();
            //添加元素
            link.addFirst("abc1");
            link.addFirst("abc2");
            link.addFirst("abc3");
            //获取元素
            System.out.println(link.getFirst());
            System.out.println(link.getLast());
            //删除元素
            System.out.println(link.removeFirst());
            System.out.println(link.removeLast());
            
            while(!link.isEmpty()){ //判断集合是否为空
                System.out.println(link.pop()); //弹出集合中的栈顶元素
           }

     

  • 相关阅读:
    Codeforces Round #592 (Div. 2)C. The Football Season(暴力,循环节)
    Educational Codeforces Round 72 (Rated for Div. 2)D. Coloring Edges(想法)
    扩展KMP
    poj 1699 Best Sequence(dfs)
    KMP(思路分析)
    poj 1950 Dessert(dfs)
    poj 3278 Catch That Cow(BFS)
    素数环(回溯)
    sort与qsort
    poj 1952 buy low buy lower(DP)
  • 原文地址:https://www.cnblogs.com/wode007/p/13300175.html
Copyright © 2011-2022 走看看