Which class would work best for a non-ordered list of pairs? I'll be taking a bunch of (float,short) pairs and will need to be able to perform simple math (like multiplying the pair together to return a single float, etc). List only takes one argument, and HashMap won't allow duplicates (as far as I know). Any thoughts?
List<Pair<Integer,String>> pairList = new ArrayList<Pair<Integer,String>>(); public class Pair<Key,Value> { private Key key; private Value value; public Pair(Key key, Value value){ this. key = key; this.
You can use the Entry<U,V>
class that HashMap
uses but you'll be stuck with its semantics of getKey
and getValue
:
List<Entry<Float,Short>> pairList = //...
My preference would be to create your own simple Pair
class:
public class Pair<L,R> { private L l; private R r; public Pair(L l, R r){ this.l = l; this.r = r; } public L getL(){ return l; } public R getR(){ return r; } public void setL(L l){ this.l = l; } public void setR(R r){ this.r = r; } }
Then of course make a List
using this new class, e.g.:
List<Pair<Float,Short>> pairList = new ArrayList<Pair<Float,Short>>();
You can also always make a List
s of List
s, but it becomes difficult to enforce sizing (that you have only pairs) and you would be required, as with arrays, to have consistent typing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With