#include <stdio.h>
#define SIZE 10
int main() {
int arr[SIZE] = {1,2,45,2,1,8,-3,0,2,4};
int tmp[SIZE];
int count = 0;
int diff;
int i, j;
for (i=0; i<SIZE; i++) {
diff = 1;
for (j=0; j<count; j++) {
if (arr[i] == tmp[j]) {
diff = 0;
break;
}
}
if (diff)
tmp[count++] = arr[i];
}
for (i=0; i<count; i++)
printf("%d ", tmp[i]);
printf("\ncount: %d\n", count);
}
在項目開發過程中遇到需要統計ArrayList中 對象的userId不相同的 對象個數,ArrayList中的數據在查詢時,已按照userId 升序排列,所以仿照上述C的寫法如下:
int count = 0; boolean flag = true; List<UserLotteryVO> listVO = new ArrayList<UserLotteryVO>(); List<UserLotteryVO> tempListVO= new ArrayList<UserLotteryVO>(); List<UserLottery> listEntity = userLotteryDao.SearchUserLotteryByDrawNum(drawNum); for(UserLottery ul : listEntity ) { listVO.add(this.convertToUserLotteryHistoryVO(ul)); } for(UserLotteryVO vo : listVO) { flag = true; for(int i = 0; i < count; i++) { if(i >= count) { break; } if(tempListVO.size() > 0 && (vo.getUserId() == tempListVO.get(i).getUserId())) { flag = false; break; } } if(flag) { tempListVO.add(vo); count++; } } return count;