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
0ton-1 - For each index
i:- Reads an integer from the scanner, subtracts 1 to get a key/index
itis - Adds the current index
ito the queue stored atallData[itis](the!!means we're sure this queue isn't null) - When that queue hits exactly
kelements, we pull allkelements out (one by one withpoll()) and add each one to the front of the corresponding list inresult(so the first polled element goes toresult[0].addFirst(), the second toresult[1].addFirst(), etc.)
- Reads an integer from the scanner, subtracts 1 to get a key/index
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).forEachtranslates to a standardforloop in Java—it's more idiomatic and efficient for this use case. - The Kotlin
!!operator asserts thatallData[itis]isn't null. In Java, you'll need to initialize every element inallDatawith anew LinkedList<>()before running this code to avoidNullPointerExceptions. addFirst()is specific toLinkedListin Java (the genericListinterface doesn't define this method), so we useLinkedList<Integer>for theresultarray 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 exactlykelements when we call this, so we don't have to handle empty queue cases here.
内容的提问来源于stack exchange,提问作者Daria K
相关产品推荐
相关产品推荐

