java - 向 ArrayList 项目添加 1

标签 java

我正在检查 3600 万次掷骰子后骰子总数的频率。我计划制作一个 arrayList,并在出现 11 个结果中的任何一个时将其用作计数系统。如何将 1 添加到列表中的一项?

int die1, die2, dicetotal;

ArrayList<Integer> results = new ArrayList<Integer>();  
results.add(0); //for the 11th

for(int i = 0; i < 36000000; i++){
          die1 = (int)(Math.random() * 6) + 1
          die2 = (int)(Math.random() * 6) + 1
          dicetotal = die1 + die2;

          Switch (dicetotal){
                 case 2: results.set(0, CURRENT + 1);
                 ...
                 ...
                 ...

      }

最佳答案

ArrayList 对此来说有点过分了。但如果你必须的话,(未经测试的代码)

首先将数组初始化为包含 13 个元素(0 到 12),这样 IndexOutOfBoundsException 就不会弹出。它们将被初始化为零。

results = new ArrayList<Integer>(13);

然后获取元素,添加一个,然后设置它

results.set(dicetotal, results.get(dicetotal) + 1);
<小时/>

事实上,如果您事先知道数组的大小,并且在程序过程中不会改变,则应该使用 int[] 。它们比 ArrayList 更快。

// initialize
results = new int[13];
// could be new int[11]; if you put results in array elements 0 to 10.

// ...

// add to tally
results[dicetotal]++;

// or, instead, pack the array because dice roll results can only be in 2 to 12. 
// Put such results in array element 0 to 10, 
// by subtracting 2 to the index before putting in
results[dicetotal - 2]++;

关于java - 向 ArrayList 项目添加 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17129638/

相关文章:

java - org.eclipse.ui.texteditor.* 类型不可见

java - 最小化/最大化java swing gui执行actionPerformed方法

java - SwipeRefresh 布局进度条即使完成后也不会隐藏

java - String.replaceAll 奇怪的行为

java - JPA直接返回query.getSingleResult()时返回null

java - Android NDK jni问题

java - 如何在多次加载页面的情况下只调用一次方法?

java - 使用 Java 和 Thymeleaf 提交表单

java - 查找具有完全相同属性的元素

java - 是否值得为新的 Web 项目确认 JSR 286 portlet?