我困在這個問題中,我無法得到我的頭。我需要編寫一種方法,將某個特定「行爲」的「投票」數量增加一個,然後列出該特定行爲的更新投票數。我也在這裏與ArrayLists合作指出。Java - 每次調用該方法時將int大小方法的值增加1
0
A
回答
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]
但它是比較醜。 ;)
相關問題
- 1. 遞歸方法 - 在每次調用時增加一個值
- 2. 每次調用JNI方法時附加值
- 3. 返回一個數組值,每個方法調用從索引0開始,每次調用時遞增1。
- 4. 方法to_pickle增加文件大小
- 5. java調整大小的方法
- 6. 每次加載某個頁面時調用一次方法(AngularJS)
- 7. Java Hotspot命令行參數用於增加Java方法的最大大小
- 8. int值變大時發送到方法
- 9. 每次調用任何其他方法之前調用方法
- 10. 如何在Rails中每小時調用一次方法?
- 11. init()方法調用在每次請求
- 12. 方法調用後不會增加的Int實例變量
- 13. Java方法()++ VS方法()+ 1
- 14. 每x分鐘調用一次方法
- 15. Java最小最大值方法
- 16. CodeIgniter - 小時方法調用
- 17. Selenium:每次頁面加載時調用方法
- 18. ArrayList大小增加每個onCreateView調用
- 19. 每次調用函數時都會增加一個Int?
- 20. 排隊方法,當隊列已滿時增加數組大小
- 21. 如何在iOS中每1秒自動調用一次方法?
- 22. 每x分鐘調用一次方法
- 23. 方法沒有被每次調用
- 24. Objective-C每月調用一次方法
- 25. 爲什麼每次我調用它時都會執行兩次該方法?
- 26. 可以從方法內部再次調用該方法嗎?
- 27. 將Color設置爲用於setRGB(int x,int y,int rgb)方法的int值? - Java
- 28. 被調用9次的方法,應該調用一次
- 29. int和++新增每次增加2
- 30. 每次調用任何方法時調用宏 - 目標C
你遇到的問題是什麼? –
清除您的arraylist之前打電話,然後當你開始他們清除方法,新的數據是有用的新arrylist – QuokMoon