Return specific value from a 2D array - java

I'm trying to figure out a way to return the value from a specific position inside a 2D array in JAVA. I've been searching for hours. I might be tired, or using the wrong terms but I can't find anything useful so far...
So for example I have a variable "a" and I want it to receive the value that is contained at a specific array position.
So for example, I want the value contained at the position :
array[1][1]
To be saved into the variable "a". Any way to do this? Btw it's a 9x9 array so it contains 81 different value but I only need 1 specific value out of the array at a time.
Thanks in advance!

You just assign the value from the array as desired:
public class Foo {
public static void main(String[] args) {
int[][] arr = {{1,2,3},{4,5,6},{7,8,9}};
int a = arr[1][1];
System.out.println(a);
}
}
// outputs : 5
Note that if a value hasn't been put in an array position then it will be in the uninitialized state. For an int this is 0.
int[][] arr = new int[9][9];
// all values in arr will be 0

Depending on the "Object type" you would assign using Object a = array[1][1]; and you can be more specific, as in int a = array[1][1];. GL

Related

Calling function would update the array?

If I would send an array to some function, for example :
public void arrayManipulate(Someclass [] arr){
arr[0] = 2
}
for example (lets say it array of ints, even though I wrote someclass)
Someclass [] arr = new Someclass[15]
this.arrayManipulate(arr);
System.out.print(arr[0]);
what will it print? 0 as the deadult value in the array, or 2 (I want to know if calling that function would update the array or that should i return the array in that function and do arr = this.arrayManipulate(arr))
thanks in advance
George
If your code were to compile, and in both places the array were declared as int[], then the answer would be:
Yes, it will update the array. Although the arr object wouldn't have changed if reassigned in the arrayManipulate method, modifying an attribute/element inside it would be visible to the caller, because the updated object is the same.
So the number that would be printed is 2

Difference between two dimensional different flavours type array ? Advantages of these of two type

I am trying to study array in depth. I tried so many multidimensional array but didn't understand
class Test
{
public static void main (String[] args) throws java.lang.Exception
{
String [][] obj1 = new String [10][5];
String [][] obj2 = new String [10][];
System.out.println(obj1[1].length);
System.out.println(obj2[1].length);
}
}
In this example , I have tried two double dimensional array.
String [][] obj1 = new String [10][5]; and String [][] obj2 = new String [10][];.
Now
System.out.println(obj1[1].length); gives the length 5 as a Output. Totally Cleared.
In Second sysout statement throws NullPointerException
System.out.println(obj2[1].length); Totally UnCleared. because i am not trying to access the member variables only want to get the length.
So, why NullPointerException Here ? Is there really any advantage of Second type of array declaration ??
Please explain in details, found several Sources but still Confused.
Thanks
In String [][] obj2 = new String [10][]; you are initializing obj2 to refer to an array of 10 String[] elements. The elements of the array are initialized to null, which is why obj2[1].length throws a NullPointerException.
This type of declaration allows you to assign arrays of different lengths in the 2D array.
For example :
obj2[0] = new String[5];
obj2[1] = new String[10];
while in
String [][] obj1 = new String [10][5];
all the inner arrays have the same length of 5, since here you are initializing obj1 to refer to an array of 10 String[] elements, each of which is initialized to refer to an array of 5 String elements.
In Second sysout statement throws NullPointerException
Which you would expect as it hasn't been initialise.
i am not trying to access the member variables only want to get the length.
You didn't create any such array or give it a length so this doesn't make sense.
Is there really any advantage of Second type of array declaration ??
You might not want all the arrays to have the same length in which case you can set each one to whatever length you want.

How to convert a string variable value into a variable name

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**
}
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
}
}
}
}
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)

Simple way to re-assign values in an array

I'm having trouble reassigning values in an array.
public static void main(String[] {
int[] arrayOfIntegers = new int[4];
arrayOfIntegers[0] = 11;
arrayOfIntegers[1] = 12;
arrayOfIntegers[2] = 13;
arrayOfIntegers[3] = 14;
arrayOfIntegers = {11,12,15,17};
}
Why am I unable to reassign values in the manner that I've attempted? If I can't do it, why can't I do it?
Why am I unable to reassign values in the manner that I've attempted? If I can't do it, why can't I do it?
Because Java doesn't have destructuring assignment like some other languages do.
Your choices are:
Assign a new array to the array variable as shown by Rohit and Kayaman, but that's not what you asked. You said you wanted to assign to the elements. If you assign a new array to ArrayOfIntegers, anything else that has a reference to the old array in a different variable or member will still refer to the old array.
Use System.arraycopy, but it involves creating a temporary array:
System.arraycopy(new int[]{11,12,15,17},
0,
ArrayOfIntegers,
0,
ArrayOfIntegers.length);
System.arraycopy will copy the elements into the existing array.
You need to provide the type of array. Use this:
arrayOfIntegers = new int[] {11,12,15,17};
From JLS Section 10.6:
An array initializer may be specified in a declaration (§8.3, §9.3, §14.4), or as part of an array creation expression (§15.10), to create an array and provide some initial values.
If you are trying to re-assign array elements in some range, you can't do that with direct assignment. Either you need to assign values at indices individually, or use the way as given by #TJCrowder in his answer.
The correct syntax is:
arrayOfIntegers = new int[]{11,12,15,17};

how can i initialize my array when i cant initialize as null?

i have an array of strings which i want to convert to int, pretty simple and straightforward here is the code :
public static void main(String[] args) {
String myarray[]=readfile("[pathtothefile]");
int mynums[] = new int[myarray.length];
for (int i=0;i<myarray.length;i++){
mynums[i]=Integer.parseInt(myarray[i]);
}
System.out.print(Arrays.toString(mynums));
}
But the Problem here is, if i initialize "mynums" like this: mynums[]=null; i get NullPointerException on the following line:
"mynums[i]=Integer.parseInt(myarray[i]);"
what i have to do to solve it is
int mynums[] = new int[myarray.length];
here someone explained why it happens but i dont know how to initialize now! i mean sometimes i dont know how big my array can get and i just want to initialize it. is it even possible?
In Java everything is a pointer behind the scenes. So when you do mynums[]=null, you are pointing to a null. So what is null[i]? That is where your NPE comes from. Alternatively when you point it to an array, then you are actually accessing the i'th element of the array.
You have to first initialize the array because it allocates memory depending on the array size. When you want to add for example an integer to an array it writes the int into previously allocated memory.
The memory size won't grow bigger as you add more items.( Unless you use Lists or Hashmaps, ... but it's not true for generic arrays)
If you don't know how big your array will be, consider using SparseIntArray. which is like Lists and will grow bigger as you add items.
Briefly, in java an array is an object, thus you need to treat it like an object and initialize it prior to doing anything with it.
Here's an idea. When you're initializing something as null, you're simply declaring that it exists. For example ... if I told you that there is a dog, but I told you nothing about it ... I didn't tell you where it was, how tall it was, how old, male/female, etc ... I told you none of its properties or how to access it, and all I told you was that there IS a dog (whose name is Array, for sake of argument), then that would be all you know. There's a dog whose name is Array and that is it.
Typically, arrays are used when the size is already known and generally the data is meant to be immutable. For data that are meant to be changed, you should use things like ArrayList. These are intended to be changed at will; you can add/remove elements at a whim. For more information about ArrayList, read up on the links posted above.
Now, as for your code:
public static void main(String[] args) {
ArrayList<int> myInts = new ArrayList<int>();
// define a new null arraylist of integers.
// I'm going to assume that readfile() is a way for you get the file
// into myarray. I'm not quite sure why you would need the [], but I'll
// leave it.
String myarray[] = readfile("[pathtothefile]");
for (int i = 0; i < myarray.length; i++) {
//adds the value you've specifed as an integer to the arraylist.
myInts.add(Integer.parseInt(myarray[i]));
}
for (int i = 0; i < myInts.size(); i++) {
//print the integers
System.out.print(Integer.toString(myInts.get(i)));
}
}
What if you don't use an array but an ArrayList? It grows dynamically as you add elements.

Categories