2013-08-30 185 views
0

下面有一個for循環代碼。我通過調用一個自定義顯示函數發現,aBook arrayList對象只添加了最後一個類對象三次。爲什麼會發生?ArrayList只添加最後一個元素

Scanner s = new Scanner(System.in); 
    ArrayList<LiFiAddressBook> aBook = new ArrayList<LiFiAddressBook>(); 
    // taking input for every LifIAddressBook and adding them to the ArrayList. 
    for (int i = 0; i < 3; i++) { 
     System.out.println("Entry " + i+1); 
     System.out.print("Please Enter First Name: "); 
     String a = s.nextLine(); 
     System.out.println(); 
     System.out.print("Please Enter Last Name: "); 
     String b = s.nextLine(); 
     System.out.println(); 
     System.out.print("Please Enter Street Address: "); 
     String c = s.nextLine(); 
     System.out.println(); 
     System.out.print("Please Enter City: "); 
     String d = s.nextLine(); 
     System.out.println(); 
     System.out.print("Please Enter Zip Code: "); 
     int e = s.nextInt(); 
     // in the next line we need to fire a blank scan function in order consume the nextLine. because after executing s.nextInt compiler skip a scan function for a weird reason 
     s.nextLine(); 
     System.out.println(); 

     LiFiAddressBook x = new LiFiAddressBook(a, b, c, d, e); 
     aBook.add(x); 


    } 

這裏是我的LiFiAddressBook類

public class LiFiAddressBook { 

static String first_name, last_name, street_address, city_state; 
static int zip_code; 

public LiFiAddressBook(String first, String last, String street, String city, int zip) { 
    //constructor for class object. 
    first_name = first; 
    last_name = last; 
    street_address = street; 
    city_state = city; 
    zip_code = zip; 
} 

public String get_first() { 
    return first_name; 
} 

public String get_last() { 
    return last_name; 
} 

public String get_address() { 
    return street_address; 
} 

public String get_city() { 
    return city_state; 
} 

public String get_zip() { 
    return Integer.toString(zip_code); 
} 

public static void display() { 
    System.out.println("First Name: "+first_name); 
    System.out.println("Last Name: "+last_name); 
    System.out.println("Street Address"+street_address); 
    System.out.println("City State: "+city_state); 
    System.out.println("Zip Code: "+zip_code); 


} 

}

+3

鑑於代碼,這是不可能發生的。你能顯示代碼顯示列表元素的位置嗎? –

+0

你如何驗證同一個物體三次? – rocketboy

+7

我懷疑問題出在'LiFiAddressBook'內。可能地,每次創建一個新的'LiFiAddressBook'時,它都會跺跺先前實例化的對象的值(可能會將成員字段聲明爲「靜態」或其他?)。 – ajb

回答

2

由於static關鍵字,每次構造函數
public LiFiAddressBook(String , String , String , String , int)
被調用時,舊值將被新值覆蓋,當列表中的元素打印時,LiFiAddressBook類的對象變量指向相同的對象。因此印刷類似的物體。

要明確,實際上有3個LiFiAddressBook實例。但這些LiFiAddressBook實例的變量/屬性引用相同的對象。

1

取出static關鍵字。實質上,該關鍵字確保這些變量只有一個實例。

1

品牌:

static String first_name, last_name, street_address, city_state; 
static int zip_code; 

分爲:

String first_name, last_name, street_address, city_state; 
int zip_code; 

你也可能需要更改此:

public static void display() { 

要:

public void display() { 
相關問題