CommentID Class PostID Score Comment Text =============== ====== ====== ===== ============================================================================= 1741194 C6 138950 13 Two comments: 1) in **HMTL-meta tags** you included a xml declaration. Remove it, it would only trigger browsers in quirks mode, you don't want to have that. Also, the HTML meta tags are in fact already implicitly done by JSP `pageEncoding`, so you could even leave it away. 2) in **MySQL database and tables** you used `utf8_swedish_si`, this should have been `utf8_unicode_ci`. You could even leave the collation away, just `CHARACTER SET utf8` is enough. 27134153 C7 18460710 18 Actually, assuming that the generated bytecode conforms to the JLS, it is a proof! 4109195 C6 1299889 7 Jesper, you should probably edit out the incorrect parts of your answers rather then just having a message saying the above is incorrect. 3480306 C7 3349987 11 There might be an answer in here somewhere, but it's obfuscated by all the byte code. 17684934 C3 4240323 21 That's not rocket science, I came up with pretty much the same answer. Minor tweak: instead of recursing until `n==0`, you can stop a level earlier at `n==1` and print out `prefix + str`. 5862500 C4 5199425 9 Java has gone down the drain, with more and more bad design choices. Autoboxing is a complete failure, it's neither robust, predictable or portable. I really really wonder what they were thinking ... instead of fixing the dreaded primitive-object duality they managed to make it worse than in the first place. 3738368 C6 886979 41 I'll never do that again, I promise ;) 29359739 C7 11227902 13 Your assessment of the train-junction not being the "best" analogy isn't doing it justice. It is a *fantastic* analogy. Put that section of track in a thick fog-bank at dawn. Now flags and lights are useless as well. Admittedly you could still use *sound* (the train whistle), and we could counter that by manning a deaf operator in the switch house, but that may be beyond the realm of plausibility =P 5316881 C7 812540 20 It's not true that ApplicationContext.getBean() is not IoC. Niether is it mandatory to have *all* your classes instantiated by Spring. That is inappropriate dogma. If the ApplicationContext is itself injected, then it's perfectly fine to ask it to instantiate a bean in this way - and the beans it creates can be different implementations based on the ApplicationContext initially injected. For instance, I have a scenario where I dynamically create new bean instances based on a bean name that is unknown at compile time but matches one of the implementations defined in my spring.xml file. 8147512 C1 6841479 17 So why the heck was Shanghai 5 minutes out of wack in the first place? 7229153 C4 116916 9 This benchmark is or rather its interpretation is not correct. In the low iteration count the later tests take advantage of the file caching of the operating system. In the higher iterations test the ranking is correct but not because File.length() is caching something but simply because the other 2 options are based on the same method but do extra work that slows them down. 18926687 C6 509230 12 @DanNeely you are correct. In general, nobody should ever do this. 8145314 C6 6841479 8 @yahelc: Nope - there's just general time zone code, which handles all kinds of historical time zone transitions. 2022835 C6 2090062 29 @Downvoter: you clearly know nothing about JSF. 2080111 C6 1439792 11 Altough as Jon says "Use Joda Time" is the basis of almost all SO questions which ask about java.util.Date or java.util.Calendar I always think that firstly is best to give a concrete answer based on the user's question, at least to show how hard can be to do the java way. And after that suggesting using Joda... 5845131 C1 5199425 30 Now imagine if `i` were declared as `Long` as well! 8504088 C7 424936 17 OK, answer is 1000 days old, has 132 upvotes, and has comments like "Wow!!", "Awesome!", and "Wow, this is beautiful!" Maybe someone can help me. Tried this code directly, and it failed my test suite. On quick inspection, the "1LL >> 33" at the end looked wonky for a couple reasons (shifting 1 right 33 times? and the fact that it's a right shift of a signed value). Changed the shift direction, everything seems to work. Am I missing something? Not criticizing A. Rex, code seems to fly now, and I couldn't have come up with this in 25 years. Just baffled. 3442894 C7 3320799 11 `import static System.out;` is a rare practice, and quite unnecessary in my opinion, and thus seeing `out.println` can cause confusion at least initially. Static import has more idiomatic usage, but this particular case isn't it. 8132319 C6 6841479 482 @Gareth: Nope, but checking the details of Shanghai time zone transitions at that period was my first port of call. And I've been working on time zone transitions for Noda Time recently, so the possibility of ambiguity is pretty much at the forefront of m 61197 C2 71399 120 I think people should start looking at enums as just a class with a feature. if you can list the instances of your class at compile time, use an enum. 3420222 C7 3301720 68 Extra points for evilness... 4012086 C7 3786376 91 Even better: just return the value right away without using intermediate `size` variable. 6152160 C6 5433425 19 @Suhail: Press the "return" key on your keyboard. Otherwise known as "enter". 25768514 C6 4011232 7 I am floored that this isn't built-in... 860803 C7 34658 114 Useful if you don't know the API perhaps, but if you are having to test private methods in this manner there is something up with your design. As another poster says unit testing should test the class's contract: if the contract is too broad and instantiates too much of the system then the design should be addressed. 14832502 C7 11227902 7 @Steve Yes, that's the downside of branch prediction and [speculative execution](http://en.wikipedia.org/wiki/Speculative_execution). You pay a heavier cost during a mispredict. But it pays off in the end because branches are (usually) correctly predicted 6104483 C7 3301720 21 Yo, dawg. I heard you like reflection, so I reflected on field so you can reflect while you reflect. 15637182 C7 11774161 85 I am looking forward to the day when I inherit some code that uses these identifiers! 14985551 C7 11227902 390 I would like to point out that the reason the Intel compiler does the loop swap is actually far more impressive than just to help out branch prediction. The loops written as is are almost 100% guaranteed to cause millions of cache misses on every iteration of the outer loop. If you flip the two loops, you get at most 32768 cache misses (disregarding os preemption.) A missed branch prediction here costs nanoseconds. A cache miss can cause milliseconds if it has to fetch from memory. That's a 10000000x improvement. 43195495 C7 27371089 9 @MorphingDragon That doesn't make sense. `-` allows you to have negative literals. The unary `+` is redundant with no operator at all, making it much less useful than `-`. 5421530 C7 3787093 30 -1: you're giving examples but not really explaining the difference between a volatile and an Atomicxxxx. 46656 C5 154939 61 This is an excelent example of polymorphism (in java) :) Great Answer! 19276614 C3 271874 8 Instead of the DO_NOTHING action I would probably create a hasAction(userInput) method, returning a true or false if there is a valid action for that userInput. Then findAction would return the action or throw an Exception ActionNotFoundException 20452316 C2 154939 61 This example also nicely highlights the difficulty of using a hierarchical system to describe biological systems. Some humans, such as the very young, pee in almost any position - and babies can't easily be told to goPee(). Some humans are intersex, where the biological labels of "male" or "female" become rather ill-defined; the social meanings are even more complex. As a teaching example, it shows how modeling assumptions can have negative results, such as the implication that someone (e.g., a student of OO programming) who is incontinent or intersex is not actually human. 26490786 C2 4240323 11 @AfshinMoazami I think str.substring(i+1, n) can be replaced by str.substring(i+1). Using str.substring(i) will cause java.lang.StackOverflowError. 27132473 C7 18460710 9 @Marko I agree with your thinking, but not necessarily your conclusion. To me the bytecode above is the obvious/canonical way of implementing `!=`, which involves loading the LHS and RHS separately. And so if the JLS *doesn't* mention anything specific 16510496 C7 3787093 10 The question is not about `volatile`. The question is about `volatile boolean` vs `AtomicBoolean`. 1130963 C2 1299889 23 Not quite true, Java does generate captures for the variables in question to capture their run-time values, its just they wanted to avoid a strange side-effect that is possible in .Net where by you capture the value in the delegate, change the value in the outer method, and now the delegate sees the new value see, http://stackoverflow.com/questions/271440/c-captured-variable-in-loop for the C# example of this behaviour that Java aims to avoid. 5171034 C2 2997760 8 Thank you!! This should be the correct answer! :) I adjusted this for a little more flexibility in this post: http://stackoverflow.com/questions/4677269/how-to-stretch-three-images-across-the-screen-preserving-aspect-ratio There I use a ImageView so one can set the drawable in the XML or use it like normal ImageView in code to set the image. Works great! 315566 C7 241209 9 Most of your examples are available in Eclipse, either directly or via 3rd party plugins. I know of no one who uses an external tool for svn merge in Eclipse. For spring/hibernate/javascript editors (and autocomplete) there are 3rd party plugins. As for regex and jsp EL, you beat me :) 21311429 C2 513839 41 Just a note `equals()` **exactly** Compares this String to another String, BUT `equalsIgnoreCase()` Compares this String to another String, **ignoring case considerations** 12495585 C2 9810499 6 Still, `HashMap` is a `Map` due to the polymorphism. 163160 C7 322742 75 Forgot to mention insertion costs. In a LinkedList, once you have the correct position, insertion costs O(1), while in an ArrayList it goes up to O(n) - all elements past the insertion point must be moved. 334729 C2 521235 16 Um...no it wouldn't. The fields are marked as final, so they can't be reassigned. And it's not threadsafe because 'left' and 'right' could be mutable. Unless getLeft()/getRight() returned defensive copies (useless in this case), I don't see what the big deal is. 1238251 C7 471314 11 its mathematically solid, why should one unreal number equal another? 5/0 != sqrt(-4) 12218559 C4 4837230 8 @sweeney In other words you are now liable to man-in-the-middle attacks. You should also note that that code doesn't meet the specification: check the Javadoc. `getAcceptedIssuers()` isn't allowed to return null. 24063833 C6 3758880 6 I think every one should note that in your project customer want see values in base 2 (devided by 1024) but with common prefix. Not KiB, MiB, GiB etc. Use KB, MB, GB, TB for it. 10922853 C7 8763548 25 +1 for generating a surprisingly coherent error message. 11305751 C6 2997760 17 I can't believe how difficult it is to do things on Android that are trivially easy in iOS and Windows Phone. 8520869 C2 26318 17 1) The `Thread` is unnecessary. 2) For a good example of using `Clip`, see the [JavaSound info. page](http://stackoverflow.com/tags/javasound/info). 3) If a method requires an `URL` (or `File`) give it a dang `URL` (or `File`) rather than accept a `String` that represents one. (Just a personal 'bee in my bonnet'.) 4) `e.printStackTrace();` provides more information with less typing than `System.err.println(e.getMessage());`. 28303211 C7 574267 12 I know this is an old question but synchronizing on "this" is considered in some circles to be an anti-pattern. The unintended consequence is that outside of the class someone can lock on an object reference that is equal to "this" and prevent other threads from passing the barriers within the class potentially creating a deadlock situation. Creating a "private final Object = new Object();" variable purely for locking purposes is the often used solution. [Here's another question](http://stackoverflow.com/questions/442564/avoid-synchronizedthis-in-java?lq=1) relating directly to this issue. 16597447 C6 509230 25 It's not just that it's an ugly, confusing, mess (when you can't avoid one copious comments can walk the maintenance programmer through it); iterating over every element in the collection turns the cast from an O(1) to an O(n) operation. This is something that would never be expected and can easily turn into a horrible mystery slowdown. 28847811 C6 6841479 121 @EdS. It actually only took him 15 minutes, the reason it shows a 16 minute difference is due to a slight timezone discrepancy on July 27th 2011 caused by how awesome Jon Skeet is. 43203593 C7 27371089 6 Whilst this is a Java question, I will also point out that using unary + is a common shorthand technique in some langauges (e.g. Javascript) for casting to a number. e.g. given a string `var s = '123';` then `+s` will evaluate to the number 123. 6155504 C5 5433425 7 +1 @Jon You deserve a million rep for this one :) 13617086 C4 2549222 9 Doesn't this cut out new line characters? 35101674 C3 513839 6 One minor edit, == is not "much cheaper" than .equals, because the first statement in String.equals reads: if (this == anObject) { return true; }. 5850964 C2 5199425 11 @TREE - the spec actually *requires* VMs to create flyweights within a certain range. But sadly it *allows* them to extend that range, meaning that programs may behave differently on different VMs. So much for cross platform... 3152122 C7 3076081 125 +1: lovely solution to the puzzle, but hopefully we don't see anything like this in the real world :) 8138059 C6 6841479 23 @Jon Do you happen to know if Java/.NET copes with September in 1752? I always used to love showing people cal 9 1752 on unix systems 27732846 C7 18804636 10 can you please explain, why != is checking for the memory index of reference objects and <= is checking for the un-boxed value of Integer ??.. why there is such difference between these operator ? 10604657 C6 509230 16 Dude, that's definitely not worth it! Imagine the poor sap who has to come back and modify some code with that mess in there. I don't like suppressing warnings, but I think that's the lesser evil here. 110059 C7 31929 61 holy detailed answer batman! :) 16949161 C5 469315 7 Wow... It's almost unbelieveable to see something implemented in a more verbose way in C# than in Java 2950883 C6 2893932 32 @EJP It's by teaching people that you educate them, not by hiding things. So keeping things secret or in obscurity is not a solution at all. This code is public, the Java API is public, it's better to talk about it than to ignore it. But I can live with 1710194 C4 271874 8 Assertion is good for TESTING. It's dangerous to use on PROD. 1820868 C5 1915197 21 +1 for the extra detail about different drivers. 14817548 C7 11227902 7 4) I think branch prediction per se is not something to take into account when designing, however avoiding branches, especially particularly unpredictable ones like this one, in inner loops is something to take into account when first writing code, it's always going to hurt afterwards. Avoid control alternatives and turn them into data alternatives (the ternary operator), at the very least. 712968 C7 424936 35 Wow, this is beautiful. I'd seen Hensel lifting before (computing roots of polynomials modulo a prime) but I hadn't even realised the lemma could be carefully lowered all the way for computing square roots of numbers; this is... uplifting :) 2555610 C7 2553533 11 don't you mean: substring(s2,concat(s1,s1)? 18769096 C7 13671003 35 It's sounds like the interviewer was more invested in his answer than he was in yours... 22159109 C7 15621602 49 Now if only I could read that... 6792586 C6 5901682 106 +1 for that final paragraph. It's a vital point that's left out of consideration *far* too often. 14832103 C7 11227902 11 @Steve That's because processors can execute multiple instructions at the same time. They don't wait until the previous instructions finish before it starts the next one. Take a look at: http://en.wikipedia.org/wiki/Instruction_pipeline The diagram shows 3282630 C2 3180202 21 @svachon: I'd wrap those classes with own javabean classes and use them instead. 2558577 C7 2553533 6 #NAME? 12394042 C7 9728314 23 @sehe I wait for your alternative design of wow64 2555593 C7 2553533 13 That's very nice. +1. 5844989 C6 5199425 21 Wow, EPIC autoboxing FAIL. 10747399 C4 3934409 17 This code does not work properly. Some "0" characters becomes missing in the generated string. I don't know why, but that's the case. 2555585 C7 2553533 37 +1 Nice!....... 1835854 C7 1927840 22 It does compile in C# provided that you declare the type as: public class Foo where T : new(). Which will limit the valid types of T to those that contain a parameterless constructor. 12377026 C7 9728314 25 @Jon That something is known as the File System Redirector. 5643363 C2 5039178 18 The same will be possible with Java 7 Objects.equals: http://download.oracle.com/javase/7/docs/api/java/util/Objects.html#equals%28java.lang.Object,%20java.lang.Object%29 30936065 C1 20660044 95 They named a function `isEquals`?? 12339007 C7 574267 18 A benefit to the consumer of the API is that using the synchronized keyword in the method declaration also explicitly declares that the method synchronizes on the object instance and is (presumably) thread-safe. 8193373 C6 6841479 278 But then : how on Earth has this kind of knowledge survived the ages, so that nearly a century ago, it is implemented in software ? In 2011, anyone who mention timezone oddities to a non-software engineer is looked upon like a nerd. (And really, people expect all software to abstract it, and they don't give a damn if it's ambigous, when they say 'noon', *we* software engineer should deal with it). But to imagine someone in Shangai, in December 1927, thinking it would be relevant to note such a thing down, and that somehow this information was never lost, deleted, anything ... mind's blown. 8137183 C1 6841479 11 @Jon: Out of curiosity, why did they set their clocks back by such a "weird" interval? Anything like an hour would have seemed logical, but how come it was 5:52mins? 2080234 C6 1439792 8 @JuanZe: That requires working out exactly how to do something properly in a painful API, which is by definition painful. I'd rather spend that time doing something more productive :) 2903068 C6 2663147 11 You should really cite your references. This algorithm was invented by Robert Floyd in the '60s, It's known as Floyd's cycle-finding algorithm, aka. The Tortoise and Hare Algorithm. 522409 C2 271874 31 In your 'getParser' example, I think I would argue that an exception should have been thrown if 'null' was going to be returned unless you can somehow construct a valid argument for why returning null is NOT an 'exceptional' case. 8652314 C7 7202659 42 +1 for digging, I also couldn't find the reason for it. :) 6129231 C5 5318896 8 Why doesn't this have more upvotes? Terrific answer! 5863455 C2 5199425 20 @Catalin I disagree with you that autoboxing is a complete failure. It has some flaws, which is no different than any other design that could have been used (including nothing.) They make very clear what you can and can't expect, and like any other design 13552564 C7 10486601 13 #NAME? 27732902 C7 18804636 41 @PunithRaj < & > operators work on primitives and not on objects, hence the auto unboxing happens for these operators. But == and != operators can be used for objects comparison also so no need of unboxing here, hence objects are compared. 26983424 C4 513839 10 @SnakeDoc — We can say the opposite. *Always use `equals()` unless you have a good reason.* What you call safety is entirely context-dependent. For instance, when comparing passwords to determine whether the user has entered the right password, it is 13361419 C2 521235 8 "Note that hashCode() as-is does gives the same value if left and right are swapped. Perhaps: `long l = left.hashCode() * 2654435761L;` `return (int)l + (int)(l >>> 32) + right.hashCode();`" 2556610 C2 2553533 6 You can also use `(s1+s1).contains(s2)` in Java. 407019 C2 513839 11 @Xokas11: compareTo is generally used for sorting. 8146787 C6 6850411 16 @trutheality: I prefer most of my code to be as unindented as possible though. And a condition with a compound assignment feels more complicated to me. 15637591 C7 11774161 46 @MarkoTopolnik Be careful what you wish for. ;) 12369966 C7 9728314 9 +1... so user *"Pawel Veselov"* was right ; ) 11861802 C6 5318896 11 wow, longest answer I've ever seen on SO. 20840974 C2 7626872 40 You can use jackson with inner (nested) classes, serialization works just fine in this case. The only stumbling block is that the inner class must be marked as "static" for deserialization to work properly. See exlanation here: http://cowtowncoder.com/blog/archives/2010/08/entry_411.html 24161546 C7 16769877 14 @3D-kreativ: Yes, but I'd still recommend using the "extract to method" approach. 2680790 C3 2663147 10 Also need to do a null-check on `fast.next` before calling `next` again: `if(fast.next!=null)fast=fast.next.next;` 8145278 C1 6841479 8 Does this mean that, somewhere in the Java date libraries, there's logic handling this very edge case (and every other bizarre edge case)? 5789745 C6 154939 10 I just saw this and believe me i just threw out my coffee out my mouth on my monitor... LOL 2985446 C6 2793153 68 You should place the apache link first, so people looking for a solution find it faster ;) 14760415 C7 11227902 20 I'd be interested to know what clang does here. 4020239 C7 3786376 7 @seanizer: less understandable than using tons of useless intermediate steps for the sake of code "purity"? 15465165 C2 1036763 6 Interruption is intended as a mechanism to gently encourage a thread to stop running entirely and cancel remaining operations. `wait`/`notify` are typically used to wait for some other thread to accomplish a task, or to wait until a certain condition is satisfied. 1881407 C3 924326 6 If using DBI makes the code more readable or expressive, then use it. The fact that it increases a bit the work the JVM has to perform is not a valid argument, in itself, against it. If it were, then we should also be worried about extra helper methods/classes, preferring instead huge classes with fewer methods... 25711216 C2 2222268 7 @KenBlair: A StringBuffer is returned on purpose, so that you easily can add on more stash. Since this is specified on the javadoc, it would be extremely absurd of the implementation to expect that the returned StringBuffer would not be modified by the ca 15001038 C7 11227902 14 It depends on the processor, but yes 100-1000x is more realistic on modern processors with sizable L2 caches. 2556089 C7 2553533 49 I like its elegance, but I had to think for a while to check there weren't any false positives. (I don't *think* there are.) 625625 C7 816152 16 Integer.MAX_VALUE is 2^31-1, actually. :) 20197854 C2 14492320 15 These results vary heavily with the initial seeds passed to `QuickRandom`. Sometimes, it's close to uniform, sometimes it's _much_ worse than this. 14808234 C7 11227902 10 @PeterM I would say that branch prediction is not something that you should worry about when you design code. Stuff like memory and cache is much more important. However, bottlenecks from branch mispredictions can be very hard to detect unless you have ac 802984 C2 992413 17 @Nick: Read PKCS #5. Salts are necessary for PBKDF2, which is why the API for password-based encryption requires them as input for key derivation. Without salts, a dictionary attack could be used, enabling a pre-computed list of the most likely symmetric 2944805 C1 2885744 13 hmm how about if i do not have QuickOffice installed in my Android? 3277789 C5 3180202 68 +1 Great answer. But don't go dogmatic, sometime using scriptlets IS ok, but that should be the exception that proves the rule. 8652357 C7 7202659 67 +1 effort for pretty ascii art :) 8157714 C6 6841479 247 @Charles: back then, travellers knew to expect local time to be different everywhere (because it was). Additionally, watches were mechanical and drifted quickly, so people we used to adjusting them according to the local clocktower every couple of days an 21921396 C4 521235 12 So if I understand correctly, rolling out a simple pair class yields a syntax error, a subpar hashCode method, null pointer exceptions, no compareTo method, design questions ... and people still advocate rolling out this class while it exists in Apache commons. Please, just copy the code if you don't want to include the JAR but stop reinventing the wheel! 7353989 C2 140861 19 "0" is not valid input. Bytes require two hexidecimal digits each. As the answer notes, "Feel free to add argument checking...if the argument is not known to be safe." 8147654 C6 6841479 16 @Charles: Lots of places were had less conventional offsets back then. In some countries, different towns each had their own offset to be as close to geographically correct as possible. 50369 C6 160935 18 "I'd say, if (x % 2 != 0) { /* x is odd */ }, but who knows. Do not know java either." 13533724 C7 10474780 45 Another fine example how writing *less* makes the program *more* correct. 12013927 C7 745769 47 This is helpful. It's worth mentioning that the class _must_ come first, you cannot say ''. 31475926 C6 20952364 15 You should just be glad I didn't post the Spring solution using an XML configuration of the set. 5945892 C7 322742 25 No, for a LinkedList, get is still O(n) even if you know the position, because in order to get to that position, the underlying implementation has to walk the linked list's "next" pointers to get to that position's value. There is no such thing as random access. For position 2, walking the pointers might be cheap, but for position 1 million, not so cheap. The point is, it's proportional to the position, which means it's O(n). 4072657 C5 3831945 81 +1 awesome use of a Race Condition to display the intermediate value. 8088799 C4 4837230 101 this answer should probably note that trusting all certificates is horribly insecure and nullifies the entire purpose of ssl... 13555994 C7 10486601 25 Minor notice: LinkedList will search from the end of the list if the index is in the later half of the list, but that doesn't really change the fundamental inefficiency. It makes it only slightly less problematic. 14794057 C7 11227902 26 @J-16SDiZ Note that I did mention that it is not strictly equivalent to the original if-statement. `data[x]` is always between `0` and `255` so it doesn't get near that corner case. 18948176 C3 4240323 6 str.substring(i+1, n) can be replace by str.substring(i) 4428661 C7 574650 9 @Jakob The [alternative is documented black on white](http://maven.apache.org/plugins/maven-assembly-plugin/plugin-info.html), use `assembly:single` instead. 4684817 C5 4298836 18 +1 for your solution (although I'd like to give you -1 for your language and attitude) 15639562 C7 11774161 82 if ( ︳ ︳| ︳!= ︳ ︳ ︳|| ︴) ... 3978983 C6 3758880 7 I prefer 1.0 KB. Then it's clear how many significant figures the output entails. (This also seems to be the behavior of for instance the `du` command in Linux.) 4402671 C7 574650 7 The Maven documentation says at http://maven.apache.org/plugins/maven-assembly-plugin/ that "Usage of the assembly:assembly [...] are DEPRECATED, since they wreak havoc with normal build processes and promote non-standard build practices." without explaining details and providing an easy alternative - looks like ideology, since you can quickly solve the task as described in this answer. 2364445 C2 271874 34 @Cshah (and MetroidFan2002). Simple, put that into the contract and then it is clear that a non-found returned action will do nothing. If this is important information to the caller, then provide a way to discover that it was a non-found action (i.e. prov 27132250 C7 18460710 19 Although strong evidence, bytecode is not actually a proof. It must be somewhere in the JLS as well... 3690193 C6 886979 125 Don't question the Skeets infinite wisdom!!! :-) 172022 C2 71399 15 I'm with Amir. The name "enum" has so many preconceived expectations, that it's takes a little while to sink in that, in Java, enumerations are really much more than a list of symbolic constants. 27737463 C7 18804636 14 Ah, the hidden dangers of implicit boxing/unboxing!! 5269546 C6 2793153 20 @ivanceras: If you can't boil it down based on the information in this answer, then please press `Ask Question` button at right top. 3976536 C5 3758880 6 +1. You rock, aioobe. 712166 C3 453067 16 You're going to close that InputStream when you're done with it, aren't you? 20262870 C2 14492320 33 Mandatory quotes: Anyone who considers arithmetical methods of producing random digits is, of course, in a state of sin.� - John von Neumann (1951)AAnyone who has not seen the above quotation in at least10 places is probably not very old.� - D. V. Pryor (1993)R andom number generators should not be chosen at random.�- Donald Knuth (1986) 2751928 C7 2725165 13 At what step exactly are you stucking? My answer almost writes code itself. Did you also note that the code references in blue are actually links to Javadocs which describes the class/method behaviour in detail? At any way, you can find [here](http://courses.coreservlets.com/Course-Materials/csajsp2.html) and [here](http://courses.coreservlets.com/Course-Materials/msajsp.html) good JSP/Servlet tutorials, specifically [this](http://courses.coreservlets.com/Course-Materials/pdf/msajsp/05-Filters.pdf) one about filters. 3975997 C5 3758880 40 That's pretty cool (+1) 12105953 C2 1299889 11 Java does not, in fact, support closures. Languages that support closures do so by storing the entire local environment (that is, the set of local variables defined in the current stack frame) as a heap object. Java doesn't have support for this (the language designers wanted to implement it but ran out of time), so as a workaround, whenever a local class is instantiated, the values of any local variables which it refers to are copied onto the heap. However, the JVM can't then keep the values in sync with the local variables, which is why they have to be final. 20197332 C6 14492320 15 +1 for numerical data - although looking on raw numbers can be misleading as it does not mean that they have statistically significant difference. 5796116 C1 509230 29 this stuff is confusing, but i think all you have done is traded ClassCastExceptions for AssertionErrors. 5260932 C4 4753866 6 Obfuscated code. We don't have to code like this nowadays. May work as expected, but I'd encourage the author to have a look at [Roger C. Martin:Clean Code](http://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882) 34394 C6 134918 20 +1 for putting a lot of effort into this answer. 7712895 C7 34658 6 The example code didn't work for me, but this made thigs clearer: http://www.java2s.com/Tutorial/Java/0125__Reflection/Callaclassmethodwith2arguments.htm 13566811 C7 10486601 7 *This is horribly inefficient*. For larger LinkedList -yes, for smaller it can work faster `REVERSE_THRESHOLD` is set 18 in `java.util.Collections`, it's weird to see so upvoted answer without the remark. 4012911 C7 3786376 11 @Rene Saarsoo It is best practice to have only one return statement 12370353 C7 9728314 63 There are two versions of `calc.exe`: 64bit in `C:\Windows\system32\` and 32bit in `C:\Windows\SysWOW64\`. For compatibility in a 32bit process `C:\Windows\system32\` is mapped to `C:\Windows\SysWOW64\`. 64bit processes will launch the 64bit calc, 32bit processes the 32bit calc. Not surprising their checksums are different. If you hold the file open and look with `handles.exe` or Process Explorer you'll see the different path. 280017 C7 241209 26 The two examples about auto-completing java code work identically in eclipse. Could someone with more rep delete just the java examples please? 30941537 C7 20660044 10 @drigoangelo: I know I know. But I wonder why they didn't just use `isEqual`, so either `verb adjective` or `verb noun`, instead of `verb verb`. Personally, I just prefer `adjective` for boolean functions, and `verb` for procedures that change state. 11809789 C4 886979 6 it looks like a goto method I did not like this one. 2772379 C6 2553533 6 @unicornaddict - what's great about this solution is it's so obvious once you point it out, I hate myself for not thinking of it! 348329 C4 462648 27 It's worse than 'for several minutes' -- you might NEVER see it. Under the Memory Model, the JVM is allowed to optimize while(!stop) into while(true) and then you're hosed. This may only happen on some VMs, only in server mode, only when the JVM recompiles after x iterations of the loop, etc. Ouch! 7204090 C7 574650 10 Thanks @IAdapter. Note that you should always do a compile before hand because it will just put whatever is in "target/classes" in the JAR. This will ensure that the JAR includes any changes you recently made to the source code. So, you should do something like: `mvn clean compile assembly:single`. 2146296 C7 34658 9 Very useful. Using this it is important to keep in mind that it would fail badly if tests were run post obfuscation. 14782855 C7 11227902 6 Couldn't they have devised a system where the engineers flashed their lights or blew the whistle to tell the switchman which way to flip the switch? 22170970 C7 15621602 6 +1 This answer deserves a gold badge. 329044 C6 513839 147 I guess in Java you should say "references" instead of "pointers". 8137245 C6 6841479 29 @Johannes: To make it a more globally normal time zone, I believe - the *resulting* offset is UTC+8. Paris did the same sort of thing in 1911 for example: http://www.timeanddate.com/worldclock/clockchange.html?n=195&year=1911 137945 C6 271874 161 "I agree that null is overused in Java, especially with lists. So many apis would be better if they return an empty list/array/collection instead of null.Many times, null is used where an exception should be thrown instead. An exception should be thrown if the parser can't parse." 14998489 C7 11227902 40 @MichaelGraczyk I agree with most of what you say. But that `10000000x` is extremely exaggerated. My tests show that the loop-interchange is "only" 2-3x improvement over the sorted cases for GCC and VC++. Note that the data fits entirely into the L2 cache 20208722 C6 14492320 20 First rule of statistics: **plot the data**. Your analysis is spot-on, but plotting a histogram shows this much quicker. ;-) (And it’s two lines in R.) 730562 C3 27609 7 Additional point about appendSuper(): you should use it in hashCode() and equals() if and only if you want to inherit the equality behavior of the superclass. For instance, if you derive straight from Object, there's no point because all Objects are distinct by default. 847514 C7 1036763 11 @Geek - why in the world do you say wait() wastes CPU cycles? 12830319 C1 2703233 11 Hmm, it's telling me that 'new SSLSocketFactory(ssslCont)' is expecting a KeyStore, not an SSLContext. Am I missing something? 15789032 C6 4240323 35 Solution seems to be coming from here http://introcs.cs.princeton.edu/java/23recursion/Permutations.java.html 26089885 C7 7202659 8 Btw. "public" is also not necessary on methods in an interface declaration... they are always public. 11160386 C7 8920232 8 @thesaint Compilers aren't perfect. Although they may outdo a human 99% of the time. They are still written by humans. So that doesn't mean they always make the best optimization choices. I've seen numerous cases where compilers (ICC, GCC, MSVC) have done 30938209 C6 20660044 19 @phresnel welcome to java? 5261000 C6 4753866 15 Obfuscated? I beg your pardon, but you probably read one book and think you can code somehow differently nowadays. Tell Joel (http://www.joelonsoftware.com/articles/ThePerilsofJavaSchools.html) about that. I dare any code you can possibly write to get anywhere close to the speed of my method! 12673858 C3 5199425 14 @why-el because they are two different objects. The 256 closest to zero are being cached by the JVM, so they return the same object for those. But beyond that range, they aren't cached, so a new object is created. Does that make sense? 18185279 C6 6841479 78 why was freewind comparing data 1 second apart in 1927 in the first place? 14016824 C7 10474780 6 Strictly, the subtraction is performed between two `size_t` values, which are guaranteed unsigned, and unsigned arithmetic wraps modulo the appropriate power of two. The only place where signed/unsigned conversion is possible is in the `result > 0` part, where `result` is the `size_t` value from the subtraction of the two sizes. 3928626 C4 2222268 14 You need to conditionally check if the query string is empty. 2683648 C2 2663147 7 i was wrong: fast can't jump over slow, because to jump over slow on next step fast should has the same pos as slow :) 6796084 C4 435568 21 @Peter Lawrey below pointed out that this test was completely invalid because the compiler was optimizing out the non-reflective solution (It can even prove that nothing is done and optimize out the for loop). Needs to be re-worked and should probably be 880710 C7 1068183 41 this is a bug-prone code. You actually compare by value, not by index. If there is an object which equals to the last one, you'll have several "lastone: " lines. 14748476 C7 11227902 78 Note that with the "hack" (which is equivalent to the `cmovge` optimization gcc does with -O3, as noted in my comment to the question) it might be possible that the speed is a bit slower than in the case where branch prediction works "perfectly". So this is once more a case where you might want to optimize your code not only for the data structure, but also for its contents. 12393960 C7 9728314 8 @DavidHeffernan Opinions vary, perhaps along with the definition of 'viable'. All this virtualization does violate the principle of least surprise and adds costs (allocation and runtime). Other operating systems manage to provide both better 32-on-64 supp 4688628 C3 3786376 6 [ONLY FOR THOSE WITH A SENSE OF HUMOR] For the purists out there, single exit points are incompatible with exception handling. Attempting to catch every possible exception would lead to catch-block code bloat and separate the return far away from the body of the method. For the sake of readability (aka single exit point), the code ends up unreadable(filled with catch blocks). The 'single exit point' approach is subjective. Just tell people "I prefer it that way" and go back to coding. No reasonable programmer will begrudge a preference when stated that way. 5125371 C3 617438 6 @Demiurg Java is known not to delete files immediately. That's true, even if you don't open it. So, a more safe way is `temp.delete(); temp = new File(temp.getPath + ".d"); temp.mkdir(); ..., temp.delete();`. 14804540 C7 11227902 94 I'm amazed at both the question and the answer - this has explained something I only barely knew about. But it raises a question for me. Should you optimize your code to take into account things like branch prediction? Or would that be a case of pre-mature optimization? Knowing the data you are processing would seem to drive the implementation. 6794968 C7 322742 22 @Kevin It may matter that memory is "close together". Hardware will cache contiguous blocks of memory (dynamic RAM) into faster static RAM in the L1 or L2 cache. In theory and most of the time practically, memory can be treated as random-access. But in re 11219178 C3 2549222 12 "For bonus points, provide an initial capacity to avoid reallocations as the StringBuilder fills up: `StringBuilder total = new StringBuilder(inputStream.available());`" 734228 C2 924326 27 What this proves is that a) double-brace initialization is slower, and b) even if you do it 1000 times, you probably won't notice the difference. And it's not like this could be the bottleneck in an inner loop, either. It imposes a tiny one-time penalty AT THE VERY WORST. 8561727 C7 424936 12 @Dan: You're right, that shift was in the wrong direction! If you look carefully, it's in the right direction in the "explanation" above the block of code, so my best guess was that it went wrong when I manually translated less-thans and greater-thans in 29319485 C4 521235 6 What do you mean "easy enough to write on your own"? That's *terrible* software engineering. Are the N^2 adapter classes to convert between MyPair and SomeoneElsesPair also considered easy enough to write on one's own? 1131048 C6 1299889 11 That's not a "strange side-effect", it's the normal behaviour people would expect - and which Java cannot deliver *because* it does not generate captures. As a workaround, local variables used in an anonymous class must be final. 20205675 C2 14492320 65 @BlueRaja-DannyPflughoeft Any PRNG where the quality of the output depends highly on the initial seed value(s) (as opposed to internal constants) seems broken to me. 6155110 C6 5433425 8 You're a a software developer.. and you don't know what is meant by 'press return'? I'm pretty sure that's illegal. 3281796 C2 3180202 15 @svachon: Scriptlets are useful for quick prototyping/testing. As far as I know, there's only one "legitimate" production use of a scriptlet, namely `<% response.getWriter().flush(); %>` between the `` and the `` to improve webpage parsing pe 847478 C7 1036763 56 No, it cannot. It can only be interrupted. 4378264 C7 3257426 16 Thanks for this. It's the best tutorial I could find on JSP tag files, which were great for me coming from JSF. Wish I could give more than one up vote. 847479 C7 1036763 7 No - a sleeping thread cannot be woken by notify 16518725 C4 3180202 16 It was a pretty good answer, but the doGet and doPost parts are misleading. Those methods are for handling specific request (HEAD, GET and POST) methods and aren't for "preprocessing" or "postprocessing" requests! 11160494 C7 8920232 14 I just tested this in ICC 11, and it's actually faster. What's going on here is that ICC 12 has a new (and powerful) transformation added to aid vectorization. It's pretty clear now that I've taken a look at the assemblies. It does things that I would normally have to do manually. Since this is new, it's possible that Intel hasn't finished tuning this feature. So you've hit a hiccup in the new optimization feature. 18764499 C7 13671003 8 In one line you can say:- You can never instantiate an abstract class. That's the purpose of an abstract class. 3443049 C7 3320799 8 +1 for Eclspe & Netbeans shortcuts. I'm undecided about the static import. 6760383 C4 271874 9 Concise does not equal quality code. I'm sorry you think so. Your code hides situations where an error would be advantageous. 989399 C6 271874 71 The latter example here is, IIRC, the Null Object design pattern. 18764500 C7 13671003 33 So a simple "No" is the correct answer, too. 847470 C7 1036763 7 A sleeping Thread can also be woken up by notify(). ? 43193659 C7 27371089 16 Useless is relative ;) Maybe you like monospace lines. 10467047 C6 4011232 14 it really feels like an oversight in the simple data format, doesn't it? 14789257 C7 11227902 10 The pipelining/hardware optimization course I took last semester has really opened my eyes to things like this. It's a shame my university only requires it for CE degrees and not CS degrees as well... 9222917 C6 683049 11 I don't event google a problem any more. I just come to stackoverflow. =0) 14752910 C7 11227902 284 One way you can make the train analogy better is if you say that the only way the operator can know if the switch is correct is if the captain gives him a thumbs up or thumbs down, and the captain sits at the back of the train such that the operator can only see him when the captain passes him. This way if the switch is incorrect the train would have to stop, back up, and then take the correct route. 530604 C2 469315 8 @Chris: only flag enums should be pluralized. That is, enumerations whose members are combined using the | operator. 552704 C7 31929 19 lolcat at IHasName 6369942 C7 3257426 35 +40million. Thank you for explaining it 50,000 times better than any crappy tutorial I've found. Coming from the Rails world and missing ERB, this is exactly what I need. You should write a blog. 4299094 C6 4011232 12 12nd? 13rd? This isn't sufficient. 27935264 C6 2549222 13 It's amazing that Android doesn't have a built-in stream-to-string conversion. Having every code snippet on the web and app on the planet re-implement a `readline` loop is ridiculous. That pattern should have died with pea green in the 70s. 4578773 C6 154939 18 @yuudachi. I came up with this example when teaching a class. The canonical "Bank Account" class didn't really express the "abstractness" of the base class. The other canonical example (Animal, make noise) was too abstract for understanding. I was loo 26654017 C7 11227902 9 One of the few questions ever where the question links to Wikipedia and the Wikipedia entry links to this question. 4577686 C5 154939 20 Best example yet, both clear and hilarious 15576631 C4 11736739 20 I know that it is possible but I don't want to use LinearyLayout because of bad view recycling. This solution will not work well with many imageviews. 5641096 C4 617438 64 This code has a race condition between `delete()` and `mkdir()`: A malicious process could create the target directory in the meantime (taking the name of the recently-created file). See [`Files.createTempDir()`](http://guava-libraries.googlecode.com/svn/tags/release08/javadoc/com/google/common/io/Files.html#createTempDir%28%29) for an alternative. 4014838 C7 3786376 57 @org I hear that is best practice all the time, but when it makes the code awkward it seems silly to me. Do you have any substantiation of this claim that its actually better? Note this is not the same as "it's consensus that this is best practice" but s 12658025 C2 9903075 82 It's Oracle's attempt to insert subtle bugs into Java to discredit it, so they can release and license their own language develop pack, O++. 163460 C7 322742 11 Regarding the use of Vector: There really is no need to fall back to Vector. The way to do this is with your preferred List implementation and a call to synchronizedList to give it a synchronized wrapper. See: http://java.sun.com/docs/books/tutorial/collections/implementations/wrapper.html 30940692 C7 20660044 9 There's no need for apache-commons-lang - just use `java.util.Arrays.equals(arr1,arr2)` from the JDK. 2680909 C3 2663147 12 you should check not only (slow==fast) but: (slow==fast || slow.next==fast) to prevent jumping the fast over the slow 8147378 C2 6841479 12 @yahelc, to elaborate: time zone changes are basically a small set of different possible parameterized events. The code implements this set of events, and a timezone database supplies a list of events and parameters for each timezone. By the way, this tim 31469838 C4 20952364 7 This still has poor readability in the sense that it uses up many lines if you have a lot of Strings 1078544 C4 1250655 7 It is a good pattern if this task handling is a one-time event. If this is done repeatedly during the same runtime, however, it is not optimal, as you would create and tear down threads repeatedly every time it is executed. 3153723 C7 3076081 17 I don't think that looks *bad*, but if the requirement in the domain is understood to be "at least two", I think it'd be easier to read `atLeastTwo(hasgoodAttendance, passedCoursework, passedExam)`. The idea of "at least 2 bools are true" is generic enough to deserve its own function. 15637823 C7 11774161 13 I might throw one or two of these into my code, just for kicks! And to test whether the build system is **really** UTF-8 compliant. 12808398 C4 140861 6 javax.xml.bind.DatatypeConverter.parseHexBinary(hexString) seems to be about 20% faster than the above solution in my micro tests (for whatever little they are worth), as well as correctly throwing exceptions on invalid input (e.g. "gg" is not a valid hexString but will return -77 using the solution as proposed). 1691873 C3 116916 45 `stream.available()` does not return the file length. It returns the amount of bytes which are available for read without blocking other streams. It is not necessarily the same amount of bytes as file length. To get the real length from a stream, you really need to **read** it (and count the read bytes meanwhile). 20483769 C6 154939 6 @AndrewDalke, +1 for notes on biological complexity. Also, `goPee` does not take a gravitational field as an input. This dependency on global state makes unit-testing `CatheterizedIntersexAstronaut` difficult, and show that subclassing may not always be 3152766 C7 3076081 108 @Juliet: I don't know, I think if this was a real-world requirement (with real variable names) it would read pretty well. Consider `return hasGoodAttendance ? (passedCoursework || passed Exam) : (passedCoursework && passedExam)`, that looks fine to me. 2556289 C7 2553533 63 Nice solution. Stupid interview question. 287070 C6 469315 21 People like you give us a bad name, Barry. Get a sense of humor. 3154583 C7 3076081 15 @Lese: Asking the most micro-optimized code in face to face interviews is impractical, and dare I say, useless. Micro-optimizations, when driven by the need, is guided by runtime profiling results, not human instincts (which are known to be terrible). You 3420611 C6 3301720 10 @thecoop, @HalfBrian: there is no doubt that this is _EXTREMELY EVIL_, but this example was chosen by design. My answer only shows how, in some circumstances, this is possible. The most disgusting example that I can think of is deliberate chosen with the 24859 C5 71399 32 I think it's the most elegant solution there can be with Java 1.5 14017457 C7 10474780 8 It doesn't *cast*, it *converts*. The term *cast* refers only to an explicit cast operator, consisting of a parenthesized type name. A cast operator explicitly specifies a conversion; a conversion may be either explicit or implicit. 2806730 C4 2772416 12 Smart, but highly unreadable solution. This means hard to edit, maintain and understand. I will avoid writing that kind of "smart" code. 3167092 C7 3076081 15 "The ternary operator is a common idiom that you should be able to read. If you can't read it you should study it until you can. Use of the ternary operator is not something I consider ""clever"" in the derogatory sense. But yes, I'd put this as the body of a method call if you're commonly using the ""at least two"" logic." 4015830 C7 3786376 58 @org.life.java This "best practice" is entirely subjective and most probably outdated (since it is a throwback to the days of languages like C where you have to explicitly manage resources). There are many times when you get far more readable and maintain 43208313 C7 27371089 27 `+` is not useless. It lets you create ASCII art like `(d+,+b)`. 15861366 C2 27609 15 Same is true with Netbeans: http://developmentality.wordpress.com/2010/08/24/java-creating-correct-equals-and-hashcode-method/ 16129952 C1 1250655 13 I'm looking for any official documentation that `Long.MAX_VALUE, TimeUnit.NANOSECONDS` is equivalent to not having a timeout. 9401870 C6 4837230 17 @sweeney - Except that it's not guaranteed that you are talking to the server you think you are. If someone has mucked up a DNS server you could be communicating an encryption key with a hacker's server. 9624146 C7 34658 16 Much better than using reflection directly would be to use some library for it such as [Powermock](http://code.google.com/p/powermock/wiki/BypassEncapsulation). 18764463 C7 13671003 95 @coders. Exact answer is: - You can't instantiate your abstract class, however you can instantiate a concrete subclass of your abstract class. 1058522 C6 160935 30 My benchmark? What benchmark? I didn't do any benchmarking. I examined the generated assembly language. This has absolutely nothing to do with printf. 12495681 C2 9810499 41 Right, but a `List` of `HashMap`s isn't a `List` of `Map`s. 1098590 C7 31929 8 The generated pseudoclasess for references types in C# share the same implementation so you won't got exactly ListOfPeople. Check out http://blogs.msdn.com/ericlippert/archive/2009/07/30/generics-are-not-templates.aspx 52874 C6 160935 7 It's getting lots of upvotes to distinguish it from the bitwise operator morons, without having to spend our karma voting them down. 6155033 C6 5433425 18 @Suhail: That's why I gave you *very* detailed instructions half an hour ago. Next time someone takes the time to give you detailed help, please make sure you've read their answer carefully before saying it doesn't work. 8652627 C6 7202659 7 Wow. So it is obsolete "by design". Those JLS designers really were always so afraid of breaking something, even breaking things that never got released... :-) 8799704 C4 271874 6 @Thorbjørn Ravn Andersen By hiding the possibility that the findAction method may *not* find an action, you've now done logic that, while it doesn't break the program, may result in undesired effects that aren't found until a much later stage (possibly i 10124791 C3 27609 181 You can get Eclipse to generate the two methods for you: Source > Generate hashCode() and equals(). 9301640 C6 271874 7 There is nothing wrong with checking null values, and I have seen lot of senior/rockstar developers who check for null values everywhere. Also, null checking is one of the cheapest operation in a programming language. 700714 C2 893330 17 actually, this is incorrect. during deserialization, the serialversionuid of all the classes in the inheritance chain is taken into account, thus the lack of one on an abstract class could be problematic. i actually encountered this issue. 14757823 C7 11227902 14 Sorry for asking the stupid question. In the code given by the person asking the question, the time to sort isn't calculated in his benchmark. What about in the benchmarks you gave in your answer? If the problem required a new set of data every time, would sorting it still come out ahead? I would imagine perhaps the amount of data would change that answer? And what would the break even point be (probably dependent on sorting algorithm used)? 43201822 C7 27371089 17 @jpmc26 `+` is not really redundant, it forces [unary numeric promotion](https://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.6.1) on the operand (which includes e.g. unboxing). 7715 C6 71399 102 I just don't like it. it seems just so hacky. 17239140 C7 12758352 17 +1 , crystal clear 1706751 C7 574650 19 I'm really not sure this answer is correct. See http://stackoverflow.com/questions/1814526/problem-building-executable-jar-with-maven