2

I created this code for adding customer objects to a list. But it is getting only first and last objects only. What's wrong of it.

import java.util.*;
class List{
    Customer ptr;   
    public void add(Customer customer){
        Customer temp = customer;
        if(ptr==null){
            ptr = temp;
        }else{                                  
            ptr.next = temp;
        }       
    }   
    public int size(){
        int size = 0;
        Customer temp = ptr;
        while(temp!=null){
            size++;         
            temp = temp.next;
        }
        return size;
    }
    public void printList(){
        Customer temp = ptr;
        while(temp!=null){
            System.out.println(temp);       
            temp = temp.next;
        }
    }

}
class Demo{
    public static void main(String args[]){
        List list = new List();
        Customer c1 = new Customer("1001","Danapala");
        Customer c2 = new Customer("1002","Gunapala");
        Customer c3 = new Customer("1003","Somapala");
        Customer c4 = new Customer("1004","Amarapala");
        list.add(c1);
        list.add(c2);
        list.add(c3);       
        list.printList();           
        System.out.println(list.size());
    }
}
class Customer{
    String id;
    String name;
    Customer next;
    public Customer(String id, String name){
        this.id = id;       
        this.name = name;
    }
    public String toString(){
        return id+" : "+name;
    }
    public boolean equals(Object ob){
        Customer c=(Customer)ob;
        return this.id.equals(c.id);
    }
}` 
4

2 回答 2

1

您继续覆盖第二项。改变:

public void add(Customer customer){
        Customer temp = customer;
        if(ptr==null){
            ptr = temp;
        }else{                                  
            ptr.next = temp;
        }       
    } 

至:

public void add(Customer customer){
    Customer temp = customer;
    if(ptr==null){
        ptr = temp;
    }else{
        Customer runner = ptr;    
        // go over the items of the list until you reach the 
        // last item (its "next" field is set to null)             
        while(runner.next != null){ 
            runner= runner.next;
        }
        // now set the customer as the last item
        runner.next= temp;
    }       
} 
于 2013-08-09T18:22:16.450 回答
0

以下:

    Customer temp = customer;
    if(ptr==null){
        ptr = temp;
    }else{                                  
        ptr.next = temp; // <<<< 
    }       

失去原来的价值ptr.next。因此,您的列表仅保留您添加的第一个和最后一个元素。

于 2013-08-09T18:21:11.433 回答