"Steve O'Hara" <[EMAIL PROTECTED]> writes: >A while back I chastised someone for not using proper String comparison >operators in their templates. I looked in the Velocity code and sure >enough "==" operators are translated into equals. So I was looking a bit >stupid.
>Somebody challenged me to come up with a situation where the equality >"==" operator doesn't work with Strings. >Well, finally, I've just found an example in my code; > #if ($SummarySortField==$Field.getUdmFieldName()) > #if ($SummarySortField==${Field.getUdmFieldName()}) > #if ($SummarySortField.equalsIgnoreCase($Field.getUdmFieldName())) >I thought perhaps I was going mad before when I raised this and plenty >of people on this list questioned me, but can anyone explain this? equalsIngoreCase != equals. In Java, equals != == Look at this: public class Test { public static void main(String [] argv) throws Exception { String s1 = "foo"; String s2 = "foobar".substring(0,3); System.out.println(s1); System.out.println(s2); System.out.println(s1 == s2); System.out.println(s1.equals(s2)); } } outputs foo foo false true However, in Velocity: --- cut --- import java.io.OutputStreamWriter; import org.apache.commons.lang.ObjectUtils; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.Velocity; public class Demo { public static void main(String[] args) { try { Velocity.init(); VelocityContext vc = new VelocityContext(); String s1 = "foo"; String s2 = "foobar".substring(0,3); vc.put("s1", s1); vc.put("s2", s2); vc.put("s1info", ObjectUtils.appendIdentityToString(null, s1).toString()); vc.put("s2info", ObjectUtils.appendIdentityToString(null, s2).toString()); Template template = Velocity.getTemplate("DemoTemplate.vm"); OutputStreamWriter osw = new OutputStreamWriter(System.out); template.merge(vc, osw); osw.flush(); osw.close(); } catch (Exception e) { e.printStackTrace(); } } } --- cut --- String1: ${s1}, Type is $s1.Class.Name String2: ${s2}, Type is $s2.Class.Name String1 Info: ${s1info} String2 Info: ${s2info} Equals: #if ($s1.equals($s2)) True #else False #end Compare: #if ($s1 == $s2) True #else False #end --- cut --- produces: String1: foo, Type is java.lang.String String2: foo, Type is java.lang.String String1 Info: [EMAIL PROTECTED] String2 Info: [EMAIL PROTECTED] Equals: True Compare: True So Velocity == is not the same as Java == for Strings. It is the same as equals(). Best regards Henning -- Dipl.-Inf. (Univ.) Henning P. Schmiedehausen INTERMETA GmbH [EMAIL PROTECTED] +49 9131 50 654 0 http://www.intermeta.de/ RedHat Certified Engineer -- Jakarta Turbine Development -- hero for hire Linux, Java, perl, Solaris -- Consulting, Training, Development 4 - 8 - 15 - 16 - 23 - 42 --------------------------------------------------------------------- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]