Kotlin中ArrayList存储tasks类对象报错及任务打印方法咨询
Let's break down what's going wrong and how to fix it, step by step.
Why Your Code Is Throwing an Error
You're hitting two key issues here:
- Invalid ArrayList Initialization: The
ArrayListconstructor doesn’t accept individual objects as direct arguments. Valid constructors are either empty, take an initial capacity integer, or a singleCollection(like aList). Passing twotasksinstances directly isn’t allowed—there’s no overload for that. - (Best Practice) Class Naming: In Kotlin, class names should start with an uppercase letter (so
tasks→Task). This isn’t a hard error, but it’s a standard convention that makes your code easier to read and maintain.
Corrected Code
First, let’s fix the Task class (with a proper name and a toString() override to make printing meaningful):
class Task(var title: String, var time: String) { // Override toString() to get a human-readable output when printing tasks override fun toString(): String { return "Task: '$title' (scheduled at $time)" } }
Next, initialize your task list correctly. You have two simple options:
Option 1: Use mutableListOf() (Recommended)
mutableListOf() creates a MutableList (implemented as an ArrayList under the hood on the JVM) and lets you pass elements directly:
fun main(args: Array<String>) { val tasksList = mutableListOf( Task("hello", "3am"), Task("meet amy", "5pm") ) }
Option 2: Use ArrayList with a Collection
If you specifically need an ArrayList type, pass a List of tasks to the ArrayList constructor:
fun main(args: Array<String>) { val tasksList = ArrayList<Task>( listOf( Task("hello", "3am"), Task("meet amy", "5pm") ) ) }
How to Print Your Tasks
Now that your list is set up correctly, printing the tasks is straightforward. Since we overridden toString(), each task will print with its title and time instead of a generic object reference.
Loop Through the List
Use a for loop to iterate and print each task:
for (task in tasksList) { println(task) }
Or Use forEach
A more concise way with Kotlin’s lambda syntax:
tasksList.forEach { println(it) }
Either way, the output will look like this:
Task: 'hello' (scheduled at 3am) Task: 'meet amy' (scheduled at 5pm)
内容的提问来源于stack exchange,提问作者Funris

