一.map的使用
TreeMap 默认是排序的
HashMap访问速度更加快,但不排序
遍历方法
Map<String,String> map = new HashMap<>();
map.put("ID1", "小明");
if(map.containsKey("ID1")) {
}
// 遍历方式1
Iterator<String> it = map.keySet().iterator();
while(it.hasNext()){
String cId = it.next();
String cName = map.get(cId);
}
遍历速度最快的方式:
// 推荐,尤其是容量大时
System.out.println("通过Map.entrySet遍历key和value");
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
}
二. ArrayList和数组的相互转换
// List转换为Array可以这样处理:
ArrayList<String> list=new ArrayList<String>();
list.add("hello");
String[] strArr = new String[list.size()];
list.toArray(strArr);
// 反过来,如果要将数组转成List如下:
String[] s = {"a","b","c"};
List list = java.util.Arrays.asList(s);
三. foreach遍历时,移除元素会报错
//这样子就不会报错
Iterator<Course> it = courseList.iterator();
while (it.hasNext()){
Course c = it.next();
if (list.contains(c)){
it.remove();
}
}
参考: https://blog.youkuaiyun.com/bimuyulaila/article/details/52088124
另外:
for (int i=0;i<arrayList.size();i++){
if (arrayList.get(i)==false)
arrayList.remove(i);
}
//这样子是错误的,因为只会移除一半的元素
应该修改为:
//倒过来遍历
for (int i=arrayList.size()-1;i>=0;i--){
if (arrayList.get(i)==false)
arrayList.remove(i);
}