Java - 每次调用方法时,将int size方法的值增加1

时间:2012-12-03 17:42:51

标签: java arrays count field add

我坚持这个问题我无法理解。我需要编写一种方法,将特定“行为”的“投票”数量增加一个,然后打印出该特定行为的更新投票数。我也在这里使用ArrayLists来指出。

4 个答案:

答案 0 :(得分:1)

以下是您要遵循的逻辑:

1:遍历“act”的ArrayList

2:检查指定的'act'

3:如果'act'等于指定的'act',请在你的计数器变量中添加一个(投票++)

这是我提供的信息,无需代码即可显示您尝试过的内容!

答案 1 :(得分: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);
       }
   }

}

答案 2 :(得分: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
    }
}

答案 3 :(得分: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],但它相对难看。 ;)