Android Apps and Game Developer
Jumat, 30 Juni 2017
Senin, 15 Agustus 2016
Different Between HashMap and HashTable
Difference between HashMap and Hashtable is one of the most popular java interview questions.
We have already discussed other popular java interview questions like ArrayList vs Vector and Comparator vs Comparable .This question is generally asked in java intereview to check whether candidate understand correct usage of collection classes and has knowledge of alternative solutions. Difference between hashmap and hashtable includes five point namely Synchronization,Null keys and values,Iterating values , Fail fast iterator ,Performance,Superclass .
Read Also : Difference between HashMap and ConcurrentHashMap with Example
Difference between HashMap and HashTable / HashMap vs HashTable
1. Synchronization or Thread Safe : This is the most important difference between two . HashMap is non synchronized and not thread safe.On the other hand, HashTable is thread safe and synchronized.
When to use HashMap ? answer is if your application do not require any multi-threading task, in other words hashmap is better for non-threading applications. HashTable should be used in multithreading applications.
2. Null keys and null values : Hashmap allows one null key and any number of null values, while Hashtable do not allow null keys and null values in the HashTable object.
3. Iterating the values: Hashmap object values are iterated by using iterator .HashTable is the only class other than vector which uses enumerator to iterate the values of HashTable object.
4. Fail-fast iterator : The iterator in Hashmap is fail-fast iterator while the enumerator for Hashtable is not.
According to Oracle Docs, if the Hashtable is structurally modified at any time after the iterator is created in any way except the iterator's own remove method , then the iterator will throw ConcurrentModification Exception.
Structural modification means adding or removing elements from the Collection object (here hashmap or hashtable) . Thus the enumerations returned by the Hashtable keys and elements methods are not fail fast.We have already explained the difference between iterator and enumeration.
5. Performance : Hashmap is much faster and uses less memory than Hashtable as former is unsynchronized . Unsynchronized objects are often much better in performance in compare to synchronized object like Hashtable in single threaded environment.
6. Superclass and Legacy : Hashtable is a subclass of Dictionary class which is now obsolete in Jdk 1.7 ,so ,it is not used anymore. It is better off externally synchronizing a HashMap or using a ConcurrentMap implementation (e.g ConcurrentHashMap).HashMap is the subclass of the AbstractMap class. Although Hashtable and HashMap has different superclasses but they both are implementations of the "Map" abstract data type.
Example of HashMap and HashTable
Output : Hashtable object output :{Love=yourself, Alive is =awesome}
HashMap object output :{Alive is =awesome, Love=yourself}
Similarities Between HashMap and Hashtable
1. Insertion Order : Both HashMap and Hashtable does not guarantee that the order of the map will remain constant over time. Instead use LinkedHashMap, as the order remains constant over time.
2. Map interface : Both HashMap and Hashtable implements Map interface .
3. Put and get method : Both HashMap and Hashtable provides constant time performance for put and get methods assuming that the objects are distributed uniformly across the bucket.
4. Internal working : Both HashMap and Hashtable works on the Principle of Hashing . We have already discussed how hashmap works in java .
When to use HashMap and Hashtable?
1. Single Threaded Application
HashMap should be preferred over Hashtable for the non-threaded applications. In simple words , use HashMap in unsynchronized or single threaded applications .
2. Multi Threaded Application
We should avoid using Hashtable, as the class is now obsolete in latest Jdk 1.8 . Oracle has provided a better replacement of Hashtable named ConcurrentHashMap. For multithreaded application prefer ConcurrentHashMap instead of Hashtable.
Recap : Difference between HashMap and Hashtable in Java
In case you have any other query please mention in the comments .
We have already discussed other popular java interview questions like ArrayList vs Vector and Comparator vs Comparable .This question is generally asked in java intereview to check whether candidate understand correct usage of collection classes and has knowledge of alternative solutions. Difference between hashmap and hashtable includes five point namely Synchronization,Null keys and values,Iterating values , Fail fast iterator ,Performance,Superclass .
Read Also : Difference between HashMap and ConcurrentHashMap with Example
Difference between HashMap and HashTable / HashMap vs HashTable
1. Synchronization or Thread Safe : This is the most important difference between two . HashMap is non synchronized and not thread safe.On the other hand, HashTable is thread safe and synchronized.
When to use HashMap ? answer is if your application do not require any multi-threading task, in other words hashmap is better for non-threading applications. HashTable should be used in multithreading applications.
2. Null keys and null values : Hashmap allows one null key and any number of null values, while Hashtable do not allow null keys and null values in the HashTable object.
3. Iterating the values: Hashmap object values are iterated by using iterator .HashTable is the only class other than vector which uses enumerator to iterate the values of HashTable object.
4. Fail-fast iterator : The iterator in Hashmap is fail-fast iterator while the enumerator for Hashtable is not.
According to Oracle Docs, if the Hashtable is structurally modified at any time after the iterator is created in any way except the iterator's own remove method , then the iterator will throw ConcurrentModification Exception.
Structural modification means adding or removing elements from the Collection object (here hashmap or hashtable) . Thus the enumerations returned by the Hashtable keys and elements methods are not fail fast.We have already explained the difference between iterator and enumeration.
5. Performance : Hashmap is much faster and uses less memory than Hashtable as former is unsynchronized . Unsynchronized objects are often much better in performance in compare to synchronized object like Hashtable in single threaded environment.
6. Superclass and Legacy : Hashtable is a subclass of Dictionary class which is now obsolete in Jdk 1.7 ,so ,it is not used anymore. It is better off externally synchronizing a HashMap or using a ConcurrentMap implementation (e.g ConcurrentHashMap).HashMap is the subclass of the AbstractMap class. Although Hashtable and HashMap has different superclasses but they both are implementations of the "Map" abstract data type.
Example of HashMap and HashTable
import java.util.Hashtable; public class HashMapHashtableExample { public static void main(String[] args) {
Hashtable<String,String> hashtableobj = new Hashtable<String, String>(); hashtableobj.put("Alive is ", "awesome"); hashtableobj.put("Love", "yourself"); System.out.println("Hashtable object output :"+ hashtableobj);
HashMaphashmapobj = new HashMap (); hashmapobj.put("Alive is ", "awesome"); hashmapobj.put("Love", "yourself"); System.out.println("HashMap object output :"+hashmapobj);
} }
Output : Hashtable object output :{Love=yourself, Alive is =awesome}
HashMap object output :{Alive is =awesome, Love=yourself}
Similarities Between HashMap and Hashtable
1. Insertion Order : Both HashMap and Hashtable does not guarantee that the order of the map will remain constant over time. Instead use LinkedHashMap, as the order remains constant over time.
2. Map interface : Both HashMap and Hashtable implements Map interface .
3. Put and get method : Both HashMap and Hashtable provides constant time performance for put and get methods assuming that the objects are distributed uniformly across the bucket.
4. Internal working : Both HashMap and Hashtable works on the Principle of Hashing . We have already discussed how hashmap works in java .
When to use HashMap and Hashtable?
1. Single Threaded Application
HashMap should be preferred over Hashtable for the non-threaded applications. In simple words , use HashMap in unsynchronized or single threaded applications .
2. Multi Threaded Application
We should avoid using Hashtable, as the class is now obsolete in latest Jdk 1.8 . Oracle has provided a better replacement of Hashtable named ConcurrentHashMap. For multithreaded application prefer ConcurrentHashMap instead of Hashtable.
Recap : Difference between HashMap and Hashtable in Java
HashMap | Hashtable | |
---|---|---|
Synchronized | No | Yes |
Thread-Safe | No | Yes |
Null Keys and Null values | One null key ,Any null values | Not permit null keys and values |
Iterator type | Fail fast iterator | Fail safe iterator |
Performance | Fast | Slow in comparison |
Superclass and Legacy | AbstractMap , No | Dictionary , Yes |
In case you have any other query please mention in the comments .
Selasa, 02 Agustus 2016
Android Code - Marshmallow Asking Permission
Pada onCreate
cek versi android
int currentapiVersion = android.os.Build.VERSION.SDK_INT; if (currentapiVersion >= 23) { // Do something for 14 and above versions cek(); } else { // do something for phones running an SDK before 14 }
Tambahkan function berikut
private static final int PERMISSION_REQUEST_CODE = 1;
public void cek(){ if (checkPermission()) { // Snackbar.make(getCurrentFocus(),"Permission already granted.",Snackbar.LENGTH_LONG).show(); } else { // Snackbar.make(getCurrentFocus(),"Please request permission.",Snackbar.LENGTH_LONG).show(); } if (!checkPermission()) { requestPermission(); } else { Snackbar.make(getCurrentFocus(),"Permission already granted.",Snackbar.LENGTH_LONG).show(); } } private boolean checkPermission(){ int result = ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE); if (result == PackageManager.PERMISSION_GRANTED){ return true; } else { return false; } } private void requestPermission(){ if (ActivityCompat.shouldShowRequestPermissionRationale(this,Manifest.permission.WRITE_EXTERNAL_STORAGE)){ Toast.makeText(getApplicationContext(),"GPS permission allows us to access location data. Please allow in App Settings for additional functionality.",Toast.LENGTH_LONG).show(); } else { ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},PERMISSION_REQUEST_CODE); } } @Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { switch (requestCode) { case PERMISSION_REQUEST_CODE: if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // Snackbar.make(getCurrentFocus(),"Permission Granted, Now you can access location data.",Snackbar.LENGTH_LONG).show(); } else { // Snackbar.make(getCurrentFocus(),"Permission Denied, You cannot access location data.", Snackbar.LENGTH_LONG).show(); } break; } }
Selasa, 20 Mei 2014
Langganan:
Postingan (Atom)