首页 > 代码库 > List的设置值,跟变量的位置关系(变量范围的变化导致结果差别很大)

List的设置值,跟变量的位置关系(变量范围的变化导致结果差别很大)

我们想要的结果是:

[RegnTypeCharge: null,null,null,null,1,null,null,null,null,null,null,null,null,null,null,]
[RegnTypeCharge: null,null,null,null,hehe,null,null,null,null,null,null,null,null,null,null,]
com.kompakar.ehealth.model.regn.mstr.common.view.RegnTypeChargeView@addbf1
com.kompakar.ehealth.model.regn.mstr.common.view.RegnTypeChargeView@42e816

需要的代码是:

package com.kompakar.ehealth.server.regn.mstr.common.service.impl;

import java.util.ArrayList;
import java.util.List;

import com.kompakar.ehealth.model.bridge.bo.RegnTypeCharge;
import com.kompakar.ehealth.model.regn.mstr.common.view.RegnTypeChargeView;

public class Test {

/**
* @param args
*/
public static void main(String[] args) {

RegnTypeCharge bo = new RegnTypeCharge();
bo.setVisitType("1");
RegnTypeCharge bo2 = new RegnTypeCharge();
bo2.setVisitType("hehe");

List<RegnTypeCharge> list = new ArrayList<RegnTypeCharge>();
list.add(bo);
list.add(bo2);


List<RegnTypeChargeView> list2 = new ArrayList<RegnTypeChargeView>();

// RegnTypeChargeView view = new RegnTypeChargeView();
for(int i=0; i < list.size(); i++){
RegnTypeChargeView view = new RegnTypeChargeView();
view.setRegnTypeCharge(list.get(i));
list2.add(view);

}

System.out.println(list2.get(0).getRegnTypeCharge());
System.out.println(list2.get(1).getRegnTypeCharge());
System.out.println(list2.get(0));
System.out.println(list2.get(1));

}

}

 

而如果这么写的话:

package com.kompakar.ehealth.server.regn.mstr.common.service.impl;

import java.util.ArrayList;
import java.util.List;

import com.kompakar.ehealth.model.bridge.bo.RegnTypeCharge;
import com.kompakar.ehealth.model.regn.mstr.common.view.RegnTypeChargeView;

public class Test {

/**
* @param args
*/
public static void main(String[] args) {

RegnTypeCharge bo = new RegnTypeCharge();
bo.setVisitType("1");
RegnTypeCharge bo2 = new RegnTypeCharge();
bo2.setVisitType("hehe");

List<RegnTypeCharge> list = new ArrayList<RegnTypeCharge>();
list.add(bo);
list.add(bo2);


List<RegnTypeChargeView> list2 = new ArrayList<RegnTypeChargeView>();

RegnTypeChargeView view = new RegnTypeChargeView();
for(int i=0; i < list.size(); i++){
// RegnTypeChargeView view = new RegnTypeChargeView();
view.setRegnTypeCharge(list.get(i));
list2.add(view);

}

System.out.println(list2.get(0).getRegnTypeCharge());
System.out.println(list2.get(1).getRegnTypeCharge());
System.out.println(list2.get(0));
System.out.println(list2.get(1));

}

}

将导致这样的结果

[RegnTypeCharge: null,null,null,null,hehe,null,null,null,null,null,null,null,null,null,null,]
[RegnTypeCharge: null,null,null,null,hehe,null,null,null,null,null,null,null,null,null,null,]
com.kompakar.ehealth.model.regn.mstr.common.view.RegnTypeChargeView@addbf1
com.kompakar.ehealth.model.regn.mstr.common.view.RegnTypeChargeView@addbf1