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

Kotlin转Java代码求助:请将指定Kotlin代码转换为Java代码

Kotlin to Java Conversion for Your Queue Processing Code

Got it, let's break down your original Kotlin code first to make sure we capture all its logic, then convert it to equivalent Java.

What the original Kotlin code does:

  • Loops through every index from 0 to n-1
  • For each index i:
    • Reads an integer from the scanner, subtracts 1 to get a key/index itis
    • Adds the current index i to the queue stored at allData[itis] (the !! means we're sure this queue isn't null)
    • When that queue hits exactly k elements, we pull all k elements out (one by one with poll()) and add each one to the front of the corresponding list in result (so the first polled element goes to result[0].addFirst(), the second to result[1].addFirst(), etc.)

Equivalent Java Code

First, make sure you have the right imports:

import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

Then the converted code:

// Assume these variables are initialized properly before this block:
// - Scanner sc = new Scanner(System.in); (or your input source)
// - Queue<Integer>[] allData = new Queue[/* appropriate size */];
//   (initialize each element with new LinkedList<>() to avoid NPEs)
// - LinkedList<Integer>[] result = new LinkedList[k];
//   (initialize each element with new LinkedList<>())

for (int i = 0; i < n; i++) {
    int itis = sc.nextInt() - 1;
    // Get the queue for this key (we ensure it's initialized, no nulls)
    Queue<Integer> queue = allData[itis];
    queue.add(i);
    
    if (queue.size() == k) {
        for (int j = 0; j < k; j++) {
            // Poll the head of the queue and add it to the front of result[j]
            result[j].addFirst(queue.poll());
        }
    }
}

Key Notes:

  • In Kotlin, (0 until n).forEach translates to a standard for loop in Java—it's more idiomatic and efficient for this use case.
  • The Kotlin !! operator asserts that allData[itis] isn't null. In Java, you'll need to initialize every element in allData with a new LinkedList<>() before running this code to avoid NullPointerExceptions.
  • addFirst() is specific to LinkedList in Java (the generic List interface doesn't define this method), so we use LinkedList<Integer> for the result array to match the Kotlin behavior exactly.
  • poll() works identically in both languages: it removes and returns the head of the queue. Our logic ensures the queue has exactly k elements when we call this, so we don't have to handle empty queue cases here.

内容的提问来源于stack exchange,提问作者Daria K

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 03:42:33