2012-03-26 100 views
0

目前,我有ArrayList,當它們被添加到俱樂部時,對象被存儲在其中。我也有一個整數,一旦一個對象被添加到ArrayList中,它就會自動遞增。但是,我不確定我能夠如何在ArrayList中添加播放器對象的註冊ID。添加到Java中ArrayList中的元素?

+0

你的Player類是怎麼樣的? Player類有一個int int registrationId屬性嗎? – Kent 2012-03-26 16:52:50

+0

你的'Player'類是什麼樣的?如果我可以假設'Player.setRegID(int)'是被定義的,那麼它會很簡單。 – nobeh 2012-03-26 16:53:32

+2

您的模型不需要您自己增加註冊ID。每次向球員添加新對象時,陣列列表大小將自動遞增。你可以通過players.size()獲得大小。 如果你想問一個當前玩家對象有哪個ID,可以調用players.indexOf(player)。 – andreasg 2012-03-26 16:54:32

回答

2

它是不是從你的描述完全清楚什麼正是你正在嘗試做的,所以我猜是這樣的:

public synchronized void registerPlayer(Player p) 
{ 
    p.setRegistrationId(registrationID++); 
    players.add(p); 
} 
2

一種解決方案是使用Map,其相關聯與特定玩家的個人ID,作爲鍵值對,而不是List

public class Club 
{ 

    private String clubName; 
    private int registrationID; 
    private Map<Player, Integer> players; 

    /** 
    * Create a club with given club name. 
    */ 
    public Club(String clubName) 
    { 
     players = new HashMap<Player, Integer>(); 
     this.clubName = clubName; 
     registrationID = 1; 
    } 

    public void registerPlayer(Player p) 
    { 
     // check if player is already in the club: 
     if (!players.containsKey(p)) { 
      players.put(p, new Integer(registrationID)); 
      // increment ID counter: 
      registrationID++; 
     } 
    } 

    public void listAll() 
    { 
     for (Player p : players.keySet()) { 
      System.out.println(p); 
     } 
    } 

} 
0

嘗試再創建一個類:

public class Registration() { 
    private Player player; 
    private String registrationId; 

    public Registration(Player p) { 
     // Assign p to player 
     // Generate the registration ID 
    } 
} 

然後只需要ArrayList<Registration> registrations來保存所有這些。然後您的listAll()方法將需要引用i.getNext().getPlayer()來執行相同的操作。

0

我猜測玩家有一個你想在添加到數組列表後設置的ID字段?

如果您知道播放器的索引,只需使用get方法獲取對象並設置ID。如果你沒有索引,你將不得不遍歷數組列表來找到你的對象。

相關問題