节点getter不会返回setter值

时间:2015-10-30 03:31:25

标签: java setter getter

编辑:我认为问题在于添加节点。当我开始获取节点时,它们返回null。我相信这是因为head不会被设置,因为impl.getHeadNode()== null永远不会发生。

构造

 public CashDonationLinkedListImpl() {
 iterNode = headNode = new CashDonationNode(null); 
}

添加方法:

public void add(Object obj) {
    CashDonation cashDonation = (CashDonation)obj; 
    CashDonationLinkedListImpl impl = new CashDonationLinkedListImpl(); 

    CashDonationNode node = new CashDonationNode();
        node.setCashDonation(cashDonation); 
        //node.setNext(null);
    if(impl.getHeadNode() == null){

        System.out.println("Head node"); 
        impl.setHeadNode(node); 

      }  
      else{
        //node.setCashDonation(cashDonation); 
        //node.setNext(null); 
        for (CashDonationNode cashNode = headNode;cashNode.getNext() != null;cashNode = cashNode.getNext()) {
           // currNode.setNext(null);
        }        

            //cashNode.setCashDonation(cashDonation);

        cashNode.setNext(node);

      }

原件: 当设置者获得100,100和10000时,getter返回两个零。我确定我忘记做某事但不能把手指放在上面。为什么getter不会从setter中返回值?

public class CashDonationNode {
    CashDonation cashDonation; 
    CashDonationNode next; 

    public CashDonationNode() {
      cashDonation = new CashDonation();
      next = null; 
    }

    public CashDonationNode(CashDonation cashDonation, CashDonationNode next) {
        this.cashDonation = cashDonation;
        this.next = next;
    }

    public CashDonationNode getNext(){
        return next; 
    }
    public void setNext(CashDonationNode nextValue){
        this.next = nextValue;
    }
    public void setCashDonation(CashDonation cashDonation){
        this.cashDonation =  cashDonation;
        System.out.print("node storage");
        System.out.println(this.cashDonation.getDonationAmount()); 
    }

    public CashDonation getCashDonation(){
        System.out.println("node retrieval " + cashDonation.getDonationAmount()); 
                return this.cashDonation; 
    }
}

以下链接列表中的代码段。返回相同的零:

CashDonationNode iterNode = new CashDonationNode(); //declared in class
public void iterator() {
  iterNode = headNode;
}

@Override
public CashDonation next() {
CashDonation cashDonation = iterNode.getCashDonation();
System.out.println("Impl: " + cashDonation.getDonationAmount()); 
  iterNode = iterNode.getNext();
  return cashDonation;
}

1 个答案:

答案 0 :(得分:0)

更正了add():

public void add(Object obj) {
    CashDonation cashDonation = (CashDonation)obj; 
    CashDonationNode node = new CashDonationNode(cashDonation);
    this.setIterNode(node);

    if(this.getHeadNode() == null){
        this.setHeadNode(node);
        node.setNext(null); 
      }  
      else{
        CashDonationNode cashNode; 
        for (cashNode = headNode;cashNode.getNext() != null;cashNode = cashNode.getNext()) {
        }        
        cashNode.setNext(node);
      }
    numElements++; 

}