2012-12-03 26 views
0

我困在這個問題中,我無法得到我的頭。我需要編寫一種方法,將某個特定「行爲」的「投票」數量增加一個,然後列出該特定行爲的更新投票數。我也在這裏與ArrayLists合作指出。Java - 每次調用該方法時將int大小方法的值增加1

+1

你遇到的問題是什麼? –

+0

清除您的arraylist之前打電話,然後當你開始他們清除方法,新的數據是有用的新arrylist – QuokMoon

回答

0

你可以使用地圖:

Class VoteCounter { 

    Map<Integer, Integer> actToCounterMap = new HashMap<Integer, Integer>(); 


    public void raiseVoteForAct(int actId) { 
     if (actToCounterMap.contains(actId) { 
     int curVote = actToCounterMap.get(actId); 
     curVote++; 
      actToCounterMap.put(actId, curVote); 
     } else { 
      // init to 1 
      actToCounterMap.put(actId, 1); 
     } 
    } 

} 
1

這裏是要遵循的邏輯:

1:檢查指定的「行爲:通過 '行爲'

2的ArrayList迭代「

3:如果 '行爲' 等於指定的 '行爲',添加一個到你的計數器變量(票++)

這是儘可能多的信息,因爲我會給出沒有代碼顯示你已經嘗試過的東西!

0

可以打印整個對象出在Java中,如

System.out.println("Array list contains: " + arrayListName); 

,它將打印數組的內容,而無需通過每個值迭代,儘管它可以具有奇數語法。至於「行爲」,我以爲你的意思是對象,如果你想通過一個迭代的票數,你可以有一個這樣的類:

public class Act{ 
    int votes = 0; 

    public void increaseVote(){ 
     votes ++; 
     //You can also do votes = votes + 1, or votes += 1, but this is the fastest. 
    } 

    //While were at it, let's add a print method! 
    pubic void printValue(){ 
     System.out.println("Votes for class " + this.getClass().getName() + " = " + votes + "."); 
    } 
} 

最後,對於該ArrayList類:

class classWithTheArrayList { 
    private ArrayList<Act> list = new ArrayList<Act>(); 

    public static void main(String[] args){ 
     Act example1 = new Act(); 

     list.add(example1); 
     //ArrayLists store a value but can't be changed 
     //when in the arraylist, so, after updating the value like this: 

     Act example2 = new Act(); 
     example2.increaseVote(); 
     //we need to replace the object with the updated one 
     replaceObject(example1, example2); 
    } 


    public void replaceObject(Object objToBeRemoved, Object objToReplaceWith){ 
     list.add(objToReplaceWith, list.indexOf(objToBeRemoved); //Add object to the same position old object is at 
     list.remove(objToBeRemoved); //Remove old object 
    } 
} 
0

一個稍微有效的投票計數器。

class VoteCounter<T> { 
    final Map<T, AtomicInteger> actToCounterMap = new HashMap<>(); 

    public void raiseVoteForAct(T id) { 
     AtomicInteger ai = actToCounterMap.get(id); 
     if (ai == null) 
      actToCounterMap.put(id, ai = new AtmoicInteger()); 
     ai.incrementAndGet(); 
    } 
} 

相反的AtomicInteger可以使用new int[1]但它是比較醜。 ;)

相關問題