Duplicate Imports in Java: Compiler Ignores, No Runtime Impact

使用 GPT-4o-mini 回答Java Q&A Hub

問題:

Is it possible to import the same class or package twice in Java and what happens to it during runtime?

答案:

In Java, it is possible to import the same class or package multiple times in a source file. However, the Java compiler ignores duplicate import statements. This means that if you have multiple import statements for the same class or package, they will not cause any issues during compilation or runtime.

For example, the following code is perfectly valid:

import java.util.List;
import java.util.List; // Duplicate import

public class Example {
    public static void main(String[] args) {
        List<String> myList = new ArrayList<>();
    }
}

In this case, the second import java.util.List; is redundant and will be ignored by the compiler.

Runtime Behavior

At runtime, the Java Virtual Machine (JVM) does not have any concept of import statements. Imports are purely a compile-time feature that helps the compiler resolve class names. Once the code is compiled into bytecode, the import statements are not included in the bytecode. Therefore, there is no impact on runtime performance or behavior due to duplicate imports.

Summary

  • You can import the same class or package multiple times in Java.
  • The compiler ignores duplicate imports.
  • Import statements do not affect runtime behavior, as they are not present in the compiled bytecode.