我应该使用静态列表还是创建并返回列表的静态方法?

时间:2016-11-26 17:38:57

标签: java list constructor static

试图像用户建议一样

private final static List<CalendarBankHoliday> COL_BANK_HOLIDAY_LIST 
        = Collections.unmodifiableList(Arrays.asList(new CalendarBankHoliday(2016,Calendar.DECEMBER,26), 
        new CalendarBankHoliday(2016,Calendar.DECEMBER,27), new CalendarBankHoliday(2017, Calendar.JANUARY, 2),
        new CalendarBankHoliday(2017, Calendar.APRIL, 14),  new CalendarBankHoliday(2017, Calendar.APRIL, 17),
        new CalendarBankHoliday(2017, Calendar.MAY, 1),     new CalendarBankHoliday(2017, Calendar.MAY, 29),
        new CalendarBankHoliday(2017, Calendar.AUGUST, 28), new CalendarBankHoliday(2017, Calendar.DECEMBER, 25),
        new CalendarBankHoliday(2017, Calendar.DECEMBER, 26)
        ));

2 个答案:

答案 0 :(得分:1)

您似乎正在创建预定义假期列表,并且您只需要一个列表。因此你应该这样做:

public class ListManager
{
    private static final List bankHolidayList = new ArrayList<>();

    private ListManager()
    {
        bankHolidayList.add(...);
    }

    public static List getList()
    {
        return Collections.unmodifiableList(bankHolidayList);
    }
}

这意味着您将获得一个不可变的列表。

答案 1 :(得分:0)

要返回列表,不需要使用static关键字,如果要在创建方法时返回列表,则不要使用void,请使用要返回的相同类型的数组列表。

示例:

public class Test{

  public ArrayList<Integer> myNumbers()    {
  ArrayList<Integer> numbers = new ArrayList<Integer>();
  numbers.add(5);
  numbers.add(11);
  numbers.add(3);
  return(numbers);
  }
}