0

So I am very new to Java programming and I am using netbeans. My question is I already have 5 arrays but I want to put all their data into one large array so it can be better referenced later on in my project. I have researched this some but I am confused without it applying to my code itself or a better explanation. I think it has something to so with multiple square brackets but I am not really sure how to do this.

    int[] particle1;
    particle1 = new int[3];
    particle1[0] = 0;  //x
    particle1[1] = 0;  //y
    particle1[2] = 1;  //weight 

    int[] particle2;
    particle2 = new int[3];
    particle2[0] = 0;   //x
    particle2[1] = 2;   //y
    particle2[1] = 1;   //wieght 

    int[] particle3;
    particle3 = new int [3];
    particle3[0] = 0;
    particle3[1] = 4;
    particle3[2] = 1;


    String[]  allPos;
    allPos = new String[5];
    allPos[0] = particle1;
    allPos[1] = particle2;
    allPos[2] = particle3;

    System.out.println("The position of all of them  and there weight is: " + 
        java.util.Arrays.toString(allPos));
    System.out.println(" Hello World!");`
rgettman
  • 176,041
  • 30
  • 275
  • 357
Pi_Co
  • 121
  • 6

4 Answers4

2
int[][] particles=new int[3][3];

particles[0][0]=0; //particle 1 x value
particles[0][1]=0; //particle 1 y value
particles[0][2]=1; //particle 1 weight value

particles[1][0]=0; //particle 2 x value
particles[1][1]=2; //particle 2 y value
particles[1][2]=1; //particle 2 weight value

particles[2][0]=0; //particle 3 x value
particles[2][1]=4; //particle 3 y values
particles[2][2]=1; //particle 3 weight value
Naili
  • 1,564
  • 3
  • 20
  • 27
1

What you need is maybe a double array like for example:

int[][] particle = new int[][] {{0, 1, 1}, {1, 2, 3}, {1, 2, 3}};
1

If you're looking for a 'multi-dimensional' array, you can set it up like this:

int[][] allPos = new int[][5];
allPos[0] = particle1;
allPos[1] = particle2;
allPos[2] = particle3;

However, if you're wishing to 'concatenate' the 5 arrays into 1 long array, you might want to look at this question: How can I concatenate two arrays in Java?

Without introducing a library, your code will probably look like this:

int[] concat(int[] A, int[] B) {
   int aLen = A.length;
   int bLen = B.length;
   int[] C = new int[aLen+bLen];
   System.arraycopy(A, 0, C, 0, aLen);
   System.arraycopy(B, 0, C, aLen, bLen);
   return C;
}

and then

int[] allPos = concat(particle1, particle2);
allPos = concat(allPos, particle3);
//result = concat(allPos, particle4)
Community
  • 1
  • 1
1

That would be a 2-dimensional array: int[][] particle = new int[3][3]; (where the first [] points to the particle and the second [] points to its value)

Example: particle[0][2] = 1; (equivalent to particle1[2] = 1;)

Solarsonic
  • 21
  • 4