日期:2014-05-20 浏览次数:20842 次
import org.apache.commons.lang.RandomStringUtils; public class Test { /** * @param args */ public static void main(String[] args) { List<String> codes = new ArrayList<String>(); int length = 10; String random = RandomStringUtils.randomAlphanumeric(8); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); String date = sdf.format(new Date()); boolean isExist = false; int loop = 0; do { loop++; isExist = false; for (int i = 0; i < codes.size(); i++) { if (random.equals(codes.get(i))) { isExist = true; break; } } random = RandomStringUtils.randomAlphanumeric(8); codes.add(date + random); } while (isExist || loop < length); for (int i = 0; i < codes.size(); i++) { System.out.println(codes.get(i)); } } }
------解决方案--------------------
改了一下,不知道还有没有问题。。。
List<String> codes = new ArrayList<String>(); int length = 10; boolean isExist = false; String random = null; SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); String date = sdf.format(new Date()); do { random = RandomStringUtils.randomAlphanumeric(8); isExist = false; for (int i = 0; i < codes.size(); i++) { if (random.equals(codes.get(i))) { isExist = true; break; } } if (!isExist) { codes.add(date + random); } } while (isExist || codes.size() < length); for (int i = 0; i < codes.size(); i++) { System.out.println(codes.get(i)); }
------解决方案--------------------
用oracle 序列
------解决方案--------------------
return java.util.UUID.randomUUID.toString().replaceAll("-", "");
------解决方案--------------------
用UUID自动生成32位字符更好
------解决方案--------------------