The class AbstractMap.SimpleEntry is generic and can be useful.
Answer from Eyal Schneider on Stack OverflowThe class AbstractMap.SimpleEntry is generic and can be useful.
Android programmers could use BasicNameValuePair
Update:
BasicNameValuePair is now deprecated (API 22). Use Pair instead.
Example usage:
Pair<Integer, String> simplePair = new Pair<>(42, "Second");
Integer first = simplePair.first; // 42
String second = simplePair.second; // "Second"
personally i wouldn't, i like the built-in collections just fine.
having said that...
- if you want something with better performance/smaller in-memory size, have a look at trove. they have map implementations that do away with the extra Entry (key-value pair) class. theyre especially good if your keys or values are primitives (say, ints)
- if you want something with better predictability (another performance aspect), have a look at javolution. their collections classes offer much better worst-case times (think what happens when you insert something into a standard collection and you just triggered a resize...)
- if youre looking for collections classes with more features, have a look at guava
Try Generics and create your own class if you don't like java collections:
public class Pair<K, V> {
private K key;
private V value;
public Pair(K key, V value) {
this.key = key;
this.value = value;
}
public K getKey() {
return key;
}
public void setKey(K key) {
this.key = key;
}
public V getValue() {
return value;
}
public void setValue(V value) {
this.value = value;
}
public static void main(String[] args) {
Pair<String, String> pair = new Pair<String, String>("key", "value");
System.out.println(pair.getKey());
System.out.println(pair.getValue());
}
}
You will need to create your own. This is done (AFAIK) to facilitate a better semantic meaning from the class name, than a general Pair<> or KeyValuePair<> would
http://docs.oracle.com/javase/7/docs/api/java/util/Map.Entry.html
and an implementation from SO Java - How to create new Entry (key, value)
One of the best ways is HashMap:
Use this sample:
HashMap<String, Integer> dicCodeToIndex;
dicCodeToIndex = new HashMap<String, Integer>();
// valuating
dicCodeToIndex.put("123", 1);
dicCodeToIndex.put("456", 2);
// retrieving
int index = dicCodeToIndex.get("123");
// index is 1
Look at this link: http://docs.oracle.com/javase/6/docs/api/java/util/HashMap.html
You can use the various implementations of java.util.Map (see http://docs.oracle.com/javase/7/docs/api/java/util/Map.html). The most commonly used Map implementation for a dictionary-like map should be HashMap.
However, depending on the exact usage scenario, another type of map might be better.