Tuesday, April 24, 2012

Hashmap vs LinkedHashMap

During development of one my project I got confused and annoyed,I was displaying the contents of Hashmap,I was amazed to see the order in which the contents were displayed.
After hours of brain-storming I came to conclusion that there is no guarantee of elements on Hashmap.Here are there few conclusion I had found.

A LinkedHashMap differs from HashMap in that the order of elements is maintained.
A HashMap has a better performance than a LinkedHashMap because a LinkedHashMap needs the expense of maintaining the linked list. The LinkedHashMap implements a normal hashtable, but with the added benefit of the keys of the hashtable being stored as a doubly-linked list.
Both of their methods are not synchronized.
Let's take a look their API documentations:

The HashMap is a hash table with buckets in each hash slot. Like in the API documentation:

This implementation provides constant-time performance for the basic operations (get and put), assuming the hash function disperses the elements properly among the buckets. Iteration over collection views requires time proportional to the "capacity" of the HashMap instance (the number of buckets) plus its size (the number of key-value mappings). Thus, it's very important not to set the initial capacity too high (or the load factor too low) if iteration performance is important.

The LinkedHashMap is a linked list implementing the map interface. As said in the API documentation:

Hash table and linked list implementation of the Map interface, with predictable iteration order. This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order).

Tuesday, April 17, 2012

Java 7 new features

I have in love with Java decade ago,As time passed my love for Java decreased day by day due to lack of features as compared other programming languages.
But I have surprised to see the new features in Java 7 and I must say that Java came back to scene with with a right timing and graceful manner.
Few things I have observed in Java 7 are.
Numeric value with a underscore.
Now we can use underscore in numeric value such as
int amount=10_000;


More Stylish Exception Handling
 try {

methodThatThrowsThreeExceptions();

} catch (ExceptionOne | ExceptionTwo | ExceptionThree e) {

// log and deal with all Exceptions

}

String in switch block
         String id = t.getId();
switch (id) {
case ONE:
//code
break;
case TWO:
//code
break;
case THREE:
//code
break;
default:
break;
}

When not to use Base64 encoding

It has been my long voyage to find where we have use base64 encoding. Recently I was developing an android app where I have get encoded (base64 encoded) from server and displays them in ListView.
The app performance was annoying I have make my app behave properly. After long brain storming I have found some interesting result which I want to share with you guys.

Here are some of my findings
  • base64 encoding makes file size roughly 33% larger than their original binary representation.
  • base64 encoded data may possible take more resources(memory + CPU).
I will update my result later.

Download Progress in Android

I was trying to integrate the progress with download in android finally I got it.
public class DownloadExampleActivity extends Activity {
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private Button startBtn;
private ProgressDialog mProgressDialog;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
startBtn = (Button) findViewById(R.id.startBtn);
startBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
startDownload();
}
});
}

private void startDownload() {
String url = "http://www.kleenspeed.com/blog/wp-content/uploads/2011/10/DSCN1590.jpg";
new DownloadFileAsync().execute(url);
}

@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Downloading file..");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}

class DownloadFileAsync extends AsyncTask {

@Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}

@Override
protected String doInBackground(String... aurl) {
int count;

try {

URL url = new URL(aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();

int lenghtOfFile = conexion.getContentLength();
Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);

InputStream input = new BufferedInputStream(url.openStream());
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
}
} catch (Exception e) {
Toast.makeText(DownloadExampleActivity.this, e.getMessage(),
Toast.LENGTH_SHORT).show();
}
return null;

}

protected void onProgressUpdate(String... progress) {
Log.d("ANDRO_ASYNC", progress[0]);
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}

@Override
protected void onPostExecute(String unused) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
}
}