Get the default value by type



  • @Jonathan said:

    The only way to check what value a string has is to check each character in the string, and String.equals() is the most efficient way to do that. There is no getting around the fact that efficient switching on strings requires calling String.equals(). Putting those calls as the second stage inside a switch statement adds efficiency by reducing the number of calls to String.equals() down to one or only a few.

    The reason switching on strings was added and not switching on other classes is because the string class is immutable and String.equals() is known to have no side effects.

    Just to add, Java's String object is fairly smart (the Sun implementation, at least).  The hash code is calculated on demand and cached thereafter, and the equals() method first checks the lengths (which is a pre-known value and does not have to be counted each time) to see if they match before walking the character array.  It does other cool tricks with sharing the underlying array between substringed instance and so forth.  Yay for immutability.  (Thus equality can be O(1) in the best case, non-matching lengths.)

    But that doesn't really excuse why other classes can't enjoy the same benefit.  If your equals() causes side effects, mutation in particular, then that also messes up Comparators and Maps and stuff.  If those can assume non-stupid developers, why not a switch?  It's no worse than a eye-bleeding chuck else-if statements.



  • You guys have no concept of optimization. Obviously, the cases should be split into characters, then have the character ordinals put into nested hashmaps. You would only require a simple while loop to extract your result. With that many hashmaps, it's bound to be blazingly fast. And as a pure bonus you will get the right result 100% of the time, so you don't even have to write unit tests.



  • Hmm, I dunno about the hashmapping, but how about nested char switches?

    switch (strType.charAt(0)) {
        case 'S': {
            switch (strType.charAt(1)) {
                case 'T': {
                    switch (strType.charAt(2)) {
                        case 'R': {

    eh, I can't be bothered to type all this out.

    (If only the language had some sort of code-generation ability...)


  • Trolleybus Mechanic

    @Xyro said:

    Hmm, I dunno about the hashmapping, but how about nested char switches?

    switch (strType.charAt(0)) {
        case 'S': {
            switch (strType.charAt(1)) {
                case 'T': {
                    switch (strType.charAt(2)) {
                        case 'R': {

    eh, I can't be bothered to type all this out.

    (If only the language had some sort of code-generation ability...)

     

    It does, but the code-generator can't generate switch statements.


Log in to reply