0% acharam este documento útil (0 voto)
3K visualizações

Class Java - util.ArrayList

Enviado por

Xavier Joaquim
Direitos autorais
© © All Rights Reserved
Formatos disponíveis
Baixe no formato PDF, TXT ou leia on-line no Scribd
0% acharam este documento útil (0 voto)
3K visualizações

Class Java - util.ArrayList

Enviado por

Xavier Joaquim
Direitos autorais
© © All Rights Reserved
Formatos disponíveis
Baixe no formato PDF, TXT ou leia on-line no Scribd
Você está na página 1/ 9

Visão geral 

Pacote   Aula  Usar  Árvore  Descontinuada  Índice  Ajuda  Plataforma Java 1.2
Beta 4
 AULA ANTERIOR AULA    PRÓXIMA QUADROS   SEM QUADROS

RESUMO: INTERIOR | CAMPO  | CONSTR  | MÉTODO DETALHE: CAMPO | CONSTR  | MÉTODO

Classe java.util.ArrayList
java.lang.Object
|
+-- java.util.AbstractCollection
|
+-- java.util.AbstractList
|
+-- java.util.ArrayList

classe pública ArrayList


estende AbstractList
implementa List , Cloneable , Serializable

Implementação de array redimensionável da interface List. Implementa todas as operações


List opcionais e permite todos os elementos, incluindo null. Além de implementar a
interface List, ArrayList fornece métodos para manipular o tamanho do array que é usado
internamente para armazenar a List. (ArrayList é aproximadamente equivalente a Vector,
exceto que não está sincronizado.)

As operações size, isEmpty, get, set, iterator e listIterator são executadas em tempo
constante. A operação add() é executada em tempo constante, a menos que faça com que
ArrayList exceda sua capacidade, caso em que é executada em tempo linear. Todas as
outras operações são executadas em tempo linear (grosso modo). O fator constante é baixo
em comparação com o de LinkedList.

Cada ArrayList tem uma capacidade . O capacityé o tamanho da matriz usada para
armazenar os elementos na lista. É sempre pelo menos tão grande quanto o tamanho da
lista. À medida que os elementos são adicionados a um ArrayList, sua capacidade cresce
automaticamente. Os detalhes da política de crescimento não são especificados além do fato
de que adicionar um elemento a uma ArrayList tem custo amortizado constante , ou seja,
adicionar n elementos requer tempo O(n). Um aplicativo pode aumentar a capacidade de
um ArrayList antes de adicionar um grande número de componentes usando a operação
ensureCapacity . Isso pode reduzir a quantidade de realocação incremental.

Observe que essa implementação não é sincronizada. Se vários threads acessarem um


ArrayList simultaneamente e pelo menos um dos threads modificar o ArrayList
estruturalmente, ele deverá ser sincronizado externamente. (Uma modificação estrutural é
qualquer operação que adiciona ou exclui um ou mais elementos, ou redimensiona
explicitamente a matriz de apoio; simplesmente definir o valor de um elemento não é uma
modificação estrutural.) Isso geralmente é feito sincronizando em algum objeto que
encapsula naturalmente o ArrayList. Se tal objeto não existir, o ArrayList deve ser
"empacotado" usando o método Collections.synchronizedList. Isso é feito melhor no
momento da criação, para evitar acesso não sincronizado acidental ao ArrayList:
List list = Collections.synchronizedList(new ArrayList(...));

Os Iterators retornados pelos métodos iterator e listIterator de ArrayList são fail-fast : se o


ArrayList for modificado estruturalmente a qualquer momento após a criação do Iterator,
de qualquer maneira, exceto por meio dos próprios métodos remove ou add do Iterator, o
Iterator lançará uma ConcurrentModificationException. Assim, diante de modificações
simultâneas, o Iterator falha de forma rápida e limpa, em vez de arriscar um
comportamento arbitrário e não determinístico em um momento indeterminado no futuro.

Desde a:
JDK1.2
Veja também:
Collection, List, LinkedList, Vector, Collections.synchronizedList(List), Forma
serializada

Campos herdados da classe java.util. AbstractList


modCount
 
Resumo do Construtor
ArrayList ()
          Constrói um ArrayList vazio.
ArrayList ( Collection  c)
          Constrói um ArrayList contendo os elementos da Collection especificada, na ordem
em que são retornados pelo iterador da Collection.
ArrayList (int initialCapacity)
          Constrói um ArrayList vazio com a capacidade inicial especificada.
 
Resumo do método
 vazio add (índice int, elemento Object  )
          Insere o elemento especificado na posição especificada neste ArrayList.
 boleano add ( Object  o)
          Acrescenta o elemento especificado ao final deste ArrayList.
 boleano addAll ( Coleção  c)
          Acrescenta todos os elementos na Coleção especificada ao final desta
ArrayList, na ordem em que são retornados pelo Iterador da Coleção especificada.
 boleano addAll (índice int, Coleção  c)
          Insere todos os elementos da Coleção especificada nesta ArrayList,
começando na posição especificada.
 vazio clear ()
          Remove todos os elementos deste ArrayList.
 Objeto clone ()
          Retorna uma cópia rasa deste ArrayList.
 boleano contém ( Object  elem)
          Retorna verdadeiro se este ArrayList contiver o elemento especificado.
 vazio assegurarCapacity (int minCapacity) Aumenta
          a capacidade deste ArrayList, se necessário, para garantir que ele possa
conter pelo menos o número de componentes especificados pelo argumento de
capacidade mínima.
 Objeto get (índice int)
          Retorna o elemento na posição especificada neste ArrayList.
 int indexOf ( Object  elem)
          Procura a primeira ocorrência do argumento fornecido, testando a igualdade
usando oequalsmétodo.
 boleano isEmpty ()
          Testa se este ArrayList não possui componentes.
 int lastIndexOf ( Object  elem)
          Retorna o índice da última ocorrência do objeto especificado nesta ArrayList.
 Objeto remove (índice int)
          Remove o elemento na posição especificada neste ArrayList.
 Objeto set (índice int, elemento Object  )
          Substitui o elemento na posição especificada nesta ArrayList pelo elemento
especificado.
 int size ()
          Retorna o número de componentes neste ArrayList.
 Objeto toArray ()
[]           Retorna um array contendo todos os elementos neste ArrayList na ordem
correta.
 Objeto toArray ( Object [] a)
[]           Retorna um array contendo todos os elementos neste ArrayList na ordem
correta.
 vazio trimToSize ()
          a capacidade deste ArrayList para ser o tamanho atual do ArrayList.
 
Métodos herdados da classe java.util. AbstractList
equals , hashCode , iterator , listIterator , listIterator , subList
 
Métodos herdados da classe java.util. AbstractCollection
contémAll , remove , removeAll , retémAll , toString
 
Métodos herdados da classe java.lang. Objeto
finalize , getClass , notifique , notifyAll , espere , espere , espere
 

Detalhe do Construtor
ArrayList
public ArrayList (int initialCapacity)

Constrói um ArrayList vazio com a capacidade inicial especificada.

Parâmetros:
initialCapacity - a capacidade inicial do ArrayList.

ArrayList
public ArrayList ()

Constrói um ArrayList vazio.

ArrayList
public ArrayList ( Coleção  c)

Constrói um ArrayList contendo os elementos da Coleção especificada, na ordem em


que são retornados pelo iterador da Coleção. O ArrayList tem capacidade inicial de
110% do tamanho da Collection especificada.

Detalhes do Método
trimToSize
public void trimToSize ()

Ajusta a capacidade deste ArrayList para o tamanho atual do ArrayList. Um aplicativo


pode usar essa operação para minimizar o armazenamento de um ArrayList.

garantirCapacidade
public void garantirCapacidade (int minCapacity )

Aumenta a capacidade deste ArrayList, se necessário, para garantir que ele possa
conter pelo menos o número de componentes especificados pelo argumento de
capacidade mínima.

Parâmetros:
minCapacity - a capacidade mínima desejada.

Tamanho
público int tamanho ()

Retorna o número de componentes neste ArrayList.

Especificado por:
tamanho na lista de interface
Retorna:
o número de componentes neste ArrayList.
Substitui:
tamanho na classe AbstractCollection

está vazia
público booleano isEmpty ()

Testa se este ArrayList não possui componentes.

Especificado por:
isEmpty na lista de interfaces
Retorna:
truese este ArrayList não tiver componentes; falsepor outro lado.
Substitui:
isEmpty na classe AbstractCollection

contém
public boolean contém ( objeto  elem)

Retorna verdadeiro se este ArrayList contiver o elemento especificado.

Especificado por:
contém na lista de interface
Parâmetros:
o - elemento cuja presença nesta Lista será testada.
Substitui:
contém na classe AbstractCollection

índice de
public int indexOf (  Elem do objeto )

Procura a primeira ocorrência do argumento fornecido, testando a igualdade usando o


equalsmétodo.

Especificado por:
indexOf na lista de interfaces
Parâmetros:
elem - um objeto.
Retorna:
o índice da primeira ocorrência do argumento neste ArrayList; retorna -1se o
objeto não for encontrado.
Substitui:
indexOf na classe AbstractList
Veja também:
Object.equals(Object)

lastIndexOf
public int lastIndexOf ( Object  elem)

Retorna o índice da última ocorrência do objeto especificado neste ArrayList.

Especificado por:
lastIndexOf na lista de interfaces
Parâmetros:
elem - o componente desejado.
Retorna:
o índice da última ocorrência do objeto especificado neste ArrayList; retorna -1 se
o objeto não for encontrado.
Substitui:
lastIndexOf in class AbstractList

clone
public Object clone()

Returns a shallow copy of this ArrayList. (The elements themselves are not copied.)

Returns:
a clone of this ArrayList.
Overrides:
clone in class Object

toArray
public Object[] toArray()

Returns an array containing all of the elements in this ArrayList in the correct order.

Specified by:
toArray in interface List
Returns:
an array containing all of the elements in this ArrayList in the correct order.
Overrides:
toArray in class AbstractCollection

toArray
public Object[] toArray(Object[] a)

Returns an array containing all of the elements in this ArrayList in the correct order.
The runtime type of the returned array is that of the specified array. If the ArrayList
fits in the specified array, it is returned therein. Otherwise, a new array is allocated
with the runtime type of the specified array and the size of this ArrayList.

If the ArrayList fits in the specified array with room to spare (i.e., the array has more
elements than the ArrayList), the element in the array immediately following the end
of the collection is set to null. This is useful in determining the length of the ArrayList
only if the caller knows that the ArrayList does not contain any null elements.

Specified by:
toArray in interface List
Parameters:
a - the array into which the elements of the ArrayList are to be stored, if it is big
enough; otherwise, a new array of the same runtime type is allocated for this
purpose.
Returns:
an array containing the elements of the ArrayList.
Throws:
ArrayStoreException - the runtime type of a is not a supertype of the runtime
type of every element in this ArrayList.
Overrides:
toArray in class AbstractCollection

get
public Object get(int index)

Returns the element at the specified position in this ArrayList.

Specified by:
get in interface List
Parameters:
index - index of element to return.
Returns:
the element at the specified position in this ArrayList.
Throws:
IndexOutOfBoundsException - index is out of range (index < 0 || index >= size()).
Overrides:
get in class AbstractList

set
public Object set(int index,
Object element)

Replaces the element at the specified position in this ArrayList with the specified
element.

Specified by:
set in interface List
Parameters:
index - index of element to replace.
element - element to be stored at the specified position.
Returns:
the element previously at the specified position.
Throws:
IndexOutOfBoundsException - index out of range (index < 0 || index >= size()).
Overrides:
set in class AbstractList

add
public boolean add(Object o)

Appends the specified element to the end of this ArrayList.

Specified by:
add in interface List
Parameters:
o - element to be appended to this ArrayList.
Returns:
true (as per the general contract of Collection.add).
Overrides:
add in class AbstractList

add
public void add(int index,
Object element)

Inserts the specified element at the specified position in this ArrayList. Shifts the
element currently at that position (if any) and any subsequent elements to the right
(adds one to their indices).

Specified by:
add in interface List
Parameters:
index - index at which the specified element is to be inserted.
element - element to be inserted.
Throws:
IndexOutOfBoundsException - index is out of range (index < 0 || index > size()).
Overrides:
add in class AbstractList

remove
public Object remove(int index)

Removes the element at the specified position in this ArrayList. Shifts any subsequent
elements to the left (subtracts one from their indices).

Specified by:
remove in interface List
Parameters:
index - the index of the element to removed.
Returns:
the element that was removed from the ArrayList.
Throws:
IndexOutOfBoundsException - index out of range (index < 0 || index >= size()).
Overrides:
remove in class AbstractList

clear
public void clear()

Removes all of the elements from this ArrayList. The ArrayList will be empty after this
call returns.

Specified by:
clear in interface List
Overrides:
clear in class AbstractCollection
addAll
public boolean addAll(Collection c)

Appends all of the elements in the specified Collection to the end of this this ArrayList,
in the order that they are returned by the specified Collection's Iterator. The behavior
of this operation is undefined if the specified Collection is modified while the
operation is in progress. (This implies that the behavior of this call is undefined if the
the specified Collection is this ArrayList, and this ArrayList is nonempty.)

Specified by:
addAll in interface List
Parameters:
index - index at which to insert first element from the specified collection.
c - elements to be inserted into this ArrayList.
Throws:
IndexOutOfBoundsException - index out of range (index < 0 || index > size()).
Overrides:
addAll in class AbstractCollection

addAll
public boolean addAll(int index,
Collection c)

Inserts all of the elements in the specified Collection into this ArrayList, starting at the
specified position. Shifts the element currently at that position (if any) and any
subsequent elements to the right (increases their indices). The new elements will
appear in the ArrayList in the order that they are returned by the specified Collection's
iterator.

Specified by:
addAll in interface List
Parameters:
index - index at which to insert first element from the specified collection.
c - elements to be inserted into this ArrayList.
Throws:
IndexOutOfBoundsException - index out of range (index < 0 || index > size()).
Overrides:
addAll in class AbstractList

Overview  Package   Class  Use  Tree  Deprecated  Index  Help  Java Platform 1.2


Beta 4
 PREV CLASS   NEXT CLASS FRAMES   NO FRAMES

SUMMARY:  INNER | FIELD | CONSTR | METHOD DETAIL:  FIELD | CONSTR | METHOD

Submit a bug or feature


Submit comments/suggestions about new javadoc look
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries.
Copyright 1993-1998 Sun Microsystems, Inc. 901 San Antonio Road,
Palo Alto, California, 94303, U.S.A. All Rights Reserved.
This documentation was generated with a post-Beta4 version of Javadoc.

Você também pode gostar