2014-03-12 25 views
-3

每次創建新的會話標識時,我都需要將它們保存在數組或列表中,以將其作爲參考。將我的sessionId追加到arrayList

糾正我在哪裏,我錯了

public static void main(String args[]) { 

//creating an arrayList 

ArrayList<String> myList = new ArrayList<String>(); 

try { 

// calculate the sessionId 

String sessionId = "b03c0-000-5h6-" + uuid.substring(0,4) + "-000000000"; 
myList.add(sessionId); 

} catch(Exception e){ 
e.printStackTrace(); 
} 

}

在我的ArrayList中的元素越來越更換,不追加。

如果我錯了

+0

你是如何斷言元素被替換的? – sanbhat

+0

這是不可能的。 – Maroun

+0

「ArrayList」中的元素沒有被替換,每次調用main方法時都會替換完整的'ArrayList'!然後它看起來像元素被替換。 – kai

回答

-1

它發生,因爲你正在創建每次新的對象

ArrayList<String> myList = new ArrayList<String>(); // creates an object evrytime whem main will be called. 

try { 
String sessionId = "b03c0-000-5h6-" + uuid.substring(0,4) 
/* from where uuid is comming?? */ 
+ "-000000000"; 
     myList.add(sessionId); 
// thiss will add inside new arraylist not in previous, 
// because everytime it is getting new object reference 
    } catch(Exception e){ 
    e.printStackTrace(); 
    } 

     } 
+1

每次我都看不到一個新對象.. – Maroun

+0

'main'被調用一次。 – Maroun

+0

^是的,但對「新」的呼籲可能在for循環。 –

1

你錯了。

List接口被設計成存儲具有重複值的值。所以你會追加。如果您只需要使用Set而不是唯一的結果。

Collection<String> myList = new HashSet<String>();

注意,List和Set是數學概念都代表集合。在Java Collection框架這些概念軟件再現作爲類和接口。

Collection<T>是Set和List的超級接口。這使您可以根據實現更改程序的行爲。

您還應該避免在變量中使用類名,以獲得靈活性。

如果你想「告訴」其他開發商的會話ID儲存,唯一的值用

Set<String> sessionsIDs = new HashSet<String>();

如果你想「說」,認爲貯存在列表的形式(即允許重複)使用

List<String> sessionsIDs = new ArrayList<String>();


如果你想保持隱藏實現,詳細說明,使用集合

Collection<String> sessionsID = crateSessionStorage(); 

private Collection<String> crateSessionStorage() { 

    boolean useUniqueStorage = isUniqueStorage(); 

    if(UseUniqueStorage) { 
     return new HashSet<String>(); 
    } 

    return new ArrayList<String>(); 
} 
+0

@Maroun Maroun那是什麼改變? –

+1

你的代碼很好,但不鼓勵它那麼極端,'Set'就足夠作爲一個*界面*(如果你喜歡這種風格,你可以回滾 - 對不便之處抱歉)。 – Maroun

+0

我是我編輯的中間。但好奇爲什麼。在那個狀態下,你有權編輯。所以沒有道歉需要。祝你今天愉快 ;-)。 –

0

在代碼中創建/初始化myList會導致意外的行爲。

您的ArrayList可以是您的類的靜態實例屬性,而不是每次調用該方法時創建。

0
String sessionId = "b03c0-000-5h6-" + uuid.substring(0,4) + "-000000000"; myList.add(sessionId); this put in loop other when you call main() it replace full arraylis 
+0

public static ArrayList myList = new ArrayList (); //根據我這應該工作..但得到了一個錯誤,無效標識符爲公共靜態.. – user1333420

+0

,因爲你聲明你的數組裏面的靜態main()你應該聲明arraylist之外main()或之前main() –