Java 不同类型的数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2815672/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 13:10:50  来源:igfitidea点击:

Arrays of different types

java

提问by Tyler

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;

But that didn't work.

但这没有用。

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?

然后更进一步,如果可能,我想按双精度对数组进行排序?

Thanks!

谢谢!

采纳答案by Jon Skeet

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

首先,有必要弄清楚数组和数组之间的区别ArrayList——它们根本不是一回事。

However, in either case you can't do what you want. The closest you can probably come is declaring your own type. (EDIT: My original code had a double ora string... I've now changed it to be a double anda string. Let me know if this change isn'twhat 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;
    }
}

Then create an ArrayList<DoubleAndString>or a DoubleAndString[].

然后创建一个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.

现在,现在感觉有点普通——大概双精度值和字符串值实际上具有更大的含义——例如名称和分数。如果是这样,请将其封装在更恰当地描述配对的类型中。

As for ordering - you couldmake DoubleAndStringimplement Comparable<DoubleAndString>- but unless that's the onlynatural ordering which makes sense, I'd write a Comparator<DoubleAndString>:

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

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

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

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

回答by Yann Ramin

It sounds like you want a Map. Since you wish to sort the Map, a TreeMap may be optimal.

听起来你想要一张地图。由于您希望对 Map 进行排序,因此 TreeMap 可能是最佳的。

Map<Double, String> myMap = new TreeMap<Double, String>();

Maps are associative. Each double has an associated string. If you want multiple strings per double, you can use a

地图是关联的。每个双精度值都有一个关联的字符串。如果你想要每个双精度多个字符串,你可以使用

Map<Double, ArrayList<String>>

回答by Maxem

What do you want to do?

你想让我做什么?

If it is not a key value mapping, you should create a new class for this.

如果它不是键值映射,您应该为此创建一个新类。

回答by Michael Aaron Safyan

Well, if you want to have an array with an arbitrary number of elements, then you simply need to use a type that is a common ancestor to both. In this case, that would be Object (since String and Double both inherit from Object). This will require you to check the types, though, when you retrieve or use them.

好吧,如果你想要一个包含任意数量元素的数组,那么你只需要使用一个类型,它是两者的共同祖先。在这种情况下,这将是 Object(因为 String 和 Double 都继承自 Object)。但是,这将要求您在检索或使用它们时检查类型。

If you are using a fixed number of multiple different types, then what you really want is a "tuple". However, Java currently does not have an implementation of tuple available. For two items:

如果您使用固定数量的多种不同类型,那么您真正想要的是“元组”。但是,Java 目前没有可用的元组实现。对于两个项目:

public class Pair<T1,T2>
{
    public Pair(){
          this(null,null);
    }

    public Pair(T1 x1){
          this(x1,null);
    }

    public Pair(T1 x1, T2 x2){
         _x1 = x1;
         _x2 = x2;
    }

    public T1 getFirst(){
        return _x1;
    }

    public T1 getSecond(){
        return _x2;
    }

    private T1 _x1;
    private T2 _x2;
}

回答by James Black

You can just do ArrayList<object> arraylistand then you can put anything in it, but that may not be what you want.

你可以做ArrayList<object> arraylist,然后你可以把任何东西放进去,但这可能不是你想要的。

Then, to sort you would just use your own comparator but, as theatrus mentioned, are these two values supposed to be connected, or do you have a single-dimension array with two different data types?

然后,要排序,您只需使用自己的比较器,但是,正如 theatrus 所提到的,这两个值是否应该连接,或者您是否有具有两种不同数据类型的单维数组?

回答by roguesys

You can use ArrayList<Object>and you can then use anything you'd like. Encapsulate the doublein a Doubleobject and when you retrieve the object use instanceofto check if it's really a doubleor a String.

您可以使用ArrayList<Object>,然后您可以使用任何您喜欢的东西。将 封装double在一个Double对象中,当您检索该对象时,使用instanceof它来检查它是否真的是 adouble或 a String

I must say, it's unlikely this 'design' would win you any awards. Is it possible to rethink the solution you're considering for your problem, and see if you could do with a different kind of approach?

我必须说,这种“设计”不太可能为您赢得任何奖项。是否有可能重新考虑您正在考虑的问题的解决方案,并看看您是否可以采用不同的方法?

回答by theraneman

You might already know this, but it is not certainly not a good idea to store different types in a list. By definition an array is a collection of similar objects and stuffing all kinds in it makes things fuzzy. So really you would rather have a separate type to hold these different values.

您可能已经知道这一点,但将不同类型存储在列表中肯定不是一个好主意。根据定义,数组是相似对象的集合,在其中填充各种对象会使事情变得模糊。所以你真的宁愿有一个单独的类型来保存这些不同的值。

回答by Affe

An ArrayList by definition only contains one object per position. You could do something like this:

根据定义,ArrayList 每个位置仅包含一个对象。你可以这样做:

List<MyTuple> list = new ArrayList<MyTuple>();

public static class MyTuple implements Comparable<MyTuple> {

    private Double doubleValue;
    private String stringValue;

    //getters and setters

    public int compareTo(MyTuple tuple) {
        return doubleValue.compareTo(tuple.getDoubleValue());
    }
}

You can then use the Collections.sort() method to sort it by the Doubles.

然后,您可以使用 Collections.sort() 方法按双打对其进行排序。

回答by Justin

You may want to look at the Number base class.

您可能想查看 Number 基类。

List<Number> list = new ArrayList<Number>(); 
list.add(new Integer(3)); 
list.add(new Double(5.2));

You may interpret the numbers as strings, using NumberFormat:

您可以使用 NumberFormat 将数字解释为字符串:

NumberFormat formatter = new DecimalFormat("#.##");
String s = formatter.format(list.get(0));

Though this may not be what you want, you are a bit short on details about your end goal.

尽管这可能不是您想要的,但您对最终目标的详细信息有点缺乏。

回答by Phani

if you are basically not trying to do any comparisons/sorting on the ArrayList then you could create something as below:

如果您基本上不尝试对 ArrayList 进行任何比较/排序,那么您可以创建如下内容:

List list = new ArrayList();

列表列表 = 新的 ArrayList();

otherwise.. Jon Skeet's answer was best approach.

否则..乔恩斯基特的答案是最好的方法。