|
Table of Contents
|
How to Iterate a Map
Iterator it = themap.entrySet().iterator(); while (it.hasNext()) { Map.Entry pairs = (Map.Entry)it.next(); pairs.getKey(); pairs.getValue();
Enhanced For Loop Since 1.5
for (MyObject myobj : theCollection)
myobj .do();
String Concatenation
The + operator performs string concatenation if and only if at least one of its operands is of type String; otherwise, it performs addition.
In this case 'a' + 'b' prints an int number not the string ab.
To force this into a String concatenation we can prepend an empty string; use a string buffer; or if you are using release 5+, use the printf facilities.
Double.NaN
It stands for Not a Number. The specification says that NaN is not equal to any floating-point value, including itself. Any floating-point operation evaluates to NaN if one or more of its operands are NaN. So in case of Nan, the statement i != i; is correct.
Static
class x { static fields; .. .. public static void main() {} }
This is the way static fields are treated by JVM:
- jvm inits class
- static fiels are set to their default values (objects to null, booleans to false, int to 0,…) in order of appearance
- static fields are executed if they have eager initialization, etc (in order)
instanceof
When we have x instanceof y then x or y must be a subtype of the other. This is the case when we cast as well.
Eager/Lazy initialization
private static final int sum = someMethod(); //eager private static final int sum; //lazy
Private Constructors
They are useful sometimes. This is called alternate constructor invocation.
public class x { public X () { this(int i); //calls a private constructor } private X (int i) {} //private constructor }
They are also used in singleton pattern
Immutable
Always watch out for immutables. All wrapper classes such as String, BigDecimal, Integer, Long, Short, Byte, Character, Boolean, Float, Double, … are immutable. They also have some misleading methods.
BigInteger sum = new BigInteger("1"); BigInteger base = BigInteger.ZERO; base.add(sum);
add method will not do sum + base and we need to do: base = base.add(sum);
Integer
Integer literals beginning with a 0 are interpreted as octal values so watch out for things like: int i = 012;
Get rid of duplicates in a list
Simply dump your list into a set or a LinkedHashSet if you want to preserve the order. In case the elements are objects make sure you have equals and hashcode properly implemented for them.
Split a String
Use split method of strting. Forget about StringTokenizer as it will be deprecated soon.
static String[] parse(String string) { return string.split(",\\s*"); }
Autoboxing and Unboxing
You can’t put an int (or other primitive value) into a collection. Collections can only hold objects, so you have to box primitive values into the appropriate wrapper class. When you take the object out of the collection, you get the Integer that you put in; if you need an int, you must unbox the Integer using the intValue method. All of this boxing and unboxing is audtomated in Java 5.
It is not appropriate to use autoboxing and unboxing for scientific computing, or other performance-sensitive numerical code. An Integer is not a substitute for an int; autoboxing and unboxing blur the distinction between primitive types and reference types, but they do not eliminate it.
Stupid Comparator
There is a big flaw in this comparator. if i2 is a big integer and i1 is a small negative integer then the result could be a long number and goes beyond integer and the comparator behaves stupidly. Always beware of CLEVER codes your write!!
Comparator<Integer> cmp = new Comparator<Integer>() { public int compare(Integer i1, Integer i2) { return i2 - i1; } };
Hiding Inherited Members
In case of a method you can not hide a an inherited method (you can override it) but you can do for varibales which is not a good practice.
public class Base { public String ss; public void testme(){} } public class Derived extends Base { private String ss; // this does not give compile error and hides Base.ss which is not a good thing private void testme(){} // this gives compile error }
Final Methods and Fields
Final modifier means something completely different on methods and fields. On a method, final means that the method may not be overridden or hidden (for static methods) but on a field, final means the field may not be assigned more than once. The keyword is the same, but the behavior is different. We can HIDE final fields of super class in a subclass but it is a bad idea.
Hiding, Shadowing, Obscuring
Whatever they are just avoid them! You might not even use them once in a lifetime! Also avoid name re-using.
Method Scope
When calling a method, the compiler searches for the method in the innermost enclosing scope containing a method with the correct name; this may not always be what we want! For more info see JLS.
Singleton and Serialization
A singleton class that implements Serializable must have a readResolve method that returns its sole instance. Watch out when your singleton extends or implements a class which has Serializable in its hierarcy.
Exception Tips
- Throw exceptions as early as possible.
- Catch exceptions as later a possible. Let come come up in the hierarchy and catch when really needed.
- Reuse Java's exceptions and do not write your exceptions all the time.
Generics
List<E> is a generic interface, List<String> is a parameterized type, and List alone is a raw type.
Avoid mixing them together in the code.
Also the raw type List is not the same as the parameterized type List<Object>!
List<?> is a special kind of parameterized type known as a wildcard type.
public List<String> doSomething() {} List lis = doSomething();//if we do this the compiler has no idea if "lis" is raw or parameterized.
The Ternary Conditional Operator ?:
I usually forget this: myVal = (a < b; a ? b);
Another usage is like:
boolean a;
a = b > c ? true : false;
Eclipse IDE
| Item | Desc |
|---|---|
| Ctrl + F7 | Views |
| Ctrl + F8 | Perspectives |
| Crtl + F6 | Similar to Ctrl + E |
| Ctrl + Right/Left Arrow | Back and forth |
| Ctrl + O | Class Summary |
| SVN Plugin | Subversive or Subeclipse are good. The latter is simpler. If you don't get to enter your username and password then need to set SVN interface client in preferences. In my case it is SVNKit now. Can add files specially Eclipse .classpath to ignore list using TortoiseSVN in Windows. |
Marker Interface
There are empty interfaces in Java such as Cloneable, Serializable, … These are known as marker (tag) interfaces. They just categorise the derived classes into a category based on their purpose. Marker interfaces are understood by the JVM. For example, all classes that implement the Cloneable interface can be cloned (the clone() method can be called on them). The Java compiler checks to make sure that if the clone() method is called on a class and the class implements the Cloneable interface, if not, you will get a compile error.
You can write marker interfaces yourself as well. Context interface in Apache Chain is a marker interface. It doesn't do anything and just extends Map but defines a category for objects that implement it or extend the ContextBase.
Comparator Based On Two Fields
See the following object. I want to write a comparator based on its two fields.
public class MyObject { private Integer speed; private Integer sequence; //getters and setters }
"speed" is the main (outer) field and "sequence" is the second (inner) fields that I want to compare based on them. When two objects have same "speed" then I will compare based on "sequence":
public class PlanSortComparator implements Comparator<MyObject> { public int compare(MyObject o1, MyObject o2) { Integer speed1 = o1.getSpeed(); Integer speed2 = o2.getSpeed(); if (speed1 == null && speed2 == null) return new DisplayOrderComparator().compare(o1, o2); else if (speed1 == null) return -1; else if (speed2 == null) return 1; else if (speed1.intValue() == speed2.intValue()) return new DisplayOrderComparator().compare(o1, o2); else return speed1.compareTo(speed2); } public class DisplayOrderComparator implements Comparator<MyObject> { public int compare(MyObject o1, MyObject o2) { Integer sequence1 = o1.getSequence(); Integer sequence2 = o2.getSequence(); if (sequence1 == null && sequence12 == null) return 0; else if (sequence1 == null) return -1; else if (sequence2 == null) return 1; else return sequence1.compareTo(sequence2); } } }
With this code if we do sorting then MyObject1(speed=33,sequence=8) will come before MyObject2(speed=39,sequence=4) and MyObject1(speed=33,sequence=5) will come before MyObject2(speed=33,sequence=9).
new Integer(int) OR Integer.valueOf(int) ?
Using new Integer(int) is guaranteed to always result in a new object whereas Integer.valueOf(int) allows caching of values to be done by the compiler, class library, or JVM. Using of cached values avoids object allocation and the code will be faster.
Values between -128 and 127 are guaranteed to have corresponding cached instances and using valueOf is approximately 3.5 times faster than using constructor. For values outside the constant range the performance of both styles is the same.
Unless the class must be compatible with JVMs predating Java 1.5, use either autoboxing or the valueOf() method when creating instances of Long, Integer, Short, Character, and Byte.






