この 1 つの質問に頭を悩ませています。特定の「アクト」の「投票」数を 1 増やし、その特定のアクトの更新された投票数を出力するメソッドを作成する必要があります。指摘するために、ここでも ArrayLists を使用しています。
3229 次
4 に答える
1
従うべきロジックは次のとおりです。
1: 'acts' の ArrayList を繰り返します
2: 指定された 'act' を確認する
3: 'act' が指定された 'act' と等しい場合は、カウンター変数 (votes++) に 1 を追加します。
これは、あなたが試したことを示すコードなしで私が提供する情報と同じくらいです!
于 2012-12-03T17:48:59.720 に答える
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]
が、比較的醜いです。;)
于 2012-12-03T18:50:46.090 に答える
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);
}
}
}
于 2012-12-03T17:48:42.567 に答える
0
次のように、オブジェクト全体を Java で出力できます。
System.out.println("Array list contains: " + arrayListName);
これは、構文が変かもしれませんが、各値を繰り返し処理せずに配列の内容を出力します。オブジェクトを意味すると思われる「行為」については、投票数を1つずつ繰り返したい場合は、次のようなクラスを作成できます。
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
}
}
于 2012-12-03T17:57:27.333 に答える