ID generator

//Actualizacion: 15/04/16: //Dos modos distintos para generar IDs. //Autor: Bregy Malpartida Ramos import java.util.Random; //PRIMER MODO; class Id { private int longitud; private int decoder; private char[] idArray; public Id(int longitud){ this.longitud = longitud; } public void generarId(int longitud){ boolean flagIntOrString = true; idArray = new char[longitud]; for(int i=0;i<longitud;i++) { Random num = new Random(); if (num.nextDouble() > 0.5) { int c = (int) ((num.nextDouble() * 95) + 97); char cc = (char) c; idArray[i] = cc; }else{ char c = (char) ((num.nextDouble() * 10) + 48); idArray[i] = c; } } } } //SEGUNDO MODO; class ID{ private int longitud; private char[] id; private char[] asciiNumeros = {'0','1','2','3','4','5','6','7','8','9',}; private char[] asciiLetras = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'}; public ID(int longitud){ this.longitud = longitud; } public String generarId(){ id = new char[this.longitud]; Random rn = new Random(); for(int i=0;i<this.longitud;i++){ int elementoNumero = (int)(rn.nextDouble()*asciiNumeros.length); int elementoLetra = (int)(rn.nextDouble()*asciiLetras.length); boolean tipoElemento = rn.nextBoolean(); id[i] = tipoElemento?asciiLetras[elementoLetra]:asciiNumeros[elementoNumero]; } String cadena = new String(id); return cadena; } } //Ejemplo de uso: // //ID id = new ID(20); //System.out.println(id.generarId());
It's very simple, is a id generator. A number combined with characters array. Mostly used for keys and unique IDs.

2 Responses

It's a very cool homemade id gen :). In java you can use UUID either https://docs.oracle.com/javase/7/docs/api/java/util/UUID.html if the project permits.
Just a little ideia in code pattern matter, I'd just change the constructor to private e make generateId a static factory (Bloch, Effective Java).
i.e.
public static Id generateId(int logitud){
Id id = new Id(longitud);
id.idArray = new String[logintud];
....
return id;
}
this helps to build more semantic sentences :D i.e. Id.generateId(10);
Just an ideia (I like to share and discuss code pattern stuff hehehe):D
Best regards!
Hi Kim :). Thanks, now it's updated and tested. And, yes, this code your help to make semantic sentences. I'm using for create UNIQUE id for database with 500 registered persons. Regards!

Write a comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.