Checking if an array has been assigned a size yet - java

Is there any way to check if an array has already been set to a length in Java?
In my case, I have a recursive method, and in the first iteration of the method, I want the array to have the length of a variable n. However, after the first recursion of the method, I don't want the array to be reassigned a new size.
Additionally, I don't know what the size should be until the first iteration of the method.
Thanks!

The array variable would be null until you assign an instance to it. Once an instance is assigned, it will have a fixed length. Therefore, a simple null check would suffice.

The Array Reference Variable Would be NULL until you assign to it.
You cannot create an Array Object without a lenght; if you want that, maybe you should create a ArrayList, and you can add objects to it without care about the size.
If you just want to see the lenght of your Array; after CREATE, do this:
public static void main (String[] args){
String[] x = new String[2]; // you cannot create here without a lenght, you MUST set
System.out.println(x.length);
}
OUTPUT: 2

Related

Don't understand error message (required: variable, found: value)

The error message pertains to this line of code
Player a = pl.get(i);
/*
* CODE MODIFTYING VARIABLES WITHIN THE OBJECT a
*/
pl.get(i) = a;
'pl' is an ArrayList of the class Player
this code is in a for loop where 'i' is equal to the number of intervals the for loop has gone through
it specifies that "(i)" is a variable an it should be a value, what does it mean by value???
Basically, I'm copying my Player object in my array list and setting it to a Player object variable that is created within the for loop and changing the values within the object and then setting the newly created object (Player a) to my index in the ArrayList (pl.get(i))
I'm doing this so I don't have to keep writing pl.get(i).getFunction() pl.get(i).setFunction() pl.get(i).CalculateFunction() pl.get(i).blablabla();
I can just use a.whatever = 83465;
So the question is, what am I missing?
pl.get(i) is a value type (rvalue) and can not be assigned a new value.
Only lvalues can be assigned values.
You have to use the set method of ArrayList to overwrite values in the list:
pl.set(i, a);
Additionally, when calling pl.get(i) to retrieve the element you named a, you can use this reference to change a in any way you want. you don't have to write the object back into the list, as the reference is still there.

How do I return not only the proper data type but an array as well?

I am currently drawing a blank on how to return more than what is "commanded"
public static long extendedEuclidGCD(long a, long b, long [] xy)
the code works fine but I am asked to also retrieve the array xy (only size 2) and add the elements their to the output without changing the header. So my question is this, how do I not only return the gcd the method provides, but return the elements inside the array.
I am asked to also retrieve the array xy
You are passing an array to the method. In java references to objects are passed by value. As long as you modify xy without reassigning it your modifications will be visible to the calling method. So, you don't have to return the array.
If you reassign the reference xy to some other array instance, then you will have to return the reference.

How to fill an array in a class JAVA

So I am having issues with a program i am trying to create. I cannot put in data into the array int[] serviceCode without the error
Exception in thread "main" java.lang.NullPointerException
at Job_18028094.<init>(Job_18028094.java:24)
at BMAS_Main_18028094.main(BMAS_Main_18028094.java:76)
Here is the relevant section of my code.
From my Main:
String[] tempRecords = fileScan.nextLine().split(",");
jobList[loopCount] = new Job_18028094(tempRecords);
From my class 'Job':
private int[] serviceCode;
public Job_18028094(String[] tempRecords) {
serviceCode[0] = Integer.parseInt(tempRecords[6]);
}
To clear things up, there is data held in tempRecords[6] as String (but is all numbers) and have been using Integer#parseInt prior to convert them. I researched what the error means and have turned up with it meaning that the variable is a 'null' value, but I am unsure as to how to change this or just over write it with the data in tempRecords.
Thank you in advance for any help :)
The NullPointerException is thrown , because the ServiceCode array is not initialized. Arrays are static objects and need to be initialized prior any use. Also, you should provide the size of this array before using it ! try to pass a "size" parameter to Job_18028094 constructor. This will solve the problem.
You have to initialize this array before use it.
private int[] serviceCode; // else serviceCode is null
You can use
private int[] serviceCode=new int[5];
If you are not sure about the length of the array. Use List
List<Integer> list=new ArrayList<>();
When you simply declare an array using the statement private int[] serviceCode;, you are telling to the compiler that a variable named serviceCode will hold an array of integers. At this point of time, compile is not informed about how many integers that the array will be holding. So the actual memory allocation to hold the integers will not happen by this time.
To start putting integers into an array, the corresponding memory allocation should have happened already. Compiler will take care of doing this memory allocation only when you initialize the array using the following statement.
int[] serviceCode = new int[5]
After the above initialization, memory allocation will be completed for the array to hold 5 integers and the array will be filled with the default values for the integers (which is '0'). Now you can start putting different values into the array.
In your case, since you have not initialized the array, memory allocation did not happen which caused the NullPointerException to be thrown when you tried accessing the array.

difference between these 2 ways of initializing an simple array

In java, I can initialize an array with predefined content either by :
int[] myArr = new int[]{1,2,3};
Or by :
int[] myArr = {1,2,3};
Essentially, is there any difference between these two ways ? Are they completely identical in Java ? Which way is better and why?
In your case there is no difference.
There will be a difference when you are not assigning your array to variable and doing inline creation.
for example, conside there is method, which takes an array as argument.
private void someX(int[] param){
// do something
}
Your case:
someX(myArr); // using some declared array .I.e your case
Now see the difference while calling it in other cases.
someX(new int[] {1,2,3}); // yes, compiler satisfied.
someX({1,2,3}); //Error. Sorry boss, I don't know the type of array
is there any difference between these two ways ? Are they completely identical in Java ?
No there is no difference. Both of them will create an array of length 3 with the given values.
The 2nd one is just a shorthand of creating an array where you declare it. However, you can't use the 2nd way of creating an array, at any other place than the declaration, where the type of array is inferred from the declared type of array reference.
No, the first and second are the same. The second is just syntactic sugar. Your end result is the same.
int[] myArr = new int[]{1,2,3};
Here it means you are initializing the three variable which will create the length of array 3
int[] myArr = {1,2,3};
Here it means you are initializing the three variable which will by default create the length of array 3
Both ways generate exactly the same result. Both are arrays of length 3 with predefined values. The second one is just shorter. The second method of declaring an array is better if you think that you need less time to write that code.
In the case you need to use that array to directly pass it to a method you should use the first one:
//Correct
someMethod(new int[]{1,2,3});
//Incorrect
someMethod({1,2,3});
But if your goal is only to declare and initialize the array in a variable either ways are correct:
int[] myArr = new int[]{1,2,3}; //Correct
int[] myArr = {1,2,3}; //Also Correct

Reference of two arrayList to same objects

I have this code. But I don't know how to explain the result:
ArrayList<String> first = new ArrayList<String>();
first.add("1");
first.add("2");
first.add("3");
ArrayList<String> second = new ArrayList<String>();
second = first;
System.out.println("before modified:"+second.size());
second.clear();
System.out.println("after modified:");
System.out.println(" First:"+first.size());
System.out.println(" Second:"+second.size());
The result will be: 3 / 0 /0
The problem I don't know is: when you assign first = second; so, both first and second array will point to same object (1,2 and 3). after you clear all elements on second array, so all reference between second array and these objects will loose (no problem here).
The thing I don't know is: but these objects (1,2 and 3) still hold reference to first array. Why first array's size is 0.
Please explain for me.
Thanks :)
By assigning second = first, there is only one arraylist with two references. The references are the same. So, when call clear using one of the two references (first or second), clear will be performed on the referenced arraylist.
This is something else than you first thought. It's not so that assigning the second = first all the references of the strings you added to the first one, will be copied into a new ArrayList object, that would be magic (in Java).
When you do first = second your ArrayList items will point to the same memory locations. Doing a .clear will remove the elements to which the ArrayList is pointing to. This will have repercussions on the other ArrayList.
If you just want to copy the elements of ArrayList1 to ArrayList2, you could do something like so: ArrayList<String> second = new ArrayList<String>(first);
but these objects (1,2 and 3) still hold reference to first array.
Why first array's size is 0.
ArrayList<String> second = new ArrayList<String>();
second = first;
is the same as writing
ArrayList<String> second = first;
You have made second reference point to the first arraylist,it is not using a new arraylist. So when you call clear it clears the "first" arraylist created - you have two references pointing to one arraylist.
When you assign one ArrayList to two variable and modify any one of them, this will reflect in both.So operation performed in any of one variable also reflect in second one. (Single object referenced by two variable).
In Java a variable (except primitives) is always a reference (which has the start address of object) to an object only, Reference is never an object in itself.
For example
second = first;
is assigning a reference, so that first and second now refering to the same object. Objects are not copied, neither in assignments, nor in argument passing (what is copied/assigned is the reference).

Categories