具有不同类型的二维ArrayList

时间:2016-11-07 09:32:16

标签: java

假设我想创建一个ArrayList,如下所示:

[
    [500000, 999999, 900000, "D\u0305", "C\u0305M\u0305"]
    [100000, 499999, 400000, "C\u0305", "C\u0305D\u0305"]
    [50000, 99999, 90000, "L\u0305", "X\u0305C\u0305"]
    [10000, 49999, 40000, "X\u0305", "X\u0305L\u0305"]
    [5000, 9999, 9000, "V\u0305", "MX\u0305"]
    [1000, 4999, 4000, "M", "MV\u0305"]
    [500, 999, 900, "D", "CM"]
    [100, 499, 400, "C", "CD"]
    [50, 99, 90, "L", "XC"]
    [10, 49, 40, "X", "XL"]
]

有没有人知道使用java实现类似内容的最佳途径?

2 个答案:

答案 0 :(得分:1)

有点不清楚你在问什么。在Java中,我们实际上没有2D数组。相反,我们有阵列数组。同样,只有1D ArrayList可以包含不同的ArrayList

另一件事是存储的类型。我建议你自己编写一个可以存储罗马字母或阿拉伯字母的课程。

public class RomanOrArabic {
    private Long arabic;
    private String roman;

    public boolean isArabic(){
        return arabic != null;
    }
    //add getters, smart setters, validators for String being Roman etc.
}

然后声明您的ArrayList

ArrayList<ArrayList<RomanOrArabic>> list = new ArrayList<>();

答案 1 :(得分:0)

我看到有一些混乱,所以我想我会在这里发布解决方案。

    // The solution
    Object RomanNumeralValues[][] = {
            {500000, 999999, 900000, "D\u0305", "C\u0305M\u0305"},
            {100000, 499999, 400000, "C\u0305", "C\u0305D\u0305"},
            {50000, 99999, 90000, "L\u0305", "X\u0305C\u0305"},
            {10000, 49999, 40000, "X\u0305", "X\u0305L\u0305"},
            {5000, 9999, 9000, "V\u0305", "MX\u0305"},
            {1000, 4999, 4000, "M", "MV\u0305"},
            {500, 999, 900, "D", "CM"},
            {100, 499, 400, "C", "CD"},
            {50, 99, 90, "L", "XC"},
            {10, 49, 40, "X", "XL"}
    };

    // Where the solution gets used
    String romanNumeral = "";
    for (Object rmRange[]: RomanNumeralValues) {
        romanNumeral += extractRomanNumeralsBelowOneMillion(
                (int)rmRange[0],
                (int)rmRange[1],
                (int)rmRange[2],
                rmRange[3].toString(),
                rmRange[4].toString()
        );
    }

我不习惯使用类型转换来将值从对象数组中拉出来,但我猜它有效。如果有人有更好的解决方案,我会打开这个问题。