Incrementing primitive wrapper class passed as a parameter to a method which has no affect on invoker - eclipse

I'm writing the Java SE 8 app on Eclipse IDE. The issue that I came across is following.
private Object[][] adjustIndexTaskValueAdded(int size){
Integer adjustingIndex = 0;
Object[][] tasksDisplay = new Object[size][taskValues[0].length];
for (int i = 0; i < size; i++) {
tasksDisplay[i][0] = taskValues[i][0];//phase colour
tasksDisplay[i][1] = identifyNextRowIDTaskTable(adjustingIndex, i);// the index
}
return tasksDisplay;
}
So, I've got adjustingIndex Integer wrapper class which I pass to the identifyNextRowIDTaskTable() method. So that the local var can store the value which gets modified at the child method.
private String identifyNextRowIDTaskTable(Integer adjustingIndex, int currentRowID){
if(UtilityOperations.isPhaseRow(phaseColourCurrent)){//it's a phase row
adjustingIndex++;
return "";
}
else{//it's a task row
int displayID = tableID - adjustingIndex;
adjustingIndex = 0;
return String.valueOf(displayID);
}
}
The above methods displays the method which modifies the Integer wrapper class which I pass to.
Now when I run the app, the new value is not reflected at the invoker method. It appears that value changes/adjusts at the child method, but the parent method does not see the changes. In the end, the outcome becomes erroneous.
The displayed source-code is simplified...
So, what the problem is?
I pass reference type var, and it is not a recursive operation.
I could use object's state to store the value instead, of-course. Yet, I want to understand the current pitfall.
Best regards

Consider
adjustingIndex++;
This is unboxing the value from the Integer to get an int and incrementing that value, this is equivalent to:
int tmp = adjustingIndex.intValue();
tmp++;
adjustingIndex = Integer.valueOf(tmp);
This resets the parameter adjustingIndex to be a reference to a new Integer, it does not change the value of the adjustingIndex variable in the calling method - that is a separate reference.
Again consider:
adjustingIndex = 0;
Again this resets the parameter adjustingIndex to be a reference to a new Integer, it does not change the value of the adjustingIndex variable in the calling method.
One alternative would be to use AtomicInteger
AtomicInteger adjustingIndex = new AtomicInteger(0);
increment with
adjustingIndex.incrementAndGet();
set back to zero with
adjustingIndex.set(0);
AtomicInteger has methods to change the value of the integer it contains, in contrast Integer is immutable and its value can't be changed.

Related

Using Setters with Constructors in Dart

How can I use the setter of a private instance variable from the default constructor in Dart?
Given the example class:
class A {
String name;
int _age;
int get age => _age;
set age(age) {
_age = age ?? 0;
}
A(this.name, this._age);
}
How can I use this constructor to go through the set age() function? Is there away aside from using a factory? I'd like to do something like this
A(this.name, newAge): age = newAge;
But I get an error forcing me to only set instance variables from the constructor, which has me just duplicating the setter:
A(this.name, newAge): _age = newAge ?? 0;
Am I missing something or is this just not possible with dart?
The initialization list of a constructor can be used only to initialize members (or call base class constructors). (Additionally, when the initialization list is executed, this isn't valid yet, so you can't access any members.)
If you want to do other kinds of initialization work, you can do it in the constructor body instead, at which point the object is considered to be sufficiently constructed for this to be valid:
A(this.name, int newAge) {
age = newAge;
}
Also see:
Difference between assigning the values in parameter list and initialiser list, which explains why this becomes valid only for the later stages of object initialization.
https://stackoverflow.com/a/64548861/ for various differences between the different ways to initialize members and for an example where the different ways matter.

Issue with passing an int field in as a parameter argument, but all others work perfectlyy how is this even possible?

ScreenShot of CodeCould someone please explain to me how everything works in this script except a simple int counter that I pass in as a parameter? However if I directly pass in the int counter field into the method instead of using/ref. the para, it works just fine, how is this even possible? HELP!
By default parameters you give to the function, are evaluated and its value is passed (eg. not int xy is passed but the value of int xy, so 5).
So if you change the value directly eg. CounterAi -= 1; you are just changing the value you've passed on not the underlying variable. So if you want to use Pass by Reference in these cases you must use out or ref.
If you change a parameter of the passed value however it's value will be changed without needing to use ref or out.
Example:
public void Example1(int myValue) {
// This won't change the actual variable, just the value of the parameter,
// that has been passed
myValue -= 1;
}
public void Example2(ref int myValue) {
// This will change the actual variable,
// it's changing just the value of the parameter again,
// but we're using pass by reference
myValue -= 1;
}
public void Example3(Transform finishLine) {
// This will change the actual variable,
// because it's changing the data within the object,
// that the parameter value refers to.
finishLine.position = flSpts[Random.Range(0, flSpots.Count)].position;
}

Understanding constructors and final [duplicate]

class X extends Y {
X(int a, int b) : super(a,b);
}
Can someone give me an explanation about the syntax meaning of the colon :?
This feature in Dart is called "initializer list".
It allows you to initialize fields of your class, make assertions and call the super constructor.
This means that it is not the same as the constructor body. As I said, you can only initialize variables and only access static members. You cannot call any (non-static) methods.
The benefit is that you can also initialize final variables, which you cannot do in the constructor body. You also have access to all parameters that are passed to the constructor, which you do not have when initializing the parameters directly in the parentheses.
Additionally, you can use class fields on the left-hand of an assignment with the same name as a parameter on the right-hand side that refers to a parameter. Dart will automatically use the class field on the left-hand side.
Here is an example:
class X {
final int number;
X(number) : number = number ?? 0;
}
The code above assigns the parameter named number to the final field this.number if it is non-null and otherwise it assigns 0. This means that the left-hand number of the assignment actually refers to this.number. Now, you can even make an assertion that will never fail (and is redundant because of that, but I want to explain how everything works together):
class X {
final int number;
X(number): number = number ?? 0, assert(number != null);
}
Learn more.
It's ok to access non static member in initializer list.
class Point {
num x, y;
Point(this.x, this.y);
Point.origin(): this.x = 10, this.y = 10;
}
main() {
Point p = Point.origin();
print(p.x); // 10
}

How to assign method output to variable by reference MQL4

I'm guessing this question is going to apply to many similar languages other than MQL4 such as c++ (which I also forget how to use) which require you manually specify when you are passing by reference.
Method reference:
int[] previous = GetPrevious(i, ZigZagBuffer);
Method definition:
int GetPrevious[](int current, const double& buffer[])
{
int count = 0;
int result[];
// calculate count
ArrayResize(result,count);
// fill array
return result;
}
The resulting compile error is:
"Invalid Array Access"
From what I understand, this is because array's can only be passed by reference, but you have to explicitly state that you are passing it by reference. But the more I look up the syntax for passing by reference, the more I find articles about passing parameter by reference. (which I already know how to do as you can see in the code example.)
What is the syntax to assign the output of a method to a variable?
In case it matters, I only need to read the array multiple times; I'm not needing to alter or re-assign it after it is declared.
You cannot return array. You have to create it and pass into the function, fill inside the function and that's it.
OnTick(){
double array[]; //declaration of the array
fillArray(array,10); //passing array by ref, updating it there
Print(array[0]=0 && array[9]=9);//returns true
}
void fillArray(double &array[],int size){
ArrayResize(array,size);
for(int i=0;i<size;i++){array[i]=i;}
}

Contract.Ensures for an OverFlowException

I have a simple Method that returns the exponential value from a given number:
public int Exp(int num)
{
return Convert.ToInt32(System.Math.Exp(num));
}
When running Pex I get an OverFlowException in the Summary/Exception field for a certain large number: 1969057606.
How could I create a Post Condition using Contract.Ensure()?
I tried the following but it does not do anything:
Contract.Ensures(Contract.Result<int>() < 2147483647);
// This is because the max value an int variable can hold is 2147483647
Contract.Ensures is used to assert something about the state of your class after the function is run or, in this case, the result of the function regardless of what the input was. You need to add a Contract.Requires such that e^num <= int.MaxValue, e.g.
Contract.Requires<ArgumentOutOfRangeException>(num <= Math.Floor(Math.Log(int.MaxValue)))
Although you'd probably want to pull the max value calculation out into a constant.
public static readonly int MAX_EXPONENT = Math.Floor(Math.Log(int.MaxValue));
...
Contract.Requires<ArgumentOutOfRangeException>(num <= MAX_EXPONENT)