Welcome!

Join our community of MMO enthusiasts and game developers! By registering, you'll gain access to discussions on the latest developments in MMO server files and collaborate with like-minded individuals. Join us today and unlock the potential of MMO server development!

Join Today!

[Java] Switch on Strings in Java ^_^

Custom Title Activated
Loyal Member
Joined
Sep 28, 2005
Messages
1,226
Reaction score
66
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 :)
 
Divine Celestial
Loyal Member
Joined
Jul 7, 2004
Messages
853
Reaction score
5
sage

A series of else if would work just as well, with no chance of collision.
 
Custom Title Activated
Loyal Member
Joined
Sep 28, 2005
Messages
1,226
Reaction score
66
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
 
Divine Celestial
Loyal Member
Joined
Jul 7, 2004
Messages
853
Reaction score
5
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.
 
Back
Top