Showing posts from August, 2012

Map interface and equals()

The Map interface cannot have duplicate keys and implies that equals is used to determine this. boolean containsKey(Object key) Returns true if this map contains a mapping for the specified key. More formally, returns true if and only if this map contains a mapping for a key k such that (key==null ? k==null : key.equals(k)). (There can be at most one such mapping.) The Maps which support this are HashMap LinkedHashMap ConcurrentHashMap Hashtable WeakHashMap The Maps which don't use equals() are IndentityHashMap TreeMap ConcurrentSkipListMap EnumMap All have different reasons as to why they violate the contract but it strikes me as not a great rule that it is as often violated as followed.

Java memes which refuse to die

Also titled; My pet hates in Java coding. There are a number of Java memes which annoy me, partly because they were always a bad idea, but mostly because people still keep picking them up years after there is better alternatives. Using StringBuffer instead of StringBuilder The Javadoc for StringBuffer from 2004 states As of release JDK 5, this class has been supplemented with an equivalent class designed for use by a single thread, StringBuilder. The StringBuilder class should generally be used in preference to this one, as it supports all of the same operations but it is faster, as it performs no synchronization. Not only is StringBuilder a better choice, the occasions where you could have used a synchronized StringBuffer are so rare, its unlike it was ever a good idea. Say you had the code // run in two threads sb.append(key).append("=").append(value).append(", "); Each append is thread safe, but the lock could be release at any point meaning you c

Uses for special characters in Java code

Overview Ever wondered how you can write code like this in Java? if( ⁀ ‿ ⁀ == ⁀ ⁔ ⁀ || ¢ + ¢== ₡) Background Underscores has long been using in C like language such as Java to distinguish fields and method names. It is common to see a leading underscore like _field or an underscore in a constant like UPPER_CASE . In Java the $ is also used in class names and accessor method names. The SCJP has notes which state Identifiers must start with a letter, a currency character ($), or a connecting character such as the underscore ( _ ). Identifiers cannot start with a number! This leads to the question; what other connecting characters are there? What are connecting characters? A connecting character joins two words together. This page lists ten connecting characters U+005F LOW LINE _ view U+203F UNDERTIE ‿ view U+2040 CHARACTER TIE ⁀ view U+2054 INVERTED UNDERTIE ⁔ view U+FE33 PRESENTATION FORM FOR VER