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



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

以下是

您要遵循的逻辑:

1:遍历数组"行为"列表

2:检查指定的"行为"

3:如果"act"等于指定的"act",则在计数器变量中添加一个(votes++)

这是我在没有代码的情况下提供的信息,以显示您尝试过的内容!

您可以使用地图:

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);
       }
   }
}

您可以在 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
    }
}

效率稍高的计票器。

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();
   }
}

你可以使用new int[1]而不是AtomicInteger但它相对丑陋。 ;)

最新更新