【问题标题】:Reordering array into arrayList at a certain position在某个位置将数组重新排序为arrayList
【发布时间】:2016-09-21 07:28:43
【问题描述】:

我正在尝试重新格式化一些日期字符串。他们中的一些人在开始时有年份,我希望那些在年底时有他们的年份。我还想将分隔符标准化为下划线。

示例输入:

07_April_2008
16_05_2012
2016-01-28
14/12/2009

期望的输出:

07_April_2008
16_05_2012
01_28_2016
14_12_2009

这是我的第一次尝试,但是当我这样做时出现错误:

public String format(String date) {
    String[] format = null;
    date = date.replace("-", "_");
    date = date.replace("/", "_");
    if (date.contains("_")) {
        format = date.split("_");
        // new arrayList to add rearrangement to
        ArrayList<String> formatNew = new ArrayList<String>();
        for (int i = 0; i < format.length; i++) {
            if (format[i].matches("\\d{4}")) {
                formatNew.add(2, format[i]);
            } else {
                formatNew.add(format[i]);
            }
        }
    }
    return date;
}

这会产生错误:

java.lang.IndexOutOfBoundsException:索引:2,大小:0

我认为年份的选择很好,但数组中的其他两个元素没有。

【问题讨论】:

  • 不确定你在问什么。异常告诉你究竟出了什么问题;您正在尝试访问索引 2;在长度为 0 的数组中。换句话说:不要假设 date.split() 创建一个包含三个元素的数组 - 检查它以确保。以及为什么需要其他人来弄清楚:“也许我应该打印出一些跟踪语句以查看发生了什么;或者,见鬼,在调试器中运行它以查看每个值会发生什么”?!
  • 您可以使用SimpleDateFormat 来解析和格式化日期。

标签: java arrays string date arraylist


【解决方案1】:

我会将其视为字符串问题:

List<String> dates; // given this
dates = dates.stream()
    .map(s -> s.replaceAll("\\W", "_")) // anything not a letter or number becomes _
    .map(s -> s.replaceAll("(\\d{4})_(.*)", "$2_$1")) // reorganise leading year dates
    .collect(Collectors.toList());

如果您只想格式化日期字符串:

str.replaceAll("\\W", "_").replaceAll("(\\d{4})_(.*)", "$2_$1")

如果你想保留分隔符(只改为下划线让你的代码工作):

str.replaceAll("(\\d{4})(.)(.*)", "$3$2$1")

【讨论】:

  • 简单就是美丽。也不需要收藏。只是简单的'全部替换
  • @SebastianZeki 谢谢。我在答案的末尾添加了另一种方法,可以根据您的最终目标进一步简化。
【解决方案2】:

来自 Java 文档

在此列表中的指定位置插入指定元素。将当前位于该位置的元素(如果有)和任何后续元素向右移动(将它们的索引加一)。

下面是ArrayList.add(index,E)方法源码

public void add(int index, E element) {
if (index > size || index < 0)
    throw new IndexOutOfBoundsException(
    "Index: "+index+", Size: "+size);
...

所以很明显,如果index 大于size 或负数,它将抛出IndexOutOfBoundsException

看看DateFormatUtils,它有很多标准的日期格式,你可以用它来格式化日期

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-17
    • 2015-10-28
    • 2012-05-07
    • 2012-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-17
    相关资源
    最近更新 更多