How do wildcards in Java import work?

人盡茶涼 提交于 2021-02-05 05:21:55

问题


I've been noticing some unexpected results with my imports, and I'm hoping to understand what's really going on. I started with the following:

import java.util.*;
import java.io.*;
import java.nio.*;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption.*;
import java.nio.file.Paths;

and then found that ArrayList and ListIterator didn't work...so I added

import java.util.ArrayList;
import java.util.ListIterator;

and everything works perfectly.

I would have assumed that java.util.* would have also imported ArrayList and ListIterator. Why didn't it?

I've a tendency to be overly verbose with my class/method/variable names, and I didn't find anything in the rest of the program that was even close to a reserved word.

I can't find anything in the documentation that suggests why this would occur, and most of the discussion on Stack is about optimaztion using * vs. explicitly coded imports.

Anyone have any ideas what else I can look at to get an understanding of this behavior?


回答1:


import java.util.* definitely imports java.util.ArrayList and everything else in that package too. Note that there's no concept of sub-packages, so it wouldn't import anything from java.util.x or java.util.y, but that doesn't appear to be the case with your issue.

You must have some other problem wrong with your code if it's not working, the import statements definitely behave as you describe.




回答2:


i have tried in eclipse.

import java.util.*;

these both the classes no need import again.

import java.util.ArrayList;
import java.util.ListIterator;

because wild card * means import all sub classes and packages (remember not package sub class)

if you import

import java.util.*;

i will import java.util.jar package but not jar subclasses :)



来源:https://stackoverflow.com/questions/10314782/how-do-wildcards-in-java-import-work

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!