0

There are around 10 different types of 2D arrays of varied sizes. eg:

int arr1[][];
float arr2[][];
long arr3[][];
String arr4[][];

Each array needs to be printed at different intervals during the program execution. There is a method defined print2DArray() which takes the 2D array as parameter calculates the number of rows and columns and print the array. But since the arrays are of varied datatypes overriding methods need to be written for each data type.

Can we create a variable as: String arrName; and pass it to the method print2DArray() and decode the String to obtain the array to be printed. eg:

if method is called as: print2DArray(arr2);

and method is defined as:

void print2DArray(String arrName){
    **Some code to identify which array is reffered by arrName to print**
}
3
  • what about passing Object and recognize type by instanceof? Commented May 20, 2015 at 9:05
  • or what about overloading methods? Commented May 20, 2015 at 9:09
  • "overriding methods need to be written" - the term should be overloading. Commented May 20, 2015 at 9:12

2 Answers 2

1

You need to use java reflection api for this purpose .

Code will be somewhat like this.

class CustomClass {
    int[][] arr1 = new int[][] { { 1, 2, 3, 4 }, { 5, 6, 8, 7 } };

    public static void main(String[] args) {
        CustomClass c = new CustomClass();

        Field[] f = c.getClass().getDeclaredFields();

        for (int i = 0; i < f.length; i++) {
            if (f[i].getName().equals("arr1")) {
                System.out.println(c.arr1[0][0]); // your own logic
            } else if (f[i].getName().equals("arr2")) {
                System.out.println(c.arr2[0][0]); // your own logic
            } else if (f[i].getName().equals("arr3")) {
                System.out.println(c.arr3[0][0]); // your own logic
            } else if (f[i].getName().equals("arr4")) {
                System.out.println(c.arr4[0][0]); // your own logic
            }
        }
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

And who said the arrays are fields?
RealSkeptic, i'm not trying to sound harsh but given you have something negative to say about each and every answer to this thread, what about you come up with some solution instead ?
Reflections is working but just a small issue.. Im able to print variable but when it comes to arrays Im unable to print it. variable b and c are getiing printed but unable to print a public class Test { public int[][] a= new int[][] { { 1, 2, 3, 4 }, { 5, 6, 8, 7 } }; public float b=20; public String c = "abc"; static void printvalue() { Test c = new Test(); Class cls = c.getClass(); Field sField = cls.getField("b"); Object value = sField.get(c); System.out.println("Public field found: " + value.toString()); }
0

I don't think you could do that natively. There's some easy workarounds though, the one i'd choose is to create a Map which contains all of your arrays linked with a key that would be the array name. That way, in your print2DArray function, you'd simply have to iterate your map and find the array that has the correct key (the one you give as a parameter in your function).

Your map would look something like this {"arr1", arr1}, {"arr2", arr2} etc... this would obviously force you to keep track of every newly created array by adding it in your Map (which isn't very costly anyways)

9 Comments

You don't iterate on maps to find something by the key. You just access it by key. Iterating a map is done only if you want to apply some operation to all the elements of a map. But in any case, how is this method better than writing overloads?
That being said you could also just create a print2DArray method that takes a 2D array of objects and do some manual casting to print it. That way you should be able to pass any type of 2D array as a parameter.
How do you suggest casting from int[][] to Object[][]?
I'm suggesting to cast from Object[][] to Integer[][] as an example, not the other way around. Obviously you could also just create N methods for each array type, which scales terribly though.
You are not supposed to write N methods, since there is only a limited and well defined number of primitives in Java. All arrays of reference types can be cast to Object[][]. This is how the standard libraries deal with the same problem, see for example Arrays.toString().
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.