Sử dụng HashMap trong java


import  java.util.HashMap;

  • Khởi dựng HashMap (HashMap Contructor)

HashMap hashMapName = new HashMap();

HashMap hashMapName = new HashMap(5);
//The 5 sets the initial element capcaity.

HashMap hashMapName = new HashMap(5, .9);
//The 5 sets the initial element capcaity.
//The .9 is the load factor.
//  The default load factor is .75.

HashMap hashMapName = new HashMap(mapIn);
//creates a new HashMap with the elements of a map.

  • Tìm kiếm trong HashMap :

int HashMapSize = hashMapName.size();

boolean isHashMapEmpty = hashMapName.isEmpty();

boolean isObjectKeyInHashMap =
hashMapName.containsKey(objectToSearchForAsKey);

boolean isObjectValueInHashMap =
hashMapName.containsValue(objectToSearchForAsValue);

  • Lấy về các phần tử từ HashMap :

Object objectName =
(ClassTypeToCastTo) hashMapName.get(keyToGetObjectValueFor);
//note: Objects coming out of HashMaps have lost
//  their class type, and must be cast

Set setOfAllKeys = hashMapName.keySet();
//The set is a “view”,
//  so changes to the original HashMap change the view,
//  and changes to the view change the original HashMap.

Collection collectionOfAllValues = hashMapName.values();
//The collection is a “view”,
//  so changes to the original HashMap change the view,
//  and changes to the view change the original HashMap.

Set setOfAllEntryValues = hashMapName.entrySet();
//note: “Returns a collection view of the mappings
//  contained in this map”
//  (Platform API Spec, See online refs)
//The collection is a “view”,
//  so changes to the original HashMap change the view,
//  and changes to the view change the original HashMap.

Object cloneOfHashMap = hashMapName.clone();
//Shallow copy of HashMap,
//  objects in HashMap are not cloned.

  • Thêm hoặc xóa các đối tượng trong HashMap :

Object objectReplacedForKey =
hashMapName.put(objectKey, objectToAdd);
//inserts object value for a specified key
//returns the object that is replaced for that key,
//  null if nothing is repplaced

hashMapName.putAll(mapToAdd);
//adds a map into the HashMap

hashMapName.remove(keyObject);
//removes a key and value pair for a key

hashMapName.clear();

Gửi phản hồi

Please log in using one of these methods to post your comment:

WordPress.com Logo

Bạn đang bình luận bằng tài khoản WordPress.com Log Out / Thay đổi )

Twitter picture

Bạn đang bình luận bằng tài khoản Twitter Log Out / Thay đổi )

Facebook photo

Bạn đang bình luận bằng tài khoản Facebook Log Out / Thay đổi )

Google+ photo

Bạn đang bình luận bằng tài khoản Google+ Log Out / Thay đổi )

Connecting to %s