PDA

View Full Version : Question on static methods


cash1981
08-20-2007, 06:52 PM
Hi I am wondering about something.

ArrayList<String yourList = new ArrayList<String>();
You have the static method Collections.sort(yourList); which sorts your list.
The call to Collections.sort() sorts your list and doesnt return a new object.
I am wondering how this is possible? In my book it says: Remember that the sort() methods for both the Collections class and the Arrays classes are static methods, and that they alter the objects they are sorting, instead of returning a different sorted object.

This statement is fine.
But I wanted to try something.
I created my own class

(pseudo code)
class A {
int test = 1;
main() {
B.increment(test);
System.out.println(test); //Still prints 1 (Doesnt get incremented)
}

class B {
static increment(int x) {
x++;
}

So my question is, how come the list I send in Collections.sort() gets sorted but my poor integer value doesnt get incremented? It seems I still have to return back the object. Can someone explain this please?

ess
08-20-2007, 07:10 PM
I think you need to do some reading on passing variables by reference...and passing variables by value.

Check the following url
http://www.yoda.arachsys.com/java/passing.html

Your book might already have a chapter on this topic...so, please check.

cash1981
08-20-2007, 07:11 PM
Never mind. I found out the answer. You can only do this with objects.


Here is an example code:

public class A {

int t;

public int getT() {
return t;
}

public void setT(int t) {
this.t = t;
}

public static void main(String args[]) {
A a = new A();
System.out.println("Value of t " + a.getT());
B.increment(a);
System.out.println("After increment value of a is: " + a.getT());
}
}


public class B {

static void increment(A a) {
int t = a.getT();
t++;
System.out.println("T is in B: " + t);
a.setT(t);
}
}



And the output was
Value of t 0
T is in B: 1
After increment value of a is: 1

ess
08-20-2007, 07:18 PM
cash1981...have you wondered why you can only perform such an operation with objects only.

The answer is in my previous post..you need to know what can be passed by value (all non-object types such as int, float, double etc), and what can be passed by reference (all objects...including arrays).