开发者

Java: String: Is there a better way to compare Strings

开发者_运维知识库I feel curious this morning and was wandering if somebody had a better way to do this

if(TAG_PLAY.equalsIgnoreCase(e.getActionCommand())
   ||TAG_PASSWORD.equalsIgnoreCase(e.getActionCommand())
   ||...
){

I'm having a hunch that this could be improved by doing something like creating 1 big string and looking for e.getActionCommand() in it but I don't know if it would be more efficient

Note: this has nothing to do with the getActionCommand, I'm purely interested in the logic, performance and new ways/patterns to do the same thing


Edit: I'm not considering the debate of upper and lower case^^


Edit:

How about this:

s = TAG_PLAY+","+TAG_PASSWORD;
//compareToIgnoreCase is not optimal since it will go through all the String
    if(0!=s.compareToIgnoreCase(anotherString)){


Have you considered using Set.contains(Object)?

For example:

  Set<String> cases = new HashSet<String>();
  cases.add( TAG_PLAY.toLowerCase() );
  cases.add( TAG_PASSWORD.toLowerCase() );

  ...
  if ( cases.contains( e.getActionCommand().toLowerCase() ) { 
  ...


If you're implementing a data structure for string matching, you probably want a Trie of some kind.

If you're just looking to do this in Java without heaps of code, chuck all the strings you want to match against in a set and then check whether your target string is in the set.


You could do

final String upperCaseCommand = e.getActionCommand().toUpperCase();
if(TAG_PLAY.equals(upperCaseCommand)
   ||TAG_PASSWORD.equals(upperCaseCommand)
   ||...
 ){

(Of course, the constants also need to be upperCased.

You could also put them in a hash.

if (tags.containsKey(upperCaseCommand))


This looks like a good candidate for an enum. A simple example is:

public enum TagType
{
  TAG_PLAY,
  TAG_PASSWORD
}

However, you can elaborate on this a lot. Java enums provide the performance of integers (for comparisons) along with the type-safety and behavior of objects. You wouldn't have to worry about the equivalent of e.getActionCommand() not being a valid TAG, since it's type-safe.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜