List接口
List list = new ArrayList(); // 线程不安全
List list = new Vector(); // 线程安全
List list = new LinkedList();
list.add("a"); // 在尾部插入 ArrayList -> 16ms LinkedList -> 31ms
list.add(0, "a"); // 在任意位置插入 ArrayList -> 1547ms LinkedList -> 0ms
list.remove(0); // 删除元素 ArrayList头部 -> 6203ms 中间3125ms 尾部16ms LinkedList头部15ms 中间8781ms 尾部16ms
遍历列表
// 方法1 ForEach操作 (用时63ms)
for (String s : list){
tmp = s;
}
// 方法2 迭代器 (用时47ms)
for(Iterator<String> it = list.iterator(); it.hasNext();){
tmp = it.next();
}
// 方法3 for循环 (用时31ms, 当为LinkedList时,用时无穷大)
for(int i = 0; i< list.size(); i++){
tmp = list.get(i);
}
Map接口
Map map = new HashMap(); // 随机排序
Map map = new LinkedHashMap(); // 进入顺序排序
Map map = new TreeMap(); // 固有顺序排序
TreeMap实例
public static class Student implements Comparable<Student>{
String name;
int scope;
public Student(String name, int s){
this.name = name;
this.scope = s;
}
// 这里是必需实现的,告诉TreeMap如何进行排序
@Override
public int compareTo(Student o){
if (o.scope<this.scope){
return 1;
} else if (o.scope>this.scope){
return -1;
}else{
return 0;
}
}
}
public static class StudentDetailInfo{
Student s;
public StudentDetailInfo(Student s){
this.s = s;
}
}
Map map = new TreeMap();
Student s1 = new Student("a", 70);
Student s2 = new Student("b", 50);
map.put(s1, new StudentDetailInfo(s1));
map.put(s2, new StudentDetailInfo(s2));
Map map1 = map.subMap(s1,s2); // 筛选出成绩介于s1与s2之间的学生
Map map2 = map.headMap(s1); // 筛选出成绩低于s1的学生
Map map2 = map.tailMap(s2); // 筛选出成绩高于s2的学生
Set接口
Set set = new HashSet();
Set set = new LinkedHashSet();
Set set = new TreeSet();
优化集合访问代码
int count = 0;
String s = null;
int colsize = this.elementCount; // 代替size()方法
for(int i= 0; i < colsize; i++){
if ((s=(String) elementData[i]).indexOf("north") != -1
|| (s.indexOf("west") != -1)
|| (s.indexOf("south") != -1)){
count++;
}
}
数组排序
Set<ProductAttributeMapStore> mapStore = ap.getProductAttributeMapStore();
List mapStoreList = new ArrayList(mapStore);
Collections.sort(mapStoreList, new Comparator<ProductAttributeMapStore>() {
public int compare(ProductAttributeMapStore o1, ProductAttributeMapStore o2) {
if (o1.getAddTime()!= null && o2.getAddTime()!=null){
return o1.getAddTime().compareTo(o2.getAddTime());
} else{
return 0;
}
}
});
遍历request.getAttributeNames()
Enumeration<String> en = request.getAttributeNames();
while(en.hasMoreElements()){
sb.append(StringUtil.reflect(request.getAttribute(en.nextElement())));
}
<c:forEach 遍历list中的map对象
<c:forEach items="${priceList}" var="price">
<c:forEach items="${price}" var="mp">
${mp.key} : ${mp.value}
</c:forEach>
</c:forEach>