Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a list of pairs in java

Tags:

java

list

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?

like image 772
V1rtua1An0ma1y Avatar asked Jan 24 '11 00:01

V1rtua1An0ma1y


People also ask

How do you create an ArrayList of pairs in Java?

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.


1 Answers

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 Lists of Lists, but it becomes difficult to enforce sizing (that you have only pairs) and you would be required, as with arrays, to have consistent typing.

like image 120
Mark Elliot Avatar answered Oct 20 '22 02:10

Mark Elliot