Erinevus lehekülje "JavaPython:Sõnastikud" redaktsioonide vahel
2. rida: | 2. rida: | ||
Pythoni sõnastikud on sarnased Java "map"-idele. | Pythoni sõnastikud on sarnased Java "map"-idele. | ||
+ | |||
+ | A <b>HashMap</b> is like a Python dictionary, but uses only object syntax. There are no literals. Declaration and creation look like: | ||
+ | <pre>HashMap<keyType, valueType> variable = new HashSet<keyType, valueType>();</pre> | ||
+ | |||
+ | Some methods: | ||
+ | <pre>type put(key, value) (returns previous value), type get(key), boolean containsKey(key).</pre> | ||
== Näide == | == Näide == |
Redaktsioon: 2. veebruar 2016, kell 11:01
Java vs Python |
|
Pythoni sõnastikud on sarnased Java "map"-idele.
A HashMap is like a Python dictionary, but uses only object syntax. There are no literals. Declaration and creation look like:
HashMap<keyType, valueType> variable = new HashSet<keyType, valueType>();
Some methods:
type put(key, value) (returns previous value), type get(key), boolean containsKey(key).
Näide
Java | Python |
---|---|
<syntaxhighlight lang="java" line="1" >
HashMap<String, String> phoneBook = new HashMap<String, String>(); phoneBook.put("Mike", "555-1111"); phoneBook.put("Lucy", "555-2222"); phoneBook.put("Jack", "555-3333"); //iterate over HashMap Map<String, String> map = new HashMap<String, String>(); for (Map.Entry<String, String> entry : map.entrySet()) { System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); } //get key value phoneBook.get("Mike"); //get all key Set keys = phoneBook.keySet(); //get number of elements phoneBook.size(); //delete all elements phoneBook.clear(); //delete an element phoneBook.remove("Lucy"); </syntaxhighlight> |
<syntaxhighlight lang="python" line="2" >
phoneBook = {} phoneBook = {"Mike":"555-1111", "Lucy":"555-2222", "Jack":"555-3333"}
for key in phoneBook: print(key, phoneBook[key])
phoneBook["Mary"] = "555-6666"
del phoneBook["Mike"]
count = len(phoneBook)
phoneBook["Susan"] = (1,2,3,4)
print phoneBook.keys()
phoneBook.clear() </syntaxhighlight> |