Map集合
Map集合的基本方法
Map集合没有继承Collection接口,其提供的是key到value的映射。
Map集合中一次添加一对元素,Collection一次添加一个元素。Map集合也称之为双列集合,Collection集合称之为单列集合。
实质上Map集合中存储的就是键值对。Map集合中必须保证键的唯一性。
Map集合中的常用方法:
1.添加
value put(key,value):返回前一个和key关联的值,如果没有,则返回null
2.删除
void clear():清空map集合
value remove(key):根据指定的key删除这个键值对
3.判断
boolean containsKey(key)
boolean containsValue(value)
boolean isEmpty()
4.获取
value get(key):通过键获取值,如果没有该键返回null.
当然可以通过返回null,来判断是否包含指定键。
int size():获取键值对的个数
Map中常见方法的演示:
public class MapDemo {
public static void main(String[] args) {
Map<Integer,String> map=new HashMap<Integer,String>();
method(map);
}
public static void method(Map<Integer,String> map){//学号和姓名
//添加元素
System.out.println(map.put(8, "ben"));
System.out.println(map.put(11, "lily"));
System.out.println(map.put(4, "luna"));
System.out.println(map.put(4, "lucky"));//存相同键值会覆盖
System.out.println(map);
//删除
System.out.println("remove:"+map.remove(8));
//判断
System.out.println("containskey:"+map.containsKey(7));
//获取
System.out.println("get:"+map.get(6));
System.out.println("get:"+map.get(4));
}
}
输出结果
null
null
null
luna
{4=lucky, 8=ben, 11=lily}
remove:ben
containskey:false
get:null
get:lucky
取出Map集合所有元素的方法:
1,通过KeySet方法获取map中所有的键所在的Set集合,再通过Set的迭代器获取到每一个键,再对每一个键获取其对应的值即可。
方法示例:
public class MapDemo {
public static void main(String[] args) {
Map<Integer,String> map=new HashMap<Integer,String>();
method_1(map);
}
public static void method_1(Map<Integer,String> map)
{
map.put(8, "lily");
map.put(3, "cindy");
map.put(9, "ben");
map.put(7, "alice");
Set<Integer> KeySet=map.keySet();
Iterator<Integer> it=KeySet.iterator();
while(it.hasNext()){
Integer key=it.next();
String value=map.get(key);
System.out.println(key+":"+value);
}
}
}
2.通过Map转成set就可以迭代, 找到了另外一个方法:entrySet。该方法将键和值的映射关系作为对象存储到了Set集合中, 而这个映射关系的类型就是Map.Entry类型。
Map.Entry是一个嵌套类,Entry是Map的内部接口。因为它存储的关系依赖于Map集合而存在,所以把它定义为内部接口。其实现原理的伪代码如下:
interface MyMap{
public static interface MyEntry{//内部接口,接口一般不会有静态注释,但是它是一个成员(内部接口)
void get();
}
}
class MyDemo implements MyMap.MyEntry{
@Override
public void get() {
}
}
此方法的方法示例:
public class MapDemo {
public static void main(String[] args) {
Map<Integer,String> map=new HashMap<Integer,String>();
method_1(map);
}
public static void method_1(Map<Integer,String> map)
{
map.put(8, "lily");
map.put(3, "cindy");
map.put(9, "ben");
map.put(7, "alice");
Set<Map.Entry<Integer, String>> entrySet=map.entrySet();
Iterator<Map.Entry<Integer, String>> it=entrySet.iterator();
while(it.hasNext()){
Map.Entry<Integer, String> me=it.next();
Integer key=me.getKey();
String value=me.getValue();
System.out.println(key+":"+value);
}
}
直接获取Map集合的所有value值:values()
方法演示:
public class MapDemo {
public static void main(String[] args) {
Map<Integer,String> map=new HashMap<Integer,String>();
method_1(map);
}
public static void method_1(Map<Integer,String> map)
{
map.put(8, "lily");
map.put(3, "cindy");
map.put(9, "ben");
map.put(7, "alice");
Collection<String> values=map.values();
Iterator<String> it=values.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
}
Map集合的常用子类
Map常用子类:
- Hashtable:内部结构是哈希表,是同步的。不允许null作为键,null作为值。Hashtable类下还有一个子类Properties:用来存储键值对型的配置文件的信息,可以和IO技术相结合。
- HashMap:内部结构是哈希表,是不同步的。允许null作为键和值。
- TreeMap:内部结构是二叉树,不是同步的。可以对Map集合的键进行排序。
jdk1.0的时候没有集合框架,单列的只有vector,双列的只有Hashtable。
HashSet实际上是由一个HashMap实例支持。Set集合的底层代码其实就是由Map集合来实现的。
HashMap集合使用示例:
public class HashMapDemo {
public static void main(String[] args) {
/*
* 将学生对象和学生的归属地通过键和值存储到map集合中。
* */
HashMap<Student,String> hm=new HashMap<Student,String>();
hm.put(new Student("lily",22),"beijing");
hm.put(new Student("baby",12),"shanghai");
hm.put(new Student("ben",20),"chengdu");
hm.put(new Student("alice",13),"wuhan");
hm.put(new Student("alice",13),"hangzhou");
// Set<Student> keySet=hm.keySet();
// Iterator<Student> it=keySet.iterator();
Iterator<Student> it=hm.keySet().iterator();
while(it.hasNext()){
Student key=it.next();
String value=hm.get(key);
System.out.println(key.getName()+":"+key.getAge()+":"+value);
}
}
}
输出:
alice:13:hangzhou
baby:12:shanghai
ben:20:chengdu
lily:22:beijing
这里,Student类见上一篇博客《泛型》里面的代码,Student类继承自Person类。从输出结果可以看到,Student(“alice”,13)被认定为一个人(键相同),所以后面的value为”wuhan”被”hangzhou”覆盖,要实现这种认定,就必须有比较方法,而这里的自定义类本身不具备比较性,所以必须在Person类(或者Student类)重写equals方法和hasCode方法。
TreeMap集合使用示例:
public class TreeMapDemo {
public static void main(String[] args) {
//TreeMap<Student,String> tm=new TreeMap<Student,String>();//Ctrl+f:查询 替换
TreeMap<Student,String> tm=new TreeMap<Student,String>(new ComparatorByName());//Ctrl+f:查询 替换
tm.put(new Student("lily",22),"beijing");
tm.put(new Student("baby",12),"shanghai");
tm.put(new Student("ben",20),"chengdu");
tm.put(new Student("alice",13),"wuhan");
tm.put(new Student("alice",13),"hangzhou");
Iterator<Map.Entry<Student, String>> it=tm.entrySet().iterator();
while(it.hasNext()){
Map.Entry<Student, String> me=it.next();
Student key=me.getKey();
String value=me.getValue();
System.out.println(key.getName()+":"+key.getAge()+":"+value);
}
}
}
初始化不带参数的时候输出结果为:
baby:12:shanghai
alice:13:hangzhou
ben:20:chengdu
lily:22:beijing
这个结果是按照年龄来排序的,这是因为在Person类中实现了Comparable接口,并复写了compareTo()方法,方法中是按照年龄排序的。
初始化带参数的时候输出结果为:
alice:13:hangzhou
baby:12:shanghai
ben:20:chengdu
lily:22:beijing
这个结果是按照姓名来排序的,参数里面传了一个ComparatorByName()比较器(这个比较器的代码见上篇博客《泛型》)。
LinkedHashMap集合使用示例:
public class LinkedHashMapDemo {
public static void main(String[] args) {
HashMap<Integer,String> hm=new LinkedHashMap<Integer,String>();
hm.put(7,"sunny");
hm.put(17,"snow");
hm.put(3,"rain");
hm.put(24,"wind");
Iterator<Map.Entry<Integer,String>> it=hm.entrySet().iterator();
while(it.hasNext()){
Map.Entry<Integer,String> me=it.next();
Integer key=me.getKey();
String value=me.getValue();
System.out.println(key+":"+value);
}
}
}
输出结果:
7:sunny
17:snow
3:rain
24:wind
结果是有序的,输出的顺序即输入的顺序。
Map集合练习
- “fdgavcbsacdfs”获取该字符串中,每个字母出现的次数。
要求打印的结果是:a(2)b(1)….;
思路:
- 字母的个数是有限的,可以将每个字母作为唯一的键,出现的次数作为对应的值,用Map集合的键值对进行存储。具体分析如下:
对于结果的分析发现,字母和次数之间存在着映射关系。而且这种关系很多。很多就需要存储,能存储映射关系的容器有数组和Map集合。
由于任意的关系一方(字母或者次数)都不是有序编号。那就使用Map集合。又发现可以保证唯一性的一方具备中顺序如a b c…所以可以使用TreeMap集合。 - 这个集合中最终应该存储的是字母和次数的对应关系。
2.1 将字符串转换成字符数组;
2.2 遍历字符数组,用字符数组中的每一个字母元素作为键去Map集合中查询:若查询没有这个字母,则将这个字母作为键存入集合中,且值设为一;若查询有这个字母,则将这个字母键对应的值取出,值加一,然后再存入集合当中,这样新的字母和对应的值就会覆盖原来的。
2.3 遍历结束,map集合就记录所有字母的出行次数。
- 字母的个数是有限的,可以将每个字母作为唯一的键,出现的次数作为对应的值,用Map集合的键值对进行存储。具体分析如下:
代码如下:
public class MapTest {
public static void main(String[] args) {
String str="Just one Last-dance~";
String s=getCharCount(str);
System.out.println(s);
}
public static String getCharCount(String str) {
//将字符串变成字符数组
char[] chs=Arrays.toArray(str);
//定义map集合表
Map<Character,Integer> map=new TreeMap<Character,Integer>;
for(int i=0;i<chs.length;i++){
if(!(chs[i]<'a'&&chs[i]>'z'||chs[i]<'A'&&chs[i]>'Z'))
continue;
//将数组中的字母作为键去查map表
Integer value=map.get(chs[i]);
int count=1;
//判断值是否为空
if(!value==null)
count=value+1;
map.put(chs[i],count);
/*
if(value==null){
map.put(chs[i],1);
}else{
map.put(chs[i],value+1);
}
*/
}
return mapToString(map);
}
private static String mapToString(Map<Character, Integer> map) {
StringBuilder sb=new StringBuilder();
Iterator<Character> it=map.keySet().iterator();
while(it.hasNext()){
Character key=it.next();
Integer value=map.get(key);
sb.append(key+"("+value+")");
}
return sb.toString();
}
}
输出结果:
J(1)L(1)a(2)c(1)d(1)e(2)n(2)o(1)s(2)t(2)u(1)
2.查表法应用
Map集合在有映射关系时,可以优先考虑。 在查表法中的应用较为多见。
public class MapTest2 {
public static void main(String[] args) {
/*
Map集合在有映射关系时,可以优先考虑
在查表法中的应用较为多见。
* */
String week=getWeek(1);
System.out.println(week);
System.out.println(getWeekByMap(week));
}
public static String getWeekByMap(String week){
Map<String,String> map=new HashMap<String,String>();
map.put("星期一","Mon");
map.put("星期二","Tues");
map.put("星期三","Wen");
map.put("星期四","Thur");
map.put("星期五","Fri");
map.put("星期六","Sat");
map.put("星期日","Sun");
map.put("星期天","Sun");
return map.get(week);
}
public static String getWeek(int week){
if(week<1||week>7)
throw new RuntimeException("no such week,please input again");
String[] weeks={"","星期一","星期二","星期三","星期四","星期五","星期六","星期天"};
return weeks[week];
}
}
工具类
Collections
Collections是集合框架的工具类。java.util.Collections工具类提供很多有用的方法这些方法都是静态的。
1.对list集合进行指定顺序的排序
public class CollectonsDemo {
public static void main(String[] args) {
/*
* Collections:是集合框架的工具类
* 里面的方法都是静态的
*/
demo_1();
}
public static void demo_1(){
List<String> list=new ArrayList<String>();
list.add("abcdef");
list.add("no");
list.add("yes");
list.add("happy");
list.add("yeah");
System.out.println(list);
//对list集合进行指定顺序的排序
Collections.sort(list);
//mySort(list);//根据工具类里sort方法原理自定义的方法
System.out.println(list);
//mySort_1(list,new ComparatorByLength());根据工具类里带参数的sort方法原理自定义的方法
//System.out.println(list);
Collections.sort(list,new ComparatorByLength());
System.out.println(list);
}
//Collections工具类中不带参数的sort方法实现原理:
public static <T extends Comparable<? super T>>void mySort(List<T> list){
for(int i=0;i<list.size()-1;i++){
for(int j=i+1;j<list.size();j++){
if(list.get(i).compareTo(list.get(j))>0){
// T temp=list.get(i);
// list.set(i,list.get(j));
// list.set(j, temp);
Collections.swap(list, i, j);
}
}
}
}
//Collections工具类中带参数的sort方法实现原理:
public static <T>void mySort_1(List<T> list,Comparator<? super T> comp){
for(int i=0;i<list.size()-1;i++){
for(int j=i+1;j<list.size();j++){
if(comp.compare(list.get(i),list.get(j))>0){
// T temp=list.get(i);
// list.set(i,list.get(j));
// list.set(j, temp);
Collections.swap(list, i, j);
}
}
}
}
}
- 查找(折半查找,以及查找集合中的最大最小值)
public class CollectonsDemo {
public static void main(String[] args) {
demo_2();
}
public static void demo_2(){
List<String> list=new ArrayList<String>();
list.add("abcdef");
list.add("no");
list.add("yes");
list.add("happy");
list.add("yeah");
Collections.sort(list);
System.out.println(list);
int index=Collections.binarySearch(list, "aca");
System.out.println(index);//-2 查找的元素不存在的时候,返回的索引是(-插入点-1),这样即使插入点为0的时候也可以知道
int index1=Collections.binarySearch(list, "yeah");
System.out.println(index1);
//获取最大值
String max=Collections.max(list);//根据元素的自然顺序,返回给定collection的最大元素,同理还有min
System.out.println("max:"+max);
String max1=Collections.max(list,new ComparatorByLength());//根据指定比较器产生的顺序,返回给定collection的最大元素
System.out.println("lengthmax:"+max1);
}
}
- 逆转有序集合中元素的顺序。
public class CollectonsDemo {
public static void main(String[] args) {
demo_3();
}
public static void demo_3() {
/*
//原理
TreeSet<String> ts=new TreeSet<String>(new Comparator<String>(){//匿名内部类 定义了一个基于字符字典顺序的比较器 实现逆序
@Override
public int compare(String o1, String o2) {
int temp=o2.compareTo(o1);
return temp;
}
});
*/
//reverseOrder:返回一个比较器,强行逆转顺序(自然顺序或指定比较器顺序)
// TreeSet<String> ts=new TreeSet<String>(Collections.reverseOrder());
TreeSet<String> ts=new TreeSet<String>(Collections.reverseOrder(new ComparatorByLength()));
ts.add("nani");
ts.add("zzz");
ts.add("wanna");
ts.add("pill");
ts.add("aow");
System.out.println(ts);
}
}
输出:[wanna, pill, nani, zzz, aow]
这里定义了一个字符串长度的比较器:
public class ComparatorByLength implements Comparator<String> {
@Override
public int compare(String o1, String o2) {
int temp=o1.length()-o2.length();
return temp==0?o1.compareTo(o2):temp;
}
}
- 其他:
replaceAll()、shuffle()、fill()等等
public class CollectonsDemo {
public static void main(String[] args) {
demo_4();
}
private static void demo_4() {
List<String> list=new ArrayList<String>();
list.add("abcdef");
list.add("no");
list.add("yes");
list.add("happy");
list.add("yeah");
System.out.println(list);
Collections.replaceAll(list,"happy","crazy");//实现原理:先找到happy元素的索引,然后再用set方法替换
// 使用另一值替换列表中出现的所有某一指定值 set(indexOf("happy"),"crazy");
System.out.println(list);
//shuffle(List<?> list) shuffle(List<?> list,Random rnd) 使用默认(指定)随机源对指定列表进行置换
Collections.shuffle(list);
System.out.println("shuffle:"+list);
Collections.fill(list,"hahaha");//使用指定元素替换指定列表中的所有元素fill(List<? super T> list, T obj)
System.out.println(list);
}
- 给非同步的集合加锁
Collections工具类里有方法:
synchronizedCollection(Collection<T> c)
synchronizedList(List<T> list)
synchronizedMap(Map<K,V> m)
synchronizedSet(Set<T> s)
synchronizedSortedMap(SortedMap<K,V> m)
synchronizedSortedSet(SortedSet<T> s)
给非同步集合加锁原理:
class MyCollections{
public List synList(List list){
return new MyList(list);
}
}
class MyList implements List{
private List list;
private static final Object lock=new Object();
MyList(List list){
this.list=list;
}
public boolean add(Object obj){
synchronized(lock){
return list.add(obj);
}
}
public boolean remove(Object obj){
synchronized(lock){
return list.remove(obj);
}
}
}
其使用如下:
List list=new ArrayLlist();//非同步
list=MyCollections.synLlist(list);
Arrays
Arrays是集合框架的工具类。里面的方法都是静态的。
1. binarySearch
通过二分查找法对有序的数组进行查找。适合除了boolean类型的其他所有(byte,char,double,float,int,long,short等)基本类型,还有Object类型和泛型。
2. copyOf以及copyOfRange
复制指定数组,截取或填充(长度大于原数组时),使副本数组具有相应长度;将指定数组的一定范围复制到新数组。
3. equals和deepEquals
equals:两个参数均为数组,判断两个数组的每一个对应的元素是否相等,以此来判断数组是否相等。
deepEquals:针对数组中的元素还是数组的情况。
4. fill
用指定元素将数组的元素替换或者部分替换,给数组赋值。
5. hashCode和deepHashCode
hashCode: 计算一个数组的hashCode.
deepHashCode:针对数组中的元素还是数组的情况。
6. sort
对数组或者数组的一部分进行排序。适合除布尔类型的基本类型,还有Object类型(实现了Comparable接口),以及泛型(提供比较器Comparator)。
7. toString和deepToString
toString:返回数组的字符串形式。直接打印数组会打印数组的实体(例如[I@6406c7e这种形式),而不会打印数组的内容,这个时候就要用toString方法。
deepToString:针对数组中的元素还是数组的情况。
toString的实现:
//toString的经典实现
public static String myToString(int[] a) {
if (a == null)
return "null";
int iMax = a.length - 1;
if (iMax == -1)
return "[]";
StringBuilder b = new StringBuilder();
b.append('[');
for (int i = 0; ; i++) {//中间省略条件判断,提高了效率
b.append(a[i]);
if (i == iMax)
return b.append(']').toString();
b.append(", ");
}
}
- asList(重点)
返回一个受指定数组支持的固定大小的列表。(对返回列表的更改会“直接写”到数组)
简单来说,这个方法的用处就是将数组转为集合。
优点:可以使用集合的方法操作数组中的元素。
注意:
- 数组的长度是固定的,所以对于集合的增删方法是不可以使用的,否则会发生java.lang.UnsupportedOperationException异常。
- 如果数组中的元素是对象,那么转成集合的时候,直接将数组中的元素作为集合中的元素进行集合存储。如果数组中的元素是基本类型数值,那么会将该数组作为集合中的元素进行存储。
下面用代码来演示以上内容:
public class ArraysDemo {
public static void main(String[] args) {
demo_1();
demo_2();
}
private static void demo_2() {
/*
* 如果数组中的元素是对象,那么转成集合的时候,直接将数组中的元素作为集合中的元素进行集合存储。
* 如果数组中的元素是基本类型数值,那么会将该数组作为集合中的元素进行存储。
*
* */
int[] arr={23,32,12,45,61};
List<int[]> list=Arrays.asList(arr);
System.out.println(list);//[[I@5cb08ba7] 数组实体
System.out.println(list.size());//1 数组实体存进去了,只有一个元素
}
public static void demo_1() {
/*
* 重点:List asList(数组) 数组->集合
*
* 优势:可以使用集合的方法操作数组中的元素
* 注意:数组的长度是固定的,所以对于集合的增删方法是不可以使用的,
* 否则会发生java.lang.UnsupportedOperationException异常
* */
String[] arr1={"abc","kkk","zaza","moumou"};
boolean b=myContains(arr1, "kkk");
System.out.println(b);
List<String> list=Arrays.asList(arr1);
boolean bb=list.contains("kkk");
System.out.println("list contains:"+bb);
//list.add("hiahia");//java.lang.UnsupportedOperationException
}
//contains方法的实现原理
public static boolean myContains(String[] arr,String key){
for(int i=0;i<arr.length;i++){
if(arr[i].equals(key))
return true;
}
return false;
}
}
输出结果为:
true
list contains:true
[[I@4aa0b07b]
1
在demo_1方法中,将数组转换成了列表,并用列表的方法contains来判断是否数组里包含指定元素。
toArray
toArray是Collection接口(注意不是Collections工具类)中功能与Arrays工具类的asList方法相对的一个方法,它的功能是将集合转为数组。
将集合转为数组,可以对集合中的元素操作的方法进行限定,不允许对其进行增删。
演示代码:
public class ToArray {
public static void main(String[] args) {
/*
* 集合转数组
*
* 使用Collection接口中的toArray方法
*
* 集合转数组:可以对集合中的元素操作的方法进行限定,不允许对其进行增删。
*
* */
List<String> list=new ArrayList<String>();
list.add("abc1");
list.add("abc2");
list.add("abc3");
list.add("abc4");
/*
toArray方法需要传入一个指定类型的数组。
长度如何定义:
如果长度小于集合的size,那么该方法会创建一个同类型并和集合相同size的数组。
如果长度大于集合的size,那么该方法会使用指定的数组,存储集合中的元素。其他位置默认为null。
所以建议长度就指定为集合的size
* */
String[] arr1=list.toArray(new String[2]);
String[] arr2=list.toArray(new String[4]);
String[] arr3=list.toArray(new String[5]);
System.out.println(Arrays.toString(arr1));//[abc1, abc2, abc3, abc4]
System.out.println(Arrays.toString(arr2));//[abc1, abc2, abc3, abc4]
System.out.println(Arrays.toString(arr3));//[abc1, abc2, abc3, abc4, null]
}
}
jdk5.0集合框架的新特性
foreach语句
格式:
for(类型 变量:Collection集合|数组)
{
}
传统for语句和高级for语句的区别:
传统for可以完成对语句执行很多次,因为可以定义控制循环的增量和条件;
高级for是一种简化形式。它必须有被遍历的目标,该目标要么是数组,要么是Collection单列集合。
使用情景区别:
对于数组的变量如果仅仅是获取数组中的元素,可以使用高级for语句;
如果要对数组的角标进行操作建议使用传统for语句。
不可以直接用高级for语句遍历map集合,但是可以将map转成单列的set。
foreach语句代码演示:
public class ForEachDemo {
public static void main(String[] args) {
List<String> list =new ArrayList<String>();
list.add("abc1");
list.add("abc2");
list.add("abc3");
//遍历列表
for(String s:list){//只用于遍历和迭代 简化书写
System.out.println(s);
}
// Iterator<String> it=list.iterator();
// while(it.hasNext()){
// System.out.println(it.next());
// }
//遍历数组
int[] arr={3,4,6,8,1};
for(int i:arr){
System.out.println(i);
}
//遍历Map集合
//不可以直接用高级for语句遍历map集合,但是可以将map转成单列的set。
Map<Integer,String> map=new HashMap<Integer,String>();
map.put(2, "lily");
map.put(14, "ben");
map.put(6, "juice");
map.put(72, "milk");
for(Integer key:map.keySet()){
String value=map.get(key);
System.out.println(key+":"+value);
}
for(Map.Entry<Integer, String> me:map.entrySet()){
Integer key=me.getKey();
String value=me.getValue();
System.out.println(key+":"+value);
}
}
}
可变参数
可变参数适用于参数个数不确定,类型确定的情况,java把可变参数当做数组处理。
注意:可变参数必须位于参数列表的最后一项。
代码演示:
public class ParamterDemo {
public static void main(String[] args) {
int[] arr={4,5,6};
int sum1=add(arr);
System.out.println("sum1="+sum1);
int sum2=newAdd(4,5,6);
System.out.println("sum2="+sum2);
int sum3=newAdd(4,5,6,7,8);
System.out.println("sum3="+sum3);
}
/*
函数的可变参数
其实就是一个数组,但是接收的是数组的元素。
自动将这些元素封装成数组。简化了调用者的书写。
注意:可变参数类型,必须定义在参数列表的结尾。
* */
public static int newAdd(int... arr){
int sum=0;
for(int i=0;i<arr.length;i++){
sum+=arr[i];
}
return sum;
}
public static int add(int[] arr){
int sum=0;
for(int i=0;i<arr.length;i++){
sum+=arr[i];
}
return sum;
}
}
静态导入
要使用静态成员(方法和变量),必须给出提供这个静态成员的类。
使用静态导入可以使被导入类的静态成员在当前类直接可见,因此使用这些静态成员无需再给出他们的类名。
代码示例:
import java.util.ArrayList;
//import java.util.Collections;
import java.util.List;
import static java.util.Collections.*;
//import static java.util.Collections.sort;//静态导入,其实导入的是类中的静态成员
//import static java.util.Collections.max;
import static java.lang.System.*;
public class StaticImportDemo {
public static void main(String[] args) {
List<String> list=new ArrayList<String>();
list.add("nani");
list.add("sleepy");
list.add("haqian");
// System.out.println(list);
out.println(list);//静态导入了System类
// Collections.sort(list);
sort(list);//静态导入了Collections接口的所有类的静态成员
System.out.println(list);
String max=max(list);
System.out.println("max:"+max);
}
}