September 13th, 2010, 03:11 PM
-
Singleton Data source
I'm writing a min-cut EA with a fairly large population and trying to make it as efficient as possible. One of the things I'm trying to do is store the graph in a Singleton where all the members of the population can find it. Basically I need the following SSCCE to print 1 instead of null. How do I do this?
Java Code:
public class Test {
private static Integer myInt;
public static void main(String[] args){
Test.setMyInt(1);
System.out.println(Test.getMyInt());
}
public static void setMyInt(Integer myInt) {
if(myInt==null)Test.myInt = myInt;
}
public static Integer getMyInt() {
return myInt;
}
}
September 13th, 2010, 03:34 PM
-
You are having the common problem people have when they name the args to a method with the same name as member names.
Comments on this post
September 13th, 2010, 03:42 PM
-
I don't believe so. That type of scoping problem was the first thing I checked for and I have referenced the correct objects in the code above. As I stated, this is a SSCCE , not the working code and the original had different names. I reran my test as shown below and got the same result, just to make sure.
Java Code:
public class Test {
private static Integer myStaticInt;
public static void main(String[] args){
Test.setMyInt(1);
System.out.println(Test.getMyInt());//should be "1", is "null"
}
public static void setMyInt(Integer myInt) {
if(myInt==null)Test.myStaticInt = myInt;
}
public static Integer getMyInt() {
return myStaticInt;
}
}
The results were the same.
The problem does appear to be a scope issue, as I have had it print when it updated the value but it always is null as soon as the setter exits. Any ideas?
Last edited by spyder0101; September 13th, 2010 at 03:54 PM.
Reason: Added link and fixed some minor format errors, added code comment
September 13th, 2010, 03:51 PM
-
Line 10 only sets myInt if the value passed in NULL. I think you might actually mean !=null
Comments on this post
September 13th, 2010, 03:54 PM
-
What does this code test for and why?
Code:
public static void setMyInt(Integer myInt) {
if(myInt==null)
...
Comments on this post
September 13th, 2010, 03:59 PM
-
NormR is actually correct in his assessment. you might want to check out your setter-method again
September 13th, 2010, 04:12 PM
-
Actually, should have been the myStaticInt there, so I guess NormR was right. Changing that fixes the problem. Thanks.
September 13th, 2010, 11:09 PM
-
You might consider throwing an exception instead of returning on null. Wouldn't it be better to know where the null came from in the first place than to ignore it?
"Java makes impossible things possible, but makes easy things difficult." - Somebody