Usando ArrayList no J2ME

12 respostas
Norxs

Uma contribuição para quem tiver o interesse ou para sente dificuldade em trabalhar com listas dinâmicas ... clássica transição do J2EE ou mesmo J2SE para o J2ME ... ehehehe

public class ArrayList {
	private Object[] storedObjects;
	private int growthFactor;
	private int size;
	
	public ArrayList() {
		this( 10, 75 );
	}
	
	public ArrayList( int initialCapacity ) {
		this( initialCapacity, 75 );
	}

	public ArrayList( int initialCapacity, int growthFactor ) {
		this.storedObjects = new Object[ initialCapacity ];
		this.growthFactor = growthFactor;
	}
	
	public int size() {
		return this.size;
	}
	
	public boolean contains( Object element ) {
	
		if (element == null) {
			throw new IllegalArgumentException( "ArrayList cannot contain a null element.");
		}
		for (int i = 0; i < this.size; i++) {
			Object object = this.storedObjects[i];
			if ( object.equals( element ) ) {
				return true;
			}
		}
		return false;
	}
	
	public int indexOf(Object element) {
		if (element == null) {
			throw new IllegalArgumentException( "ArrayList cannot contain a null element.");
		}
		for (int i = 0; i < this.size; i++) {
			Object object = this.storedObjects[i];
			if ( object.equals( element ) ) {
				return i;
			}
		}
		return -1;
	}
	
	public Object get( int index ) {
		if (index < 0 || index >= this.size ) {
			throw new IndexOutOfBoundsException("the index [" + index + "] is not valid for this list with the size [" + this.size + "].");
		}
		return this.storedObjects[ index ];
	}

	public Object remove( int index ) {
		if (index < 0 || index >= this.size ) {
			throw new IndexOutOfBoundsException("the index [" + index + "] is not valid for this list with the size [" + this.size + "].");
		}
		Object removed = this.storedObjects[ index ];
		for (int i = index+1; i < this.size; i++) {
			this.storedObjects[ i-1 ] = this.storedObjects[ i ];
		}
		this.size--;
		this.storedObjects[ this.size ] = null;
		return removed;
	}
	
	public boolean remove( Object element ) {
		if (element == null) {
			throw new IllegalArgumentException( "ArrayList cannot contain null.");
		}
		int index = -1;
		for (int i = 0; i < this.size; i++) {
			Object object = this.storedObjects[i];
			if ( object.equals( element ) ) {
				index = i;
				break;
			}
		}
		if (index == -1) {
			return false;
		}
		for (int i = index+1; i < this.size; i++) {
			this.storedObjects[ i-1 ] = this.storedObjects[ i ];
		}
		this.size--;
		this.storedObjects[ this.size ] = null;
		return true; 
	}

	public void clear() {
		for (int i = 0; i < this.size; i++) {
			this.storedObjects[i] = null;
		}
		this.size = 0;
	}

	public void add( Object element) {
		if (element == null) {
			throw new IllegalArgumentException( "ArrayList cannot contain null.");
		}
		if (this.size >= this.storedObjects.length) {
			increaseCapacity();
		}
		this.storedObjects[ this.size ] = element;
		this.size++;
	}

	public void add( int index, Object element ) {
		if (element == null) {
			throw new IllegalArgumentException( "ArrayList cannot contain null.");
		}
		if (index < 0 || index > this.size ) {
			throw new IndexOutOfBoundsException("the index [" + index + "] is not valid for this list with the size [" + this.size + "].");
		}
		if (this.size >= this.storedObjects.length) {
			increaseCapacity();
		}
		// shift all following elements one position to the back:
		for (int i = this.size; i > index; i--) {
			this.storedObjects[i] = this.storedObjects[ i-1 ];
		} 
		// insert the given element:
		this.storedObjects[ index ] = element;
		this.size++;
	}

	public Object set( int index, Object element ) {
		if (index < 0 || index >= this.size ) {
			throw new IndexOutOfBoundsException("the index [" + index + "] is not valid for this list with the size [" + this.size + "].");
		}
		Object replaced = this.storedObjects[ index ];
		this.storedObjects[ index ] = element;
		return replaced;
	}

	public String toString() {
		StringBuffer buffer = new StringBuffer( this.size * 23 );
		buffer.append( super.toString() ).append( "{\n" );
		for (int i = 0; i < this.size; i++) {
			buffer.append( this.storedObjects[i] );
			buffer.append('\n');
		}
		buffer.append('}');
		return buffer.toString();
	}

	public Object[] toArray() {
		Object[] copy = new Object[ this.size ];
		System.arraycopy( this.storedObjects, 0, copy, 0, this.size );
		return copy;
	}

	public Object[] toArray( Object[] target ) {
		System.arraycopy( this.storedObjects, 0, target, 0, this.size );
		return target;
	}

	public void trimToSize() {
		if (this.storedObjects.length != this.size ) {
			Object[] newStore = new Object[ this.size ];
			System.arraycopy( this.storedObjects, 0, newStore, 0, this.size );
			this.storedObjects = newStore;
		}
	}

	private void increaseCapacity() {
		int currentCapacity = this.storedObjects.length;
		int newCapacity = currentCapacity + ((currentCapacity * this.growthFactor) / 100);
		if (newCapacity == currentCapacity ) {
			newCapacity++;
		}
		Object[] newStore = new Object[ newCapacity ];
		System.arraycopy( this.storedObjects, 0, newStore, 0, this.size );
		this.storedObjects = newStore;
	}

	public Object[] getInternalArray() {
		return this.storedObjects;
	}
}

12 Respostas

Raff

só falto ele implementar a interface List huahuuhahau

Norxs

essa é a parte mais fácil :smiley:

adrian.gois

Obrigado pela contribuição. FOi muito util pra mim num projeto que estou fazendo. Mas nao pesa a aplicação nao?

malves_info

Com certeza pesa!.. mas muito boa a implementação.

Norxs

depende de como você utilizar …

no meu caso eu uso com poucos elementos … não notei nenhuma perda de processamento ou algo do tipo …
mas como o ArrayList ai trabalha em cima de array … é muita pouca diferença de utilizar um array[] normal … num sei se deu pra entender

trainpotting

Blz Pessoal,

sou novato no assunto mas como o codigo recebeu elogios resta saber c roda bem em midp s/ o risco de tornar pesado como mencionado.
no caso o device é um i876 motorola.

é possivel usar este codigo para numa Thread com intervalo de leitura de 50s continuamente?
c der pau na transmissao como armazeno isto no device ?
vi alguma coisa rapida sobre rms.
é isso mesmo ou tem uma solução melhor?

c pudessem comentar o codigo do Norxs em portugues para entender como armazenar o os dados (xml) abaixo, agradeceria muito.

na verdade o vai ler e enviar dados puros para um servlet via getParameter(); e o segundo armazena em banco.
outro servlet faz a consulta ao banco e retorna um xml como o mysql exportou neste exemplo abaixo.

Ao invocar o servlet o banco ja poderá estar configurado para esta saida em xml? isto porque a camada final vai requisitar xml ao servlet e nao faz sentido ficar gerando xml com ou.println();, eu acho :wink:

desculpa ai pessoal, mas é tanta duvida,que parece código espaguetti … :smiley:

obrigado

abs

Norxs

como exatamente tu quer usar? …

tu pode usar o ArrayList normalmente como vc usa numa aplicação J2SE ou J2EE … mas obvio que tu num vai me lota uma lista num dispositivo que vc saiba que tenha pouca memória.

essa sua aplicação é para se comunicar com servlet né? … eu usei … e não deu problema!

trainpotting

Fala Norxs.

blz kra?

quero inserir os dados acima mas sem as tags xml que fica a cargo do servlet.
nao vou armazenar muita coisa, na verdade só quando cair a rede (que metodo?) e o midlet não ficar sem fazer nada :slight_smile:
voltando a rede ele envia os dados armazenados.
O arroz com feijão é fazer a leitura a cada 5 (talvez 10) segundos numa thread configuravel e enviar os dados pro servlet.

meuI876_Motorola.updateMessage("lendo dados....na verdade nem vai ter  interface com o usuario pois é uma aplicação oculta para liberar o device para outras coisas. minha duvida é que hj quando rodo um midlet, musica por exemplo, e up outro midlet (qualquer um) a musica para e fica em standby. quando o ultimo midlet para, tenho que up de novo o de musica.
quando uso a opção de "ocultar aplicação" (é nativa do hardware?) , até posso continuar escutando musica mas so tenho acesso a aplicativos nativos do device. outro midlet?.....100 chance :|");
                Thread.currentThread().sleep(50); // cinco segundos

abs

Norxs
ArrayList list = new ArrayList();
try{
         \\envia para o servlet
} catch(IOException ioe){
         \\salva o que tu quer
         list.add(new NomedaClasse(id, telefone, latitude, longitude, altura ...));
}

ou se preferir poem Exception em vez de IOException

trainpotting

santo portuga!!!
valew

abs

rampazzo1989

ahee galera! essa ArrayList não pode ser tipada neh… tipo ArrayList, pelo q entendi.

P

Não, não pode e quer saber, é até bom !
Abro tranquilamente mão da verificação em tempo de compilação para obter clareza no código. J2ME não é bicho de sete-cabeças e podemos sem dúvida conviver sem esta ‘funcionalidade’ da linguagem.

Criado 11 de junho de 2008
Ultima resposta 4 de out. de 2010
Respostas 12
Participantes 7