在java中创建对列表 [英] Creating a list of pairs in java

查看:283
本文介绍了在java中创建对列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

哪个类对于非有序的对列表最有效?我将采用一堆(浮动,短)对,并且需要能够执行简单的数学运算(比如将这些对相乘以返回单个浮点数等)。 List只接受一个参数,而HashMap不允许重复(据我所知)。有什么想法吗?

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?

推荐答案

你可以使用条目< U,V> HashMap 使用的类,但你会被它的语义 getKey getValue所困扰

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>>();

您还可以随时生成列表 s 列表,但很难强制执行大小调整(只有对),并且与数组一样,您需要具有一致的输入。

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.

这篇关于在java中创建对列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆