Master Core Java Concepts!
Subscribe to Ram N Java for clear explanations, practical code examples, and essential Java tutorials!
Subscribe Now on YouTubeWhat Is Static Import with Collections in Java?
The static import feature expands the capability of the import keyword by allowing you to access static members (fields and methods) of a class directly without qualifying them with the class name.
The java.util.Collections class contains numerous static utility fields and methods such as EMPTY_LIST, emptySet(), and sort(). Using static import allows you to refer to them directly in your code without repeatedly writing Collections..
Two Forms of Static Import Statements
-
Single Static Member Import: Imports only a specific static member of a class.
Syntax:import static package.ClassName.staticMemberName;
Example:import static java.util.Collections.EMPTY_LIST; -
All Static Members Import (On-Demand): Imports all static fields and methods of a class.
Syntax:import static package.ClassName.*;
Example:import static java.util.Collections.*;
Code Example: Without Static Import
import java.util.List;
import java.util.Set;
public class WithoutStaticImportExample {
public static void main(String[] args) {
List<String> list = Collections.EMPTY_LIST;
Set<String> set = Collections.emptySet();
System.out.println("List: " + list);
System.out.println("Set: " + set);
}
}
Code Example: With Static Import
import java.util.List;
import java.util.Set;
public class StaticImportExample {
public static void main(String[] args) {
// Directly accessible without Collections qualification
List<String> list = EMPTY_LIST;
Set<String> set = emptySet();
System.out.println("List: " + list);
System.out.println("Set: " + set);
}
}
Key Takeaways
✔️ Cleaner Code: Eliminates repetitive class name prefixes when calling static methods or constants.
✔️ Targeted or Wildcard: You can import a single static member or all static members with .*.
✔️ Readability Balance: Use static import wisely to avoid cluttering your namespace or confusing method origins.
No comments:
Post a Comment