[Java] Switch on Strings in Java ^_^

Results 1 to 4 of 4
  1. #1
    Alpha Member evill33t is offline
    MemberRank
    Sep 2005 Join Date
    /int/Location
    2,603Posts

    [Java] Switch on Strings in Java ^_^

    Since you cant switch strings in java..someone made a funny bypass
    (found it on worsethanfailure )
    Code:
    int helpArg = getHashValue("help");
    
    int singleArg  = getHashValue("single");
    
    int mutiArg = getHashValue("multi");
    
    
    
    public static void  main (String args[])
    
    {
    
        // Get a hash value for the first argument
    
        int hash = getHashValue(args[0].toCharArray());
    
    
    
        switch(hash)
    
        {
    
            case helpArg: 
    
                ...
    
                break;
    
            case singleArg: 
    
                ...
    
                break;
    
            case mutiArg: 
    
                ...
    
                break;
    
            // etc
    
        }
    
    }
    the orginal version
    Code:
    public static void  main (String args[])
    {
        // Get a hash value for the first argument
        int hash = getHashValue(args[0].toCharArray());
    
        switch(hash)
        {
            case 972346: // The first argument was "help"
                ...
                break;
            case -91058: // The first argument was "single"
                ...
                break;
            case -4830672: // The first argument was "multi"
                ...
                break;
            // etc
        }
    }
    Attention: Some Strings can have the same hashcode but overall it should be secure to use this :)


  2. #2
    Omega username1 is offline
    MemberRank
    Jul 2004 Join Date
    5,867Posts

    sage

    A series of else if would work just as well, with no chance of collision.

  3. #3
    Alpha Member evill33t is offline
    MemberRank
    Sep 2005 Join Date
    /int/Location
    2,603Posts

    Re: [Java] Switch on Strings in Java ^_^

    sure it would work but its just an example how to use switch on strings :P
    imagine 100 else conditions then this switch would look nicer :)
    and it would work faster (the hash function takes up the speed you gain tough)

    edit:
    i wouldnt use it in a real project
    its just a funny code snippet

  4. #4
    Omega username1 is offline
    MemberRank
    Jul 2004 Join Date
    5,867Posts

    Re: [Java] Switch on Strings in Java ^_^

    If all your strings are 4 or less characters in length, this is one way to switch (32-bit machine):
    Code:
    char strarray[4];
    unsigned int *dordmaker = &strarray;
    switch(*dordmaker) {
     case 542393671:
      ...
     case 1414745936:
      ...
     case 1145128264:
      ...
    }
    This gets even better on a 64-bit machine. 8 or less characters in length. Or you could use long ints on a 32-bit machine.



Advertisement