Hey everyone,
I am relatively new to Java and while trying out some code came across something that surprised me. Hopefully some one can shed some light on this. Here's some code snippets relevant to my question. Those who've read the practice of programming might find this familiar.
This function is defined for the List datatype, and applies the passed "fn" argument (which is nothing but a function wrapped in an object) to all members of the list.
public void apply(MapFunctionI fn, Object fnArg) {
Node curr = head;
for (; curr != null; curr = curr.getNext()){
fn.function(curr.getItem(), fnArg);
}
}
Next, I try to use this function to count the number of elements in a list using a class that implements MapFunctionI (an interface that requires a method called 'function')
class CounterFunction implements MapFunctionI {
public void function(Object node, Object arg){
((MyInteger)arg).increment();
}
}
Here's how I call this.
static void TestApply(LinkedList l){
System.out.println("Number of elements in List -> ");
MyInteger n = new MyInteger(0);
l.apply(new CounterFunction(),n);
System.out.println(n.value());
}
And here's the MyInteger type.
class MyInteger {
private int n;
MyInteger(int i){
n = i;
}
public void increment(){
n++;
}
public int value(){
return n;
}
Now, if you're wondering why I am using my own Integer type, that's what my question is related to. I tried using the Java Integer type for this, but I could not get it to work, the answer printed was always O, the value of the "Integer" did not persist across multiple invocations. Here's how I was doing it,
arg = ((Integer)arg).intValue() + 1;
What explains this behavior?
And I am sure there is a more succinct way of posing this question :-)