Go4Expert

Go4Expert (http://www.go4expert.com/)
-   Java (http://www.go4expert.com/articles/java-tutorials/)
-   -   Multi-dimensional arrays in Java (http://www.go4expert.com/articles/multi-dimensional-arrays-java-t1162/)

pradeep 11Aug2006 14:36

Multi-dimensional arrays in Java
 
Multi-dimensional arrays

Java, as with most languages, supports multi-dimensional arrays - 1-dimensional, 2-dimensional, 3-dimensional, ... This discusses 2-dimensional arrays, but the same principles apply to higher dimensions.

2-dimensional arrays


2-dimensional arrays are usually represented in a row-column approach on paper, and the terms "rows" and "columns" are used in computing.
Arrays of arrays

There are two ways to implement 2-dimensional arrays. Many languages reserve a block of memory large enough to hold all elements of the full, rectangular, array (number of rows times number of columns times the element size). Java doesn't do this. Instead Java builds multi-dimensional arrays from many one-dimensional arrays, the so-called "arrays of arrays" approach. [C++ supports both styles.]

There are a couple of interesting consequences of this: Rows may be different sizes. Also, each row is an object (an array) that can be used independently.

Declaration

Declare a 2-dimensional array as follows:

Code: Java

int[][] a2; // Declares, but doesn't allocate, 2-dim array.
 


Allocation

As with all arrays, the new keyword must be used to allocate memory for an array. For example,

Code: Java

int[][] a2 = new int[10][5];


This allocates an int array with 10 rows and 5 columns. As with all objects, the values are initialized to zero (unlike local variables which are uninitialized).

This actually allocates 6 objects: a one-dimensional array of 5 elements for each of the rows, and a one-dimensional array of ten elements, with each element pointing to the appropriate row array.

Processing 2-dimensional arrays

Often 2-dimensional arrays are processed with nested for loops. Notice in the following example how the rows are handled as separate objects. For example,

Code: Java

int[][] a2 = new int[10][5];
 // print array in rectangular form
 for (int r=0; r<a2.length; r++) {
     for (int c=0; c<a2[r].length; c++) {
         System.out.print(" " + a2[r][c]);
     }
     System.out.println("");
 }


Uneven rows

One consequence of arrays of arrays is that each row can be a different size ("ragged" arrays). For example, we could create a lower triangular array, allocating each row "by hand" as follows.

Code: Java

int[][] tri;
 tri = new int[10][]// allocate array of rows
 for (int r=0; r<tri.length; r++) {
     tri[r] = new int[r+1];
 }
 
 // print the triangular array (same as above really)
 for (int r=0; r<tri.length; r++) {
     for (int c=0; c<tri[r].length; c++) {
         System.out.print(" " + tri[r][c]);
     }
     System.out.println("");
 }


abcdou 12Aug2006 13:14

Re: Multi-dimensional arrays in Java
 
hi pradeep!

how about if the user will input student information?
Label(row 0) Lastname firstname address
dou abc malaysia

There are method()
1.Assign name
2.Display name
3.Sort name in ascending
4.Search name

how to do this pradeep
pls........

pradeep 12Aug2006 14:18

Re: Multi-dimensional arrays in Java
 
We will use a multi-dimensional array.

Code: Java

String[][] Data;
 
 //Assign the values, do it either dynamically or statically
 //For first fow
 Data[0][0] = "S"; //lastname
 Data[0][1] = "Pradeep"; //firstname
 Data[0][2] = "Kolkata"; //location
 
 //Second row
 Data[1][0] = "Bhimani"; //lastname
  Data[1][1] = "Shabbir"; //firstname
  Data[1][2] = "Kolkata"; //location
 
 //Add as many rows you want
 
 //printing
 System.out.print("Lastname\tFirstname\tLocation\n");
 for(i=0;i<2;i++)
 {
   for(j=0;j<3;j++)
   {
     System.out.print(Data[i][j]+"\t");
   }
   //move to new line
   System.out.print("\n");
 }



This should do the work for you.

abcdou 14Aug2006 05:02

Re: Multi-dimensional arrays in Java
 
thank you pradeep!!!

how about sorting and searching?

do you have any tutorial in two dimensional array?


thanks.....

pradeep 14Aug2006 11:31

Re: Multi-dimensional arrays in Java
 
You can use simple sorting algorithms like Bubble Sort,Selection Sort to sort the array data. Multi-dimensional array concepts can be applied to two-dimensional arrays. You are free to ask any specific questions you have about two-dimensional arrays.

abcdou 19Aug2006 09:08

Re: Multi-dimensional arrays in Java
 
how about in searching?

thanks pradeep

champion 12Jul2007 17:37

Re: Multi-dimensional arrays in Java
 
How do we test if the array is null not testing for a null element?

champion 12Jul2007 19:56

Re: Multi-dimensional arrays in Java
 
Quote:

Originally Posted by pradeep
We will use a multi-dimensional array.

Code: Java

String[][] Data;
 
 //Assign the values, do it either dynamically or statically
 //For first fow
 Data[0][0] = "S"; //lastname
 Data[0][1] = "Pradeep"; //firstname
 Data[0][2] = "Kolkata"; //location
 
 //Second row
 Data[1][0] = "Bhimani"; //lastname
  Data[1][1] = "Shabbir"; //firstname
  Data[1][2] = "Kolkata"; //location
 
 //Add as many rows you want
 
 //printing
 System.out.print("Lastname\tFirstname\tLocation\n");
 for(i=0;i<2;i++)
 {
   for(j=0;j<3;j++)
   {
     System.out.print(Data[i][j]+"\t");
   }
   //move to new line
   System.out.print("\n");
 }



This should do the work for you.

How do we test if the array is null not testing for a null element?

shilpa dessai 20Mar2008 15:08

Re: Multi-dimensional arrays in Java
 
Pradeep please reply soon we have to complete our project and we are stuck only due to this sorting code.......

pradeep 20Mar2008 15:32

Re: Multi-dimensional arrays in Java
 
Please post the 1D sorting you have already written!

itzkloive 23Mar2008 19:51

Re: Multi-dimensional arrays in Java
 
Can some one help a novice

I am kinda teaching myself java and got stuck trying to create a a program to translate 10 words bi-directional from english to spaniah, using two different String Arrays one consist of english words and one consist of spanish words. Can someone help this novice out?


import java.io.*;//tell Java we are using java.io libary.
import java.util.*;//Java utility package also for Scanner class

public class transWords //Naming the program.
{

public static void main(String[ ]args)throws Exception
{
//This set-up allow for user to input using keyboard.
Scanner input= new Scanner(System.in);


//Declaring Array String.
String[]englishTrans={"color","white","blue","green","blac k","purple",};
//Declaring Array String.
String[]spanishTrans={"en color","blanco","azul","verde","negro","purp˙reo", };

pradeep 23Mar2008 22:33

Re: Multi-dimensional arrays in Java
 
What's the exact nature of help you are looking for? the code snippet is probably incomplete!

shilpa dessai 26Mar2008 18:34

Re: Multi-dimensional arrays in Java
 
hi Pradeep,
For sorting a 1D array we used the simply Bubble sort aLgorithm which worked perfectly fine...but we cant write the code 4 the 2D array as we had written earlier....
thx...
Shilpa

Mazharul 11Aug2008 14:18

Re: Multi-dimensional arrays in Java
 
sir,
i want to show a 2D array corresponding to a .jpg/.gif/.png image file in a separate window. suppose i have...
class Image {
protected int width,height;
// 'samples' stores the image pixel values.
protected int[][] samples;
// Constructor: Reads the image from the
// specified file name.
public Image(String filename)
throws Exception { read(filename); }
// Returns the pixel width of the image.
public int getWidth() { return width; }
// Returns the pixel height of the image.
public int getHeight() { return height; }
// Reads the image from the specified file
// name into the 'samples' array. Throws an
// exception if the image is stored in an
// unsupported file format (currently only
// .GIF, .JPG, and .PNG are supported by Sun).
public void read(String filename)
throws Exception {
// Extract the file name suffix...
.......
...........
.............
from the startup java file like..
import java.awt.*;
import javax.imageio.*;
class TestImage {
public static void main(String args[])
throws Exception {
// Create a frame to display the image.
Frame frame = new Frame("Test Image");
frame.setSize(1024,768);
frame.setVisible(true);
Graphics gc = frame.getGraphics();
try {
// Read the image from the file.
Image img = new Image("Horse.jpg");
.........

I want to access the int [][] samples array then want to disply this array values in a separate windo or applet..How to approach......

majidpucit123 9Sep2008 12:24

Re: Multi-dimensional arrays in Java
 
i'm trying to create a method that adds an element in an existing string array. Kind of like the arraylist "add()" method.
so far, i have this

String[] addToArray(String[] strArray1, String s)
{
return strArray1+s;

}



but this doesnt work...
why?
:worried:

pradeep 9Sep2008 14:16

Re: Multi-dimensional arrays in Java
 
There already exists such a method, it's called push!

new2Java 10Dec2008 03:41

Re: Multi-dimensional arrays in Java
 
Hi!

I need to compare 2 words in a given name and see if any part of the name in index [0] (first name and/or surname) matches the rest of the names. For instance,

robert smith | robert mathews | john robert | john roberts

Basically, only the first and lastname in the first index ("robert smith") needs to be compared with rest of the first and the last names. '

How do I go about this?

I'm successful in comparing just 1 word. eg: robert|RoBERT|smith
boolean result1= choiceKeys[0].equalsIgnoreCase (choiceKeys[i+1]);

What should I do when I have 2 words?

Thanks in advance,
-new2Java

thusha 13Aug2009 13:20

Re: Multi-dimensional arrays in Java
 
Hai
I am inteested in adding elements to 2D array.
So i do like this
i have always one input as prod id ; where i get from parameter

then the for loop
Code:

int n = productsid;
                 
                              for( row=0;row<10;row++) {                     
                    year2007[n][row] = (float) tot;
              }

but when i display my array
i dont get the prod id?? what ican do ??

Theone 17Dec2009 18:30

Re: Multi-dimensional arrays in Java
 
Hi Pradeep,
Can you use a 2d array to make a chess board and store the pieces within it?.

technica 18Dec2009 09:58

Re: Multi-dimensional arrays in Java
 
Thanks for posting. A article on handling arrays for sorting and searching would be great.

afredi786 30Jan2010 02:42

Re: Multi-dimensional arrays in Java
 
Sir Can yo Kindly tell me how to multiply two arrays. or you can say if we want to multiply numbers in two string and save result in another string.how will i will be able to do it.

e.g string1= "3298733333233121215455"
string2= "98234234239847239847239482"
how can i multiply them and save them in string3.

Harishgp 15Feb2010 12:08

Multi-dimensional arrays in Java
 
Hi,
Can someone tell me how to generate general "n dimensional arrays"?. (i.e) I am given the number of dimensions and the length along each dimension as arguments to a function , I need to generate such an array in that function. All I can tell about the number of dimensions before hand is it will be less than 20. (Assume the lengtth along dimensions are such that the number of elements don't go beyond memory).


Thanks,
Harish

Bearcat20 25Apr2010 04:47

Re: Multi-dimensional arrays in Java
 
I am studying for my Programming 1 final and I am having a little trouble with this problem on my study guide. Any assistance would be greatly appreciated. The problem is as follows.

Show how to declare a 2 dimensional array of integer values. This array should have 5 rows and 300 columns. Next, show the code necessary to fill this array with random values ranging from 0 up to 99 (including both 0 and 99). Finally, show the code necessary to sum up the values in each column and display the sum of each on the screen.

srkanth_rks 20May2010 23:23

Re: Multi-dimensional arrays in Java
 
MATLAB scans column-wise the input matrix and writes them column-wise into the new matrix of specified matrix. Now i need to do that in Java, not a generic reshape, but for some specific cases. One of them is to transform a 1D array a[50400] into this 7D array c[2][12][4][5][5][7][3]. please, suggest how to do this.

marcox4 14Aug2010 21:12

Re: Multi-dimensional arrays in Java
 
Would anybody know how to get user input into a muti-array in netbeans, from two diffrent textfields?

shivika 28Oct2010 01:11

Re: Multi-dimensional arrays in Java
 
How can i implememt a gauss jacobi iteration in java programming language...using multi dimentional array and asking the user to enter all the details(No.of row, columns, the elements...).

thanks and regards....

shivika 29Oct2010 01:07

Re: Multi-dimensional arrays in Java
 
hello,
im having problem to implement a gauss jacobi iteration in java...
can som1 please help me....

rameshb 13Dec2010 13:12

Re: Multi-dimensional arrays in Java
 
Thank you pradeep for uploading it in this forum . the example code are superb.. chow

yellowscooter 15Dec2010 22:18

Re: Multi-dimensional arrays in Java
 
Multi-dimensional arrays are powerful constructs in Java. However, most of the times its better to an VO class, and store these objects in a List or a Map. This approach is more object oriented, and much easier to implement and understand.

rameshb 20Dec2010 14:28

Re: Multi-dimensional arrays in Java
 
thank you for submitting this code ...

mikkko 28Jul2011 21:11

Re: Multi-dimensional arrays in Java
 
pradeep, can you help me with this please

Create an addressbook program that asks for user input and could store until 15 entries using multi-dimensional array.

Note: Use JOptionPane or BufferedReader for the user input and program output.

Here is the sample format:
Name : Florence Santiago
Tel# : 735-1234
Address : Manila

Name : Joyce Jimenez
Tel# : 983-33333
Address : Quezon City

Name : Becca Singson
Tel# : 456-12345
Address : Pasig City

The number of entries to be displayed will be based on the number of addressbook entries inputted by the user.

finedesignnyc 28Jul2011 21:39

Re: Multi-dimensional arrays in Java
 
Does all of this work well with any version of Java?

weebo123 21Oct2011 20:40

Re: Multi-dimensional arrays in Java
 
Hi Pradeep,

I have recently decided to do some Android Game Development using Java. However I am having the below issue:

I am looking at creating a 2D birdseye view of a map where the user is basically working there way through it.

Is there a way that I can create the whole map in 1 go and store it somewhere. Then simply only display a certain section of that map during gameplay.
e.g map size =100 x 100 but user can only ever see 5x5 (which is zoomed tin to use up 70% of the screen).

I am thinking of using a 2d java array of bitmaps and using this array to draw onto a canvas. However, I am not entirly sure how to do this, as i would also like that every time the player moves their character forward a step, the next section of the canvas is drawn (always 5 x 5 regardless of whether they go left, right, straight or back).

Any help as to how I could go about doing this would be much appreciated.

Thanks

mjshaheed 20Dec2011 10:17

Re: Multi-dimensional arrays in Java
 
Hi Pradeep,

First of all sorry for digging up the old thread! I am learning Java...

I have a question as to how many objects are created in the following code:

Code:

int[][] a2 = new int[10][5];
You said "This allocates an int array with 10 rows and 5 columns. As with all objects, the values are initialized to zero (unlike local variables which are uninitialized).

This actually allocates 6 objects: a one-dimensional array of 5 elements for each of the rows, and a one-dimensional array of ten elements, with each element pointing to the appropriate row array
."

Aren't 10 object(references) created here, each for one row...a[0]....a[9]? Again sorry if i am mistaken!!!

Thanks,
Shahul

lis 28Mar2012 03:38

Re: Multi-dimensional arrays in Java
 
How to do an array in java?
I need to make an array that reads the latitude and longitude.
A for loop that reads into all of them into the array.

latitude Longitude
27.03434 -73.3423
27.02342 -73.2466
........... ...........
........... ...........
...this continues on
So I guess I need an array to read in the rows from the file without knowing the exact number of rows in the file.

double[][] numbers = new double [][];

for (double row = 0; row < numbers.length; row++)
{
for (double col = 0; col < numbers[row].length; col++)
System.out.println(numbers[row][col]);

Can you please help me. This won't work.


I have tried many ways, but can't figure it out.
There are two columns, but the rows of the files are a lot, and I need the array to read the numbers in the rows that are available into the array

mfred90 1Jun2012 18:02

Re: Multi-dimensional arrays in Java
 
To Create two dimensional array dunamically.I know the number of columns. but the number of rows are chnaged dynamically. I have tried array lisy. But it storing single value. so what should I Do ?

cuongedvhp 14Jun2012 12:05

Re: Multi-dimensional arrays in Java
 
There are two ways to implement 2-dimensional arrays. Many languages reserve a block of memory large enough to hold all elements of the full, rectangular, array (number of rows times number of columns times the element size). Java doesn't do this. Instead Java builds multi-dimensional arrays from many one-dimensional arrays, the so-called "arrays of arrays" approach. [C++ supports both styles.]

Healthcare 20Jun2012 12:09

Re: Multi-dimensional arrays in Java
 
for (int r=0; r<a2.length; r++) {
for (int c=0; c<a2[r].length; c++) {
System.out.print(" " + a2[r][c]);
}

Hi, Pradeep
I have a doubt in for loop. Can you explain why you have taken the statement "c<a2[r].length". I am little bit confused. please help.


All times are GMT +5.5. The time now is 10:12.