Data Types and Exceptions in Java
Jim White
Java Developer
Map
interface defines operations on the key and value pairsMap
Map
that are similar in behaviorMap
is HashMap
HashMap<Integer, String> map = new HashMap<Integer, String>();
The parameterized/ generic constructor for a HashMap
requires two types
The first type = the key type
The second type = the value type
java.util.HashMap
.put(key,value)
to add a key/value pairs to the table.remove(key)
to remove the key/value pair specified at the key.get(key)
to retrieve the value from the table at the keyimport java.util.HashMap
...
HashMap<Integer, String> map
= new HashMap<Integer, String>();
map.put(0, "Jim");
map.put(1, "James");
map.put(3, null);
map.put(4, "James");
map.remove(0);
System.out.println(map);
{1=James, 3=null, 4=James}
String nickname = map.get(1);
System.out.println(nickname);
James
java.util.Collections
is a supporting classstatic
methodsList
addAll(List list, Object a, b, ...)
frequency(Collection c, Object o)
List
reverse(List list)
List
sort(List list)
List
with another objectfill(List a, Object o)
ArrayList<String> x = new ArrayList<String>(); Collections.addAll(x, "milk", "bread", "eggs", "milk"); System.out.println(x);
int cnt = Collections.frequency(x, "milk"); System.out.println(cnt);
Collections.reverse(x); System.out.println(x);
Collections.sort(x); System.out.println(x);
Collections.fill(x, "sugar"); System.out.println(x);
[milk, bread, eggs, milk]
2
[milk, eggs, bread, milk]
[bread, eggs, milk, milk]
[sugar, sugar, sugar, sugar]
int[]
) to a List
List
has greater capability (searching, sorting, etc.)java.util.Arrays
is another supporting classList
String[] arrayCountries = {"France", "Japan", "Brazil", "Egypt", "China"};
List<String> countries = Arrays.asList(arrayCountries);
System.out.println(countries);
[France, Japan, Brazil, Egypt, China]
Data Types and Exceptions in Java