|
>I am using an object that I know is a String, but accessing it through an >interface (such as Iterator) that only returns an Object. >Is it "correct" to use the toString method on the Object, rather than >casting it to String? >Which is more efficient? The question would boil down in practice to whether String.toString() simply returns "this" or not (because String is "immutable" and therefore does not change after construction, allowing this trick) and whether a polymorphic call that simply returned the first parameter ("this" is a hidden first parameter on method calls) is faster than the typechecking/typcasting operation. Try this fragment: String x = new("Some String"); String y = x.toString(); if (x == y) System.out.println("toString returns 'this'"); // explicitly not the usual x.equals(y) else System.out.println("toString does who knows what"); In the nearest-by IBM JVM I had available, it returned 'this' as I expected it to. So, it should come out along these lines -- typecheck costs versus polymorphic call. It's an interesting little trick if it works. There's a lot of code out there that typecasts known Strings from Objects. The latter practice is clearer whether it is faster or not. The problem with using toString() is that if you somehow unexpectedly don't get a String, the code is likely to create a garbage String of some kind for you. If you're casting to start with, it means you might find yourself obscurely enjoined from (e.g.) putting something other than a string as the target of a hash table lookup. This is not entirely unlikely, however, as many problem domains have a limited set of object types unlikely to change. Even so, it does create one more obscure source of error if you reverse an original decision to have "all Strings" as targets of a hash table. Larry W. Loen - Senior Linux, Java, and iSeries Performance Analyst Dept HP4, Rochester MN
As an Amazon Associate we earn from qualifying purchases.
This mailing list archive is Copyright 1997-2024 by midrange.com and David Gibbs as a compilation work. Use of the archive is restricted to research of a business or technical nature. Any other uses are prohibited. Full details are available on our policy page. If you have questions about this, please contact [javascript protected email address].
Operating expenses for this site are earned using the Amazon Associate program and Google Adsense.