您的位置:首页 > 其它

心得总结<一>

2018-02-26 17:48 288 查看

枚举类:

package com.aliyun.sop.myEnum;

import java.util.HashMap;
import java.util.Map;

public enum MyProductEnum {

APPLE(001,"苹果","apple"),

ORANGE(002,"橘子","orange"),

BANANA(003,"香蕉","banana");

private Integer code;

private String name;

private String enName;

private static final Map<Integer,MyProductEnum> map = new HashMap<>();

static {
for (MyProductEnum product :MyProductEnum.values()){
map.put(product.getCode(),product);
}
}

private MyProductEnum(Integer code, String name, String enName) {
this.code = code;
this.name = name;
this.enName = enName;
}

public static MyProductEnum getEnum(Integer code){
return map.get(code);
}

public void setCode(Integer code) {
this.code = code;
}

public void setName(String name) {
this.name = name;
}

public void setEnName(String enName) {
this.enName = enName;
}

public Integer getCode() {
return code;
}

public String getName() {
return name;
}

public String getEnName() {
return enName;
}
}


遍历集合并把符合条件的从集合里删除。

@Test
public void testListRemove(){
List<Integer> list = new ArrayList<>();
list.add(3);
list.add(10);
list.add(5);
list.add(4);
list.add(15);
Iterator<Integer> it = list.iterator();
//使用迭代器,同时移除时使用it.remove();
while(it.hasNext()){
Integer next = it.next();
if(next % 5 == 0){
/* ERROR:删除后集合下标会发生变化
* list.remove(next);*/
it.remove();
}
}
/* ERROR:删除后集合下标会发生变化
* for (int i = 0; i < list.size(); i++) {
if(list.get(i) % 5 == 0){
list.remove(i);
}
}*/
/* ERROR:可能会抛异常java.util.ConcurrentModificationException
* for (Integer i : list) {
if(list.get(i) % 5 == 0){
list.remove(i);
}
}*/
System.out.println(list.toString());
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: