Sunday, July 7, 2013

"Optional" Implementation on Interface Methods

Some interface definitions state that certain methods are optional. Iterator<E> is an example in Oracle Docs. The method remove() is said optional.

But Java language requires that every method in an interface is implemented by every implementation of that interface. There are no exceptions to this rule. It confused me for this point and I did some research. It turned out that the implementation is not really optional but it can be empty.

Take the remove() method of interface Iterator<E> as en example. The signature is
void remove();

To make this implementation optional, one can do one of following two. Either way, you are implementing the method.
void remove() {
    // empty
}
void remove() {
    throw new UnsupportedOperationException();
}
This is the real meaning of "optional" implementation. Of course, one can choose to actually implement the method like below.
void remove() {
    // do some thing here
    // validate state and remove element
}

Saturday, July 6, 2013

Interface Implementation and Class Inheritance

Short note:
If superclass implements some interface and is extended by some subclass, by default the subclass implicitly implemented all methods declared in the interface. Programmers do not need to explicitly specify the implements as in superclass. However, it won't hurt if they do so.

Interface definition:

Superclass definition:

Subclass definition can be either of following two:
(Programmers do not have to override the methods, even explicitly using implements)

Inheritance and Override in Java

Some learning and testing code on Java class inheritance and member override.

Super class in pkg1:

Sub class in pkg2:

Main class for testing in pkg3:

Output:
in super private method1
in sub public method2
in super private method3
in super public method4
in super package-private method5
in sub private method1
in sub public method2
in sub public method3
in super public method4

Some points about inheritance and override in Java:
  1. Only public or protected members can be overridden. In above test code, Line 21 in SubClass.java will break if commented out.
  2. If moving SubClass and SuperClass to the same package, Line 21 in SubClass.java will work since default access scope is package-private.
  3. private or package-private members cannot be overridden. Even they have definitions with same signature, they are different methods and overriding rules and resolution don't apply to them.
  4. If calling in subclass, even with super, JVM will try to locate overriding members in subclass. Again, this happens only when the member is declared as public or protected.

Thursday, July 4, 2013

Android App Development Notes


  1. Error: "string_id" is not translated in es... (languages)

    Eclipse > Window > Preferences > Android > Lint Error Checking > Change the Severity for "MissingTranslation" to Warning

  2. Error: Attribute is missing the Android namespace prefix

    Add prefix "android:" to the element that complains, like "android:color="#A00080FF"

  3. Class requires API level 11 (current min is 8): android.view.ActionMode.Callback

    One solution is to change android:minSdkVersion from "8" to "11" in Manifest.xml.


How to Implement Singleton in Java

There are multiple solutions for this. Let me describe one by one.

Solution 1:

Solution 2:
Compared to Solution 1, this one is easier to change the singularity if things change.

Solution 3:
Compared to Solutions 1 and 2, this one is lazy instantiation and used double checked locking. Do not synchronize the method instead because for most cases if the instance is already initialized, threads want to return right away. Also, note the volatile in Line 2. This is used to avoid the out-of-order issue of double checked locking solution.

Solution 4:
This is a preferred solution as of Java v5.0.

Monday, July 1, 2013

Android Development Environment Setup with Eclipse

Very good tutorial to set up Android development environment on Linux:
http://www.wikihow.com/Install-Android-on-Ubuntu-Linux-With-Eclipse-Ide

For Windows, one of my friends wrote a nice blog, too.
http://blog.csdn.net/lihancheng/article/details/5783310

When I was trying to set up the development environment, I tried both Linux (Ubuntu 12.0.4, 32 bit) and Windows (Windows 7, 64 bit). Here are some problems I encountered:

  1. Change language encoding to GB2312 to enable Chineses characters

    Open project in Eclipse → Right click the project → Properties → Resource → Text file encoding → Other (Select or input GB2312, it's a combo box)

  2. Unable to resolve target 'android-8'

    This was because I didn't install the required level of Android API. I installed Android 4.2.2 (API 17) instead of Android 2.2 (API 8), but the project I was testing on required API 8. After I installed this version, the error disappeared.

    Windows menu in Eclipse → Android SDK Manager → Check Android 2.2 (API 8) in package list → Install packages

    On Ubuntu, I didn't see that version in the package list initially. I "remember" I did following to fix this:

    Open Android SDK Manager → Go to tab Tools → Click Options → Check "Force https://... sources to be fetched using http://" (The hint for this check item is: if you are not able to connect to the official Android repository using HTTPS, enable this setting to force accessing it via HTTP.)

  3. Virtual device is too large on the display

    Here is one reference to fix this: http://android.yaohuiji.com/archives/151

    More specifically,
    Run menu in Eclipse → Run Configurations → Select the project in Android Application fold → Target tab → Scroll down to "Additional Emulator Command Line Options" → Input "-scale 0.8" (or any other number you want to scale down)

  4. Chinese characters display on app

    After I successfully started up the emulator and launched the app, there are some unrecognizable encoding. This should be because of the Chinese language use in this app. After I enabled the Chinese language on the emulator and installed a Chinese input app to input Chinese, this error went away and the app can start up as expected.

  5. Special problem on Ubuntu (not resolved)
    Waiting for HOME ('android.process.acore') to be launched...
    [*** Emulator] Failed to load libGL.so
    Emulator-5554 disconnected! Cancelling 'xxx.yyy activity launch'!

    I searched online and tried almost all suggestions available but failed to resolve the issue. Not sure if this is related to my old computer or dual systems installed on the old machine. I turned over to a relatively newer Windows machine and was able to start the emulator correctly.

  6. Data files missing on SD card of the emulator

    Go to DDMS perspective → Open or activate Devices view → Select the emulator you want to add files to → Click File Explorer tab on the right → Locate the directory "/mnt/sdcard" → Click the right arrow on the upper right corner (to push files to the emulator) → Locate the file/directory you want to copy to SD card → Click Open and submit

Wednesday, June 19, 2013

Useful Links

This blog is just used as reference and put some useful links together for future convenience. Will update this blog from time to time.

How to Install Oracle Java JDK on Ubuntu Linux

Introduction to SVN

How to Install Android on Ubuntu Linux With Eclipse Ide

Install Third Party Apps on Android

For 3rd-party apps that are not in Google Play, one can install them by manually downloading the .apk files to SD card and then installing with package installer.

Just a simple note here. By default, 3rd-party apps are not allowed on Android and users have to change the settings. I am using a Android 4.1.1 (Jelly Bean) and here is the setting change.

1. Go to Main Menu
2. Select "Settings"
3. In "Personal" section, select "Security"
4. In "Device administration" section, check "Unknown sources"

Thursday, June 13, 2013

Shuffle an Array

Question:
Given an input array, shuffle it and output a randomized sequence.

Analysis:
The array can actually be of any type, not necessary integer or number. One special example is to shuffle a deck of cards. That happens to be of integer type.

Variations:
There may be different variations of this similar problem. I hope to summarize all the cases here and would like to go through each with some implementation.
  1. Randomize an array of n elements
  2. Randomly select m elements out of an array of n elements
  3. Randomly select m elements out of a stream of n elements (n is known before hand)
  4. Randomly select m elements out of a stream of elements (not sure how many elements there are until stopping reading)

This blog talks about Case 1. The code is not hard but there are some tricks. It's better to select from the end of array and that will help control the number of elements remained. Also, the code will be cleaner.


The mathematical proof would be trickier and it's good to have some combinatorics. The probability of any output sequence will be \[\frac{1}{n!}\]

Sunday, June 9, 2013

Decide if a Binary Tree is Binary Search Tree

Question:
Given a binary tree, validate if it's a binary search tree.

Analysis:
The elements in a BST are sorted if traversed in-order. This is a very important feature BST and based on the definition, the problem can be solved by in-order traversal.

The class definition of tree node:

Based on the analysis above, we can have the implementation below.

Many people may think we can simply check "left.value < parent.value < right.value" for each node. That being said, we can have an implementation like this:

However, this is not correct. Simply checking the parent and children relationship is not sufficient. Here is a counter-example.

      5
     /  \
    /    \
   3    7
  / \    / \
2  6  4  9

This is a top-down approach although it's not correct. If adding more constraints on the value for each node, there is a working solution for this. Here is the implementation:

Thursday, June 6, 2013

Find Next Character in Sorted String

Question:
Given a sorted array of unique elements R, that are letters of English alphabet and an input character x. The elements in R are sorted with the least element appearing first. Find the minimum r in R such that r > x. If there is no r > x, find the first element of the array (wrap around).

Example:
R = ['c', 'f', 'j', 'p', 'v']
if x equals:
'a' => return 'c'
'c' => return 'f'
'k' => return 'p'
'z' => return 'c' (wrap around case)

Wednesday, June 5, 2013

Is Input String a Valid Number?

Question:
Given an input string, check if it is in a valid number format.

Analysis:
Valid number format can be either positive or negative, can be integer or float number.

Solution 1:
Directly call Java library method and if the string is not in a valid format, it will throw out an exception. Return false if catching an exception.

Solution 2:
Make a regular expression and call the string library method to see if the input matches the pattern.

Solution 3:
Start from no library method available. Compare and make decision based on the characters in the input.

Saturday, April 6, 2013

Synchronized and Unsynchronized Types in Java

TypesSynchronizedUnsynchronized
HashtableY-
HashMap-Y
VectorY-
ArrayList-Y
StringBufferY-
StringBuilder-Y

Hashtable & HashMap & HashSet

Hashtable
  1. A table of records
  2. Stores key-value pairs
  3. Implements Map interface
  4. Does not allow null key
  5. Does not allow null values
  6. Synchronized

HashMap
  1. Stores key-value pairs
  2. Implements Map interface
  3. Allows null key (at most one)
  4. Allows null values (arbitrary number)
  5. Unsynchronized

HashSet
  1. A collection of elements
  2. Implements Set interface
  3. Allows null element (at most one)
  4. Unsynchronized