目录
Collection的一些常用方法说明
代码演示:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
public class Demo {
public static void main(String[] args) {
Collection<String> collection = new ArrayList<>();
collection.add("hello");
collection.add("hello2");
System.out.println(collection); //在AbstractCollection中有toString方法
collection.clear();//clear将每个元素都置为null
System.out.println("=================================");
System.out.println(collection);
System.out.println(collection.isEmpty());
Object[] objects = collection.toArray();
System.out.println(Arrays.toString(objects));
String[] strs = (String[]) collection.toArray();//java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;
//内部元素没有进行强制类型转换
collection.add("hello");
collection.add("hello2");
System.out.println(collection.remove("hello"));
System.out.println(collection);
System.out.println(collection.size());
}
}
执行结果如下
[hello, hello2]
=================================
[]
true
[]java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;
true
[hello2]
1
注意:
实际上,在java中,
Object
是所有class类型
的根
,数组
当然也是一种class类型
,因此Object[]
类型和String[]
类型都是Object
类型的子类型
但是对于Object[]
类型和String[]
类型,二者同为数组类型,可他们之间并没有
什么父子
关系,而是平级
的关系
正是因为很多同学误以为Object[]
应该是String[]
的父类型
,才会随手写出导致程序运行时ClassCastException
异常
Map的一些常用方法说明
代码演示:
public class TestDemo {
public static void main(String[] args) {
Map<String,String> map = new HashMap<>();
map.put("及时雨","宋江");
map.put("国名女神","高圆圆");//如果key的值相同,value会被覆盖
map.put(null,null);//HashMap不会报错,
System.out.println(map);
String ret = map.get("及时雨2");//有返回value值,没有返回null
System.out.println(ret);
ret =map.getOrDefault("及时雨2","你好");
System.out.println(ret);
System.out.println("======================================");
boolean flg = map.containsKey("国民女神");
System.out.println(flg);
flg = map.containsValue("高圆圆");
System.out.println(flg);
System.out.println("===================================");
Set<String> set = map.keySet();//获取key
System.out.println(set);
System.out.println("======================================");
Set<Map.Entry<String,String>> entrySet=map.entrySet();
for (Map.Entry<String,String> entry:entrySet) {
System.out.println(entry.getKey()+" "+entry.getValue());
}
System.out.println("=================================");
System.out.println(map.isEmpty());
System.out.println(map.remove("及时雨"));
System.out.println(map.size());
System.out.println(map);
}
}
代码执行结果:
{null=null, 国名女神=高圆圆, 及时雨=宋江}
null
你好
======================================
false
true
===================================
[null, 国名女神, 及时雨]
======================================
null null
国名女神 高圆圆
及时雨 宋江
=================================
false
宋江
2
{null=null, 国名女神=高圆圆}
- 在Map中插入键值对时,key不能为空,否则就会抛NullPointerException异常,但是value可以为空。new HashMap不会。
- 推荐使用HashMap