不同类型的数组 [英] Arrays of different types

查看:139
本文介绍了不同类型的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以拥有包含两种不同类型数据的数组?我想要一个包含double和字符串的数组。我尝试过:

Is it possible to have an array that contains two different types of data? I want to have an array that contains a double and also a string. I attempted:

ArrayList<double><String> array;

但这不起作用。

对不起这个愚蠢的问题,但已经有一段时间了,因为我使用过这样的东西..你能否刷新我的记忆,我将如何声明和填充这样的数组?

Sorry for the silly question, but it has been a while since I have used something like this.. Can you refresh my memory on how would I declare and populate such an array?

然后再向前迈进一步,如果可能,我想用双排序数组?

And then to take it a step further, I would like to sort the array by the double if possible?

谢谢!

推荐答案

首先,值得清楚的是数组与 ArrayList 之间的区别 - 它们不是完全相同的事情。

Firstly, it's worth being clear about the difference between an array and an ArrayList - they're not the same thing at all.

然而,在任何一种情况下,你都无法做你想做的事。你可能来的最接近的是声明你自己的类型。 (编辑:我原来的代码有一个双一个字符串...我现在把它改成了一个双一个字符串。让我知道这个改变是否不是你的想法。)

However, in either case you can't do what you want. The closest you can probably come is declaring your own type. ( My original code had a double or a string... I've now changed it to be a double and a string. Let me know if this change isn't what you had in mind.)

public final class DoubleAndString
{
    private final String stringValue;
    private final double doubleValue;

    public DoubleAndString(String stringValue, double doubleValue)
    {
        this.stringValue = stringValue;
        this.doubleValue = doubleValue;
    }

    public String getString()
    {
        return stringValue;
    }

    public String getDouble()
    {
        return doubleValue;
    }
}

然后创建 ArrayList< DoubleAndString> DoubleAndString []

现在,这感觉有点香草味当下 - 大概是双重和字符串值实际上有更大的含义 - 例如名称和分数。如果是这样,请将其封装在更恰当描述配对的类型中。

Now, this feels somewhat vanilla at the moment - presumably the double and string values actually have a greater meaning - a name and a score, for example. If so, encapsulate that in a type which describes the pairing more appropriately.

至于订购 - 你可以制作 DoubleAndString 实现 Comparable< DoubleAndString> - 但除非那是唯一的自然顺序,这是有道理的,我会写一个 Comparator< DoubleAndString>

As for ordering - you could make DoubleAndString implement Comparable<DoubleAndString> - but unless that's the only natural ordering which makes sense, I'd write a Comparator<DoubleAndString>:

public class DoubleComparator implements Comparator<DoubleAndString>
{
    public int compare(DoubleAndString ds1, DoubleAndString ds2)
    {
        return Double.compare(ds1.getDouble(), ds2.getDouble());
    }
}

然后你可以使用收藏.sort ArrayList< DoubleAndString> Arrays.sort 进行排序以对数组进行排序。

Then you can use Collections.sort to sort an ArrayList<DoubleAndString> or Arrays.sort to sort an array.

这篇关于不同类型的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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