A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© yuhongzhen 中级黑马   /  2015-11-30 21:29  /  1164 人查看  /  7 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

使用增强for循环遍历集合,请大家指!

package cn.itheima;

import java.util.ArrayList;
import java.util.Collection;

class Person{
        String name;
        int id;
       
        @Override
        public String toString() {
                // TODO Auto-generated method stub
                return this.name+this.id;
        }
        public Person(String name,int id) {
                super();
                this.name = name;
                this.id=id;
        }
        @Override
        public int hashCode() {
                final int prime = 31;
                int result = 1;
                result = prime * result + id;
                result = prime * result + ((name == null) ? 0 : name.hashCode());
                return result;
        }
        @Override
        public boolean equals(Object obj) {
                if (this == obj)
                        return true;
                if (obj == null)
                        return false;
                if (getClass() != obj.getClass())
                        return false;
                Person other = (Person) obj;
                if (id != other.id)
                        return false;
                if (name == null) {
                        if (other.name != null)
                                return false;
                } else if (!name.equals(other.name))
                        return false;
                return true;
        }
       
}

public class Demo5 {

        /**
         * @param args
         */
        public static void main(String[] args) {
                ArrayList c=new ArrayList();
                c.add(new Person("李三",110));
                c.add(new Person("张三",120));
                c.add(new Person("王五",130));
                System.out.println(new Person("王五",130));
                Object[] o=c.toArray();
                for(Object p:c){
                        Person p1=(Person)p;
                        if(p1.id==120){
                                System.out.println(p1);       
                        }

                }
               

        }

}


7 个回复

倒序浏览
你学到这里了,,和我一样唉,我也是昨天 学到这里的,,加我qq1070941548
回复 使用道具 举报
学习学习
回复 使用道具 举报
很简单啊
回复 使用道具 举报
学习一下,在哪里
回复 使用道具 举报
没啥难的,有遍历对象即可
回复 使用道具 举报
其实我想说 HashCode 和 equals 方法的重写是关键, 理解增强循环的格式就好, 类型  名字 :  数组(集合),强转部分可以使用泛型
回复 使用道具 举报
乌鲁特 来自手机 中级黑马 2015-12-4 12:58:09
8#
增强for循环
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马