开发者

Adding and removing elements efficiently from Collection object

Below coding is the working sample,but still i am not happy with this code with related to performancewise.Please have a look and let me know if any better approach is there.Thanks in advance.

Adding items to the arraylist object

String resultItems[] = paging.getMoveLeftArray().split(",");
String fields[]={"id","name","name1"};

leftObj=new ArrayList();

for(int i=0;i<resultItems.length;i++){

//below line mea

TestVO bean=new TestVO();

String resultItem = resultItems[i];

String idANDname[] = resu开发者_运维知识库ltItem.split("@");

String id = idANDname[0];

// name or id should not contain "-"

String name[] = idANDname[1].split("-");

//values and fileds are always having same length

for(int j=0;j<name.length;j++) {

PropertyUtils.setProperty(bean, fields[j], name[j]);

}

leftObj.add(bean);

}

Removing items from the arraylist object:availableList contains all the TestVO objects:

String []removeArray=paging.getMoveRightArray().split(",");

tempList=new CopyOnWriteArrayList();

newTempList=new CopyOnWriteArrayList();

for(int i=0;i<availableList.size();i++){

boolean flag = false;

TestVO tempObj = (TestVO )availableList.get(i);

int id =(Integer)tempObj.getId();

// System.out.println("id value"+id);

// availableList.get(i).getClass().getField(name);

for(int j=0;j<removeArray.length;j++){

String resultItem = removeArray[j];

String idandname[] = resultItem.split("@");

for(int k=0;k<idandname.length;k++){

String ids[]=idandname[0].split("-");

if(id==Integer.parseInt(ids[0])){

flag = true;

break;

}

}

}

if(flag){

tempList.add(tempObj);

}

else{

newTempList.add(tempObj);

}


You could try

List<TestVO> leftObj=new ArrayList<TestVO>();
for(String resultItem : paging.getMoveLeftArray().split(",")) {
     String[] names = resultItem.split("@")[0].split("-");
     leftObj.add(new TestOV(names[0], names[1], names[2]));
}

Add a constructor to TestOV which sets the three fields.

Assuming the first '-' is before the first '@', getId() should be an int value so you don't need to cast it. CopyOnWriteArrayList is only required if you intend to read and write from different threads at the same time.

Set<Integer> removeIds = new HashSet();
for(String resultItem: paging.getMoveRightArray().split(","))
     removeIds.add(Integer.parseInt(resultItem.split("-")[0]));
List<TestOV> tempList=new ArrayList(), newTempList=new ArrayList();
for(TestVO tempVO: availableList)
   (removeIds.contains(tempVO.getId()) ? tempList : newTempList).add(tempVO);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜