You need to sign in to do that
Don't have an account?
philbo
Apex and Case Insensitivity = 99 44/100% Pure
Hey,
An interesting little quirk related to case insensitivity in Apex. If you go
String s1 = 'a';
String s2 = 'A';
system.debug ( s1 == s2 );
...it'll say 'true' as you'd expect.
But now do this:
Set<String> s = new Set<String> { 'a' , 'b' };
System.debug ( s.contains ( 'a' ) );
System.debug ( s.contains ( 'B' ) );
...the second debug statement says 'False'; in other words, you cannot find that second set element by 'B'.
Thus - this little corner of Apex is case-sensitive. The same thing applies to Map keys, which makes sense, as they're probably implemented similarly under the sheets.
This can be used to your advantage if you need to do a case-sensitive compare between strings:
static boolean streq ( String a , String b ) {
Set<String> s = new Set<String> { a };
return ( s.contains ( b ) );
}
-philbo
An interesting little quirk related to case insensitivity in Apex. If you go
String s1 = 'a';
String s2 = 'A';
system.debug ( s1 == s2 );
...it'll say 'true' as you'd expect.
But now do this:
Set<String> s = new Set<String> { 'a' , 'b' };
System.debug ( s.contains ( 'a' ) );
System.debug ( s.contains ( 'B' ) );
...the second debug statement says 'False'; in other words, you cannot find that second set element by 'B'.
Thus - this little corner of Apex is case-sensitive. The same thing applies to Map keys, which makes sense, as they're probably implemented similarly under the sheets.
This can be used to your advantage if you need to do a case-sensitive compare between strings:
static boolean streq ( String a , String b ) {
Set<String> s = new Set<String> { a };
return ( s.contains ( b ) );
}
-philbo
From my original example,
String s1 = 'a';
String s2 = 'A';
system.debug ( s1 == s2 );
spits out 'True'. The '==' operator is case insensitive.
But now go:
system.assertEquals ( s1 , s2 );
and lo and behold - it throws an error. Clearly the assertEquals method is case sensitive.
This will print false, true, and true, denoting that '==' is case insensitive, but .equals() is case sensitive. Given this behavior, it would seem that internally the set.contains() method is using .equals() for comparison. In any case - don't bother trying to implement your own case-sensitive string equals function - just use .equals().