Java数组问题

Java数组问题,java,arrays,Java,Arrays,我如何创建一个包含5个项目的数组,然后再为每个项目创建一个数组?。我知道如何创建一个由5个项目组成的数组,但我遇到的问题是为每个项目创建一个数组。我假设我需要5个数组,因为有5个项目 int gas = 0; int food = 0; int clothes = 0; int entertainment = 0; int electricity = 0; int[] budget = new int[4]; budget[0] = gas; budget[1] = food;

我如何创建一个包含5个项目的数组,然后再为每个项目创建一个数组?。我知道如何创建一个由5个项目组成的数组,但我遇到的问题是为每个项目创建一个数组。我假设我需要5个数组,因为有5个项目

 int gas = 0;
 int food = 0;
 int clothes = 0;
 int entertainment = 0;
 int electricity = 0;
 int[] budget = new int[4];
 budget[0] = gas;
 budget[1] = food;
 budget[2] = clothes;
 budget[3] = entertainment;
 budget[4] = electricity;

提前感谢

您是说要创建2D阵列吗?预算数组中的每个元素都是另一个数组

你会使用一个循环

int[] budget = new int[5]; //There are 5 elements to be stored in budget, not 4
for (int y = 0; y < 5; y++) {
     budget[y] = new int[5];
}
int[]预算=新的int[5]//预算中要存储的要素有5个,而不是4个
对于(int y=0;y<5;y++){
预算[y]=新整数[5];
}

也许你需要一个矩阵

int[][] budget = new int[4][4];
在第一个索引中保存预算,在第二个索引中保存五个(在上面的例子中)预算项目。
当你有一个矩阵[x][y]时,你有x+1个数组,每个数组都有y+1个元素。

数组中有5个元素

    int[] budget = new int[5];
    budget[0] = gas;
    budget[1] = food;
    budget[2] = clothes;
    budget[3] = entertainment;
    budget[4] = electricity;
您需要二维数组,它基本上是数组的数组。2D数组由2对[]声明。在下面的示例中,每个
预算都有10个详细信息

    String[][] detail = new String[budget.length][10];

如果我理解正确的话,你需要一个2d数组,类似于

int gas = 0;
int food = 1;
int clothes = 2;
int entertainment = 3;
int electricity = 4;
int maxEntries = 10;

int[][] myArray = new int[5][maxEntries];
可通过以下方式访问:

myArray[gas][entryNumber] = 6;
int value = myArray[gas][entryNumber];
但这有多僵硬?您必须提前知道每个“类别”将有多少个条目,或者在添加项目时有代码检查给定的数组长度,在需要更大的项目时创建新数组(并将旧数据复制到其中)

您可能至少需要一个
ArrayList
ArrayList

ArrayList<ArrayList<Integer>> my2dArrayList = 
    new ArrayList<ArrayList<Integer>>();
...
my2dArrayList.get(gas).add(someValue);
int myValue = my2dArrayList.get(gas).get(index);

与其创建一个二维数组来保存逻辑上分组在一起的金额类型(我假设每月一次),不如定义一个数据持有者类,这样您就可以使用这些金额的名称而不是容易出错的索引来访问这些金额

例如(减去getter和setter):


你说“然后为每个项目创建一个数组”是什么意思?听起来你真的想要一个由你的项目键入的
ArrayList
s的
HashMap
。为什么每个项目都需要一个数组?你能举个例子说明你想做什么吗?你为什么要这样做?数组和单个项目代表什么?您所说的每个项目的数组是什么意思?你是说一个气体阵列和一个食物阵列。。。或者你是说你想把预算数组放到另一个数组中?我想你的意思是
int[]budget=newint[5][]你可能是对的-我已经有一段时间没有在Java中这样做了。
HashMap<String, ArrayList<Integer>> myMap = 
    new HashMap<String, ArrayList<Integer>>();
...
myMap.get("gas").add(someValue);
int myValue = myMap.get("gas").get(index);
public class Budget {
    public int gas = 0;
    public int food = 0;
    public int clothes = 0;
    public int entertainment = 0;
    public int electricity = 0;
};

// ....
Budget[] months = new Budget[12];

budget[0].gas = gasCosts;
budget[0].food = foodCosts;
// etc