我对java很新,所以想知道我是否能得到一些基本的帮助。
我有一个名为Timetable的课程
public class Timetable
{ private String Month;
private String Day;
private int[] times;
public Timetable(String month, String Day, int[] times)
{
this.month = month;
this.day = day;
//initalize various times..
此类与Timetables的另一个类(LinkedList)相关,它添加月,日和时间。喜欢这个..
Add(new Timetable("May","Monday", **???**));
现在我需要添加数组中的时间,例如{1,2,3,4}或{2,4,9},并且只有int [4]索引。
有关如何初始化时间并将int []次传递给创建时间表的任何建议吗?
答案 0 :(得分:0)
您可以在调用Add方法之前初始化数组:
int[] times = {1, 2, 3, 4};
Add(new Timetable("May", "Monday", times));
或:
int[] times = {5, 6, 7};
Add(new Timetable("May", "Monday", times));
答案 1 :(得分:0)
您也可以像这样添加时间:
LinkedList<Timetable> link = new LinkedList<Timetable>();
link.add(new Timetable("May", "Monday", new int[]{1, 2, 3, 4}));
link.add(new Timetable("June", "Sunday", new int[]{5, 6, 7}));
答案 2 :(得分:0)
除了其他答案,您还可以调整构造函数签名
public Timetable(String month, String Day, int... times) { /*...*/ }
Timetable类中的用法将保持不变(int...
参数映射到int
s的数组),但优点是调用将简化为
LinkedList<Timetable> link = new LinkedList<Timetable>();
link.add(new Timetable("May", "Monday", 1, 2, 3, 4)); // array creation is now optional
link.add(new Timetable("May", "Monday", new int[]{1, 2, 3, 4})); // works as well
link.add(new Timetable("June", "Sunday", 5, 6, 7));