在Java中,将对象作为列表输入到数组中
我是Java的初学者。我想从用户那里获取2D数组的输入,并将其转换为对象列表在Java中,将对象作为列表输入到数组中,java,arraylist,multidimensional-array,Java,Arraylist,Multidimensional Array,我是Java的初学者。我想从用户那里获取2D数组的输入,并将其转换为对象列表 当我硬编码数据时,可以这样做 class Job // Job Class { public int taskID, deadline, profit; public Job(int taskID, int deadline, int profit) { this.taskID = taskID; this.deadline = deadline; this.profit = prof
- 当我硬编码数据时,可以这样做
class Job // Job Class { public int taskID, deadline, profit; public Job(int taskID, int deadline, int profit) { this.taskID = taskID; this.deadline = deadline; this.profit = profit; } } public class JobSequencing{ public static void main(String[] args) { // List of given jobs. Each job has an identifier, a deadline and profit associated with it List<Job> jobs = Arrays.asList( new Job(1, 9, 15), new Job(2, 2, 2), new Job(3, 5, 18), new Job(4, 7, 1), new Job(5, 4, 25), new Job(6, 2, 20), new Job(7, 5, 8), new Job(8, 7, 10), new Job(9, 4, 12), new Job(10, 3, 5) ); }
您能给我一个从用户输入的2D数组中添加对象作为列表的解决方案吗?首先,创建列表,然后在for循环中添加到列表中
List jobs=new ArrayList();
for(int i=0;i
而不是
List<Job> jobs = Arrays.asList(
for(int i=0 ; i< count ; i++){
new Job(arr[i][0], arr[i][1], arr[i][2]);
}
);
List jobs=Arrays.asList(
for(int i=0;i
尝试使用lambda
List<Job> jobs = Arrays.stream(arr)
.map(arrElement -> new Job(arrElement[0],arrElement[1],arrElement[2]))
.collect(Collectors.toList());
List jobs=Arrays.stream(arr)
.map(ArReElement->新作业(ArReElement[0]、ArReElement[1]、ArReElement[2]))
.collect(Collectors.toList());
您也可以使用bufferedReader
尝试这种方法
InputStreamReader isr=新的InputStreamReader(System.in);
BufferedReader BufferedReader=新的BufferedReader(isr);
列表作业=新建ArrayList();
字符串x=bufferedReader.readLine();
字符串[]y;
int count=Integer.parseInt(x);
for(int i=0;i
您希望它做什么<代码>列表作业=数组.asList(用于(int i=0;iArrayList
,然后根据需要将Job
对象添加到构造函数或任何其他方法外的for循环中
List<Job> jobs = Arrays.asList(
for(int i=0 ; i< count ; i++){
new Job(arr[i][0], arr[i][1], arr[i][2]);
}
);
List<Job> jobs = Arrays.stream(arr)
.map(arrElement -> new Job(arrElement[0],arrElement[1],arrElement[2]))
.collect(Collectors.toList());