Java - If statement in foreach not called -
i trying check if string in collection of strings. (the strings in case topics activemq broker) iterate through topic list , compare topics searched 1 (save in variable "compare"). "topic.gettopicname()" definately returns string not why varaible count not set 1 eventhough condition true in 1 case. statement in if clause never executed. overlooking something?
public arraylist<string> gettopics() throws remoteexception { try { // topics strings broker activemqconnectionfactory connectionfactory = new activemqconnectionfactory("tcp://localhost:61616"); activemqconnection connection; connection = (activemqconnection) connectionfactory.createconnection(); connection.start(); destinationsource ds = connection.getdestinationsource(); set<activemqtopic> topics = ds.gettopics(); string compare = "physical"; int count = 0; for(activemqtopic topic : topics){ system.out.println(topic.gettopicname()); if(compare == topic.gettopicname()) { system.out.println("found " + topic.gettopicname()); count = count + 1; } } if(count == 0){ system.out.println("no topic found"); } else system.out.println("topic found"); } catch (jmsexception e) { // todo auto-generated catch block e.printstacktrace(); } return null; }
i can't debug code because i'm not sure in activemqconnectionfactory
can provide advice.
try adding
if(compare == topic.gettopicname()) { system.out.println("found " + topic.gettopicname()); count = count + 1; } else { system.out.println("not found " + topic.gettopicname()); }
the following else statement can see happens when should equal. additionally, think should comparing string using .equals()
not ==
since strings objects.
you can see string comparison using == fail in following code
public static void main(string[] args) { string compare = "physical"; string somestring = new string("physical"); string[] words = {"test", "cheese", "physical", somestring}; (string s: words) { if(s == compare) { system.out.println(s + " == " + compare); } else { system.out.println(s + " " + "!= " + compare); } } system.out.println("--------------------------------------------------------"); (string s: words) { if(s.equals(compare)) { system.out.println(s + " == " + compare); } else { system.out.println(s + " " + "!= " + compare); } } }
prints
test != physical cheese != physical physical == physical physical != physical -------------------------------------------------------- test != physical cheese != physical physical == physical physical == physical
Comments
Post a Comment