You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kotlin中ArrayList存储tasks类对象报错及任务打印方法咨询

Fixing Your To-Do List App Errors & Printing 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 ArrayList constructor doesn’t accept individual objects as direct arguments. Valid constructors are either empty, take an initial capacity integer, or a single Collection (like a List). Passing two tasks instances 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:

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:27:22