Attention and tips- java

Initialize before operate

Let’s take a list as an example: a list must be firstly initialized using “new ArrayList<>()…” before we add anything into it, or will cause a NullPointerException.

Remove something from a list

Here is the example: ZigZagIterator2. When removing something from a list in a for/while loop, we have to check the list size. (e.g. fixed size in BFS layer traversal, set fixed size = queue.size()). In this example, we have to make sure when we removing an item, we roll the index/pointer back (j–).

Initialize an empty array

Sometimes we have to return an empty array. Pay attention that the array might be 0 instead of null if you used “new” to initialize. A good way to solve this problem is to build an empty array. int[] empty = {};

Don’t initialize as null

Take queue as an example, initialize it like “queue…. = new Queue<>()” instead of null. If you set it null, you will get a NullPointer exception when you try to push/add/do any operation.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s