对对象的二维数组列表进行排序

Sorting 2D Arraylist of Object

我有 2D Arralist of Object,我想根据包含 LocalDate 的第一列对其进行排序

我用这个代码来排序

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d/M/yyyy");
    formatter = formatter.withLocale( Locale.US );

ArrayList<ArrayList<Object>> cusKashf = new ArrayList<ArrayList<Object>>();

cusKashf.addAll(new ReadBillDeateals().readSell(textField_4.getText()));
Collections.sort(cusKashf , new Comparator<ArrayList<Object>>() {
      @Override
      public int compare(ArrayList<Object> entry1, ArrayList<Object> entry2) {
             return ((LocalDate.parse(entry1.get(0).toString(), formatter)).compareTo((LocalDate.parse(entry2.get(0).toString(), formatter))));
            }
        });

问题是这段代码发生了异常,我想知道我的代码哪里错了

这是异常报告

java.lang.IndexOutOfBoundsException: Index: 2, Size: 0
    at java.util.ArrayList.rangeCheck(Unknown Source)
    at java.util.ArrayList.get(Unknown Source)
    at reports.Kashf.compare(Kashf.java:327)
    at reports.Kashf.compare(Kashf.java:1)
    at java.util.TimSort.countRunAndMakeAscending(Unknown Source)
    at java.util.TimSort.sort(Unknown Source)
    at java.util.Arrays.sort(Unknown Source)
    at java.util.ArrayList.sort(Unknown Source)
    at java.util.Collections.sort(Unknown Source)
    at reports.Kashf.actionPerformed(Kashf.java:324)
    at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
    at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
    at javax.swing.plaf.basic.BasicButtonListener$Actions.actionPerformed(Unknown Source)
    at javax.swing.SwingUtilities.notifyAction(Unknown Source)
    at javax.swing.JComponent.processKeyBinding(Unknown Source)
    at javax.swing.JComponent.processKeyBindings(Unknown Source)
    at javax.swing.JComponent.processKeyEvent(Unknown Source)
    at java.awt.Component.processEvent(Unknown Source)
    at java.awt.Container.processEvent(Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.KeyboardFocusManager.redispatchEvent(Unknown Source)
    at java.awt.DefaultKeyboardFocusManager.dispatchKeyEvent(Unknown Source)
    at java.awt.DefaultKeyboardFocusManager.preDispatchKeyEvent(Unknown Source)

您尝试比较的列表中有一个是空的,请尝试通过 try and catch 包围或在获取项目 0 之前检查列表是否为空。

在你的 cusKashf 列表中检查子列表是否不为空。

@Override
  public int compare(ArrayList<Object> entry1, ArrayList<Object> entry2) {
     if(Objects.isNull(entry1) || entry1.isEmpty())  return -1;
     if(Objects.isNull(entry2) || entry2.isEmpty())  return -1;

     return ((LocalDate.parse(entry1.get(0).toString(), formatter)).compareTo((LocalDate.parse(entry2.get(0).toString(), formatter))));
  }