zoukankan      html  css  js  c++  java
  • java-集合框架4---foreach使用--for的增强使用

    1、如果只是遍历集合的话 使用foreach更好一些

    2、如果要对数据元素进行修改,那就使用for

    package cn.burce.for1;
    
    import java.util.ArrayList;
    
    /*
     * 1.5之后增强FOR循环
     * 出现新接口java.lang.Iterable
     * Collection 继承Iterable
     * Iterable作用,实现增强for循环
     * Iterable的小弟都可以使用foreach(基本上所有的集合
     * 格式
     * for(数据类型 变量 :数组或者集合){syso(变量)}
     * 
     *  */
    
    public class ForLearn {
        public static void main(String[] args) {
            function();
            function1();
        }
    
        /*
         * 好处:减少代码循环 坏处:没有索引,不能动里面元素
         */
        public static void function() {
            int[] a = { 1, 2, 3, 4, 5 };
            for (int i : a)
            {
                System.out.println(i);
            }
        }
    
        private static void function1() {
            ArrayList<Person> arr = new ArrayList<Person>();
            Person p1 = new Person("请求", 10);
            Person p2 = new Person("问问", 10);
            Person p3 = new Person("嗯嗯", 10);
    
            arr.add(p1);
            arr.add(p2);
            arr.add(p3);
            arr.add(new Person("弱弱", 10));// 匿名对象也可以
            for (Person person : arr)
            {
                person.learn();// 遍历对象的方法
            }
        }
    }
    
    class Person {
        public String name;
        public int age;
    
        public Person(String name, int age)
        {
            super();
            this.name = name;
            this.age = age;
        }
    
        public void learn() {
            System.out.println(this.name + "在学习");
        }
    
        public void eat() {
            System.out.println(this.name + "在学习");
        }
    }

  • 相关阅读:
    python2
    python1
    jmeter基础使用
    LoadRuuner资源监控
    UI自动化
    MYSQL增删改查添加外键
    DW网页代码笔记
    Linux常用命令(常用)
    Linux常用命令大全(全全全!!!)
    第十二章 : shell 环境
  • 原文地址:https://www.cnblogs.com/BruceKing/p/13379645.html
Copyright © 2011-2022 走看看