问题描述
package com.pro;import java.util.Date;public class Credence implements java.io.Serializable {// Fieldsprivate Integer keyId;public Credence() {}public Credence(Integer keyId) {this.keyId = keyId;} public Integer getKeyId() {return this.keyId;}public void setKeyId(Integer keyId) {this.keyId = keyId;}public boolean equals(Object obj) {if (obj instanceof Credence) {Credence cd = (Credence) obj;return (keyId.equals(cd.keyId));}return super.equals(obj);}public int hashCode() {return keyId.hashCode();}}public class DemoTest {/** * @param args */public static void main(String[] args) {Credence cd = new Credence();List list = new ArrayList();for(int i=0;i<10;i++){cd.setKeyId(i);list.add(i,cd);}Iterator iterator = list.iterator(); while(iterator.hasNext()) { cd = (Credence)iterator.next(); System.out.println(cd.getKeyId()); }}}怎么无法遍列出对像的,输出都是9,麻烦高手帮我解决,谢谢!
解决方案
# Credence cd = new Credence(); # List list = new ArrayList(); # for(int i=0;i<10;i++){ # cd.setKeyId(i); # list.add(i,cd); # } 里的代码修改成# Credence cd ; # List list = new ArrayList(); # for(int i=0;i<10;i++){ # cd = new Credence();# cd.setKeyId(i); # list.add(i,cd); # } 每次新建一个Credence对象,不然一直再操作同一个。。。。
解决方案二:
Credence cd = new Credence(); List list = new ArrayList(); for(int i=0;i<10;i++){ cd.setKeyId(i); list.add(i,cd); } 里代码改为 Credence cd ; List list = new ArrayList(); for(int i=0;i<10;i++){ cd = new Credence(); cd.setKeyId(i); list.add(i,cd); } 不然一直操作的都是同一个Credence对象...