Você está na página 1de 24

Captulo 7 Colees e Utilitrios Java

Introduo
Nesta sesso estudaremos o Java Collections Framework, as classes e interfaces, os mtodos que as processam e os iteradores que as percorrem. As Collections esto no pacote java.util. necessrio import-lo nas suas aplicaes que as utilizam. ArrayList, Vector, Enumeration, Stack e Hashtable so exemplos de classes Java que representam estruturas para armazenar objetos e possuem mtodos para manipulao destas estruturas. As Colees so estruturas de armazenamento e organizao de objetos. Elas fornecem componentes reutilizveis prontos para incluso em programas Java. As classes sero mostradas abaixo com seus principais mtodos, mas sempre necessrio estudar cada classe com todos os seus mtodos na referncia da linguagem em http://java.sun.com/, na sesso API Specifications. Complemente os estudos utilizando Deitel, Java, como programar, Editora Bookman, a maioria dos exemplos utilizados aqui citados so baseados nesta publicao.

Utilitrios Java
As classes estudadas nesta sesso esto no pacote java.util. necessrio import-lo nas suas aplicaes que as utilizam.

Classe Vector
Estruturas de dados tipo arrays que armazenam referncias a Objects e que podem redimensionar dinamicamente a si prprias. O tamanho do redimensionamento pode ser definido na sua inicializao ou, se no for definido, a estrutura dobra de tamanho quando for necessrio. Criando um Vector com tamanho inicial 20 e redimensionamento 5: Vector v = new Vector (20, 5);

Java Notas de Aulas Captulo 7: Utilitrios Java e Colees

Mtodos de Vector
v.addElement(objeto) adiciona um elemento estrutura. v.insertElementAt(objeto, posio) adiciona na posio alocando

espao.
v.setElementAt(objeto, posio) modifica um elemento na posio. v.removeElement(objeto) remove a primeira ocorrncia do elemento

retornando true se encontrou ou false, caso contrrio. Os objetos seguintes so deslocados para posies anteriores.
v.removeElementAt(posio) remove o elemento na posio. v.removeAllElements() remove todos os elemento da estrutura.

retorna NoSuchElementException.
v.firstElement()

o o

primeiro primeiro

elemento objeto

ou ou

retorna NoSuchElementException.
v.lastElement()

v.isEmpty() retorna true se o Vector estiver vazio. v.contains(chave) retorna true se o Vector contm a chave

especificada.
v.indexOf(objeto) retorna o ndice da primeira ocorrncia do objeto. v.trimToSize() reduz a capacidade para o nmero de elementos atual. v.size() retorna o nmero de elementos atual. v.capacity() retorna a capacidade atual. v.elements() retorna uma Enumeration contendo o conjunto de

elementos.

Enumeration Estrutura de objetos que possui dois mtodos de manipulao:


enum.hasMoreElements() retorna true se houver mais elementos. enum.nextElement()

retorna uma referncia para o prximo

elemento.
2001-2007, Adriano Caminha, www.templojava.org

Java Notas de Aulas Captulo 7: Utilitrios Java e Colees

Exemplo: VectorTest (Deitel)


import import import import java.util.*; java.awt.*; java.awt.event.*; javax.swing.*;

public class VectorTest extends JFrame { public VectorTest() { super( "Vector Example" ); final JLabel status = new JLabel(); Container c = getContentPane(); final Vector v = new Vector( 1 ); c.setLayout( new FlowLayout() ); c.add( new JLabel( "Enter a string" ) ); final JTextField input = new JTextField( 10 ); c.add( input ); JButton addBtn = new JButton( "Add" ); addBtn.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { v.addElement( input.getText() ); status.setText( "Added to end: " + input.getText() ); input.setText( "" ); } } ); c.add( addBtn ); JButton removeBtn = new JButton( "Remove" ); removeBtn.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { if ( v.removeElement( input.getText() ) ) status.setText( "Removed: " + input.getText() ); else status.setText( input.getText() +

2001-2007, Adriano Caminha, www.templojava.org

Java Notas de Aulas Captulo 7: Utilitrios Java e Colees " not in vector" ); } } ); c.add( removeBtn ); JButton firstBtn = new JButton( "First" ); firstBtn.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { try { status.setText( "First element: " + v.firstElement() ); } catch ( NoSuchElementException exception ) { status.setText( exception.toString() ); } } } ); c.add( firstBtn ); JButton lastBtn = new JButton( "Last" ); lastBtn.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { try { status.setText( "Last element: " + v.lastElement() ); } catch ( NoSuchElementException exception ) { status.setText( exception.toString() ); } } } ); c.add( lastBtn ); JButton emptyBtn = new JButton( "Is Empty?" ); emptyBtn.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { status.setText( v.isEmpty() ? "Vector is empty" : "Vector is not empty" ); } }

2001-2007, Adriano Caminha, www.templojava.org

Java Notas de Aulas Captulo 7: Utilitrios Java e Colees ); c.add( emptyBtn ); JButton containsBtn = new JButton( "Contains" ); containsBtn.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { String searchKey = input.getText(); if ( v.contains( searchKey ) ) status.setText( "Vector contains " + searchKey ); else status.setText( "Vector does not contain " + searchKey ); } } ); c.add( containsBtn ); JButton locationBtn = new JButton( "Location" ); locationBtn.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { status.setText( "Element is at location " + v.indexOf( input.getText() ) ); } } ); c.add( locationBtn ); JButton trimBtn = new JButton( "Trim" ); trimBtn.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { v.trimToSize(); status.setText( "Vector trimmed to size" ); } } ); c.add( trimBtn ); JButton statsBtn = new JButton( "Statistics" ); statsBtn.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e )

2001-2007, Adriano Caminha, www.templojava.org

Java Notas de Aulas Captulo 7: Utilitrios Java e Colees { } } ); c.add( statsBtn ); JButton displayBtn = new JButton( "Display" ); displayBtn.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { Enumeration enum = v.elements(); StringBuffer buf = new StringBuffer(); while ( enum.hasMoreElements() ) buf.append( enum.nextElement() ).append( " JOptionPane.showMessageDialog( null, buf.toString(), "Display", JOptionPane.PLAIN_MESSAGE ); } } ); c.add( displayBtn ); c.add( status ); setSize( 300, 200 ); show(); } public static void main( String args[] ) { VectorTest app = new VectorTest(); app.addWindowListener( new WindowAdapter() { public void windowClosing( WindowEvent e ) { System.exit( 0 ); } } ); } }
/************************************************************************** * (C) Copyright 1999 by Deitel & Associates, Inc. and Prentice Hall. * * All Rights Reserved. * * Comentrios por Adriano Caminha * *************************************************************************/

status.setText( "Size = " + v.size() + "; capacity = " + v.capacity() );

" );

2001-2007, Adriano Caminha, www.templojava.org

Java Notas de Aulas Captulo 7: Utilitrios Java e Colees

Classe Stack
Estende a classe Vector para implementar uma estrutura tipo pilha. Criando uma Stack vazia: Stack s = new Stack ();

Mtodos de Stack
s.push(objeto) adiciona um elemento ao topo da pilha. s.pop() remove um elemento do topo da pilha e retorna uma referncia

para o objeto removido. Se estiver vazia, retorna EmptyStackException.


s.peek() para verificar o elemento do topo da pilha sem remove-lo.

Retorna uma referncia para o topo.


s.isEmpty() para verificar se pilha vazia. s.search(chave) retorna a posio do elemento na pilha ou 1 se no

estiver na pilha. Podem ser usados tambm os mtodos de Vector, que superclasse de Stack. O exemplo utiliza o mtodo elements():

Exemplo: StackTest (Deitel)


import import import import java.util.*; java.awt.*; java.awt.event.*; javax.swing.*;

public class StackTest extends JFrame { public StackTest() { super( "Stacks" ); Container c = getContentPane(); final JLabel status = new JLabel(); final Stack s = new Stack(); c.setLayout( new FlowLayout() ); c.add( new JLabel( "Enter a string" ) ); final JTextField input = new JTextField( 10 );

2001-2007, Adriano Caminha, www.templojava.org

Java Notas de Aulas Captulo 7: Utilitrios Java e Colees c.add( input ); JButton pushBtn = new JButton( "Push" ); pushBtn.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { status.setText( "Pushed: " + s.push( input.getText() ) ); } } ); c.add( pushBtn ); JButton popBtn = new JButton( "Pop" ); popBtn.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e { try { status.setText( "Popped: " + s.pop() } catch ( EmptyStackException exception ) status.setText( exception.toString() } } } ); c.add( popBtn );

); { );

JButton peekBtn = new JButton( "Peek" ); peekBtn.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { try { status.setText( "Top: " + s.peek() ); } catch ( EmptyStackException exception ) { status.setText( exception.toString() ); } } } ); c.add( peekBtn ); JButton emptyBtn = new JButton( "Is Empty?" ); emptyBtn.addActionListener( new ActionListener() {

2001-2007, Adriano Caminha, www.templojava.org

Java Notas de Aulas Captulo 7: Utilitrios Java e Colees public void actionPerformed( ActionEvent e ) { status.setText( s.empty() ? "Stack is empty" : "Stack is not empty" ); } } ); c.add( emptyBtn ); JButton searchBtn = new JButton( "Search" ); searchBtn.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { String searchKey = input.getText(); int result = s.search( searchKey ); if ( result == -1 ) status.setText( searchKey + " not found" ); else status.setText( searchKey + " found at element " + result ); } } ); c.add( searchBtn ); JButton displayBtn = new JButton( "Display" ); displayBtn.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { Enumeration enum = s.elements(); StringBuffer buf = new StringBuffer(); while ( enum.hasMoreElements() ) buf.append( enum.nextElement() ).append( " " ); JOptionPane.showMessageDialog( null, buf.toString(), "Display", JOptionPane.PLAIN_MESSAGE ); } } ); c.add( displayBtn ); c.add( status ); setSize( 675, 100 );

2001-2007, Adriano Caminha, www.templojava.org

Java Notas de Aulas Captulo 7: Utilitrios Java e Colees show(); } public static void main( String args[] ) { StackTest app = new StackTest(); app.addWindowListener( new WindowAdapter() { public void windowClosing( WindowEvent e ) { System.exit( 0 ); } } ); } }
/************************************************************************** * (C) Copyright 1999 by Deitel & Associates, Inc. and Prentice Hall. * * All Rights Reserved. * * Comentrios por Adriano Caminha * *************************************************************************/

Classe Hashtable
Estende a classe Vector para implementar uma estrutura tipo tabela de hashing, tcnica onde uma tabela converte chaves para ndices de um vetor. Esta classe resolve problemas de colises implementando um buqu de hash, ou seja, uma lista encadeada para pares chave/valor que produzem hash para a clula em questo. Criando uma Hashtable vazia com capacidade para 101 elementos e fator padro de carga de 0,75 (quando o nmero de posies ocupadas for se tornar maior que a capacidade vezes o fator de carga, a tabela automaticamente crescer): Hashtable t = new Hashtable (); //ou (capacidade, fator de carga)

Mtodos de Hashtable
t.put(chave, objeto) adiciona uma chave e um elemento tabela. Se

no existir esta chave, adicionar e retornar null, se existir, retornar o valor original.
t.get(chave) retorna um elemento da tabela. Retornar uma referncia

para o objeto ou null se no existir.

2001-2007, Adriano Caminha, www.templojava.org

10

Java Notas de Aulas Captulo 7: Utilitrios Java e Colees

t.remove(chave) remove um elemento da tabela. Retornar uma

referncia para o objeto ou null se no existir.


t.isEmpty() para verificar se tabela vazia. t.containsKey(chave) retorna true se a tabela contm a chave

especificada.
t.contains(objeto) retorna true se a tabla contm o elemento

especificado.
t.clear() para esvaziar a tabela. t.elements() retorna uma Enumeration contendo o conjunto de

valores da tabela.
t.keys() retorna uma Enumeration contendo o conjunto de chaves da

tabela.

Exemplo: HashtableTest (Deitel)


import import import import java.util.*; java.awt.*; java.awt.event.*; javax.swing.*;

public class HashtableTest extends JFrame { public HashtableTest() { super( "Hashtable Example" ); final JLabel status = new JLabel(); final Hashtable table = new Hashtable(); final JTextArea display = new JTextArea( 4, 20 ); display.setEditable( false ); JPanel northPanel = new JPanel(); northPanel.setLayout( new BorderLayout() ); JPanel northSubPanel = new JPanel(); northSubPanel.add( new JLabel( "First name" ) ); final JTextField fName = new JTextField( 8 ); northSubPanel.add( fName ); northSubPanel.add( new JLabel( "Last name (key)" ) ); final JTextField lName = new JTextField( 8 ); northSubPanel.add( lName ); northPanel.add( northSubPanel, BorderLayout.NORTH ); northPanel.add( status, BorderLayout.SOUTH );

2001-2007, Adriano Caminha, www.templojava.org

11

Java Notas de Aulas Captulo 7: Utilitrios Java e Colees

JPanel southPanel = new JPanel(); southPanel.setLayout( new GridLayout( 2, 5 ) ); JButton put = new JButton( "Put" ); put.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { Employee emp = new Employee( fName.getText(), lName.getText() ); Object val = table.put( lName.getText(), emp ); if ( val == null ) status.setText( "Put: " + emp.toString() ); else status.setText( "Put: " + emp.toString() + "; Replaced: " + val.toString() ); } } ); southPanel.add( put ); JButton get = new JButton( "Get" ); get.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { Object val = table.get( lName.getText() ); if ( val != null ) status.setText( "Get: " + val.toString() ); else status.setText( "Get: " + lName.getText() + " not in table" ); } } ); southPanel.add( get ); JButton remove = new JButton( "Remove" ); remove.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { Object val = table.remove( lName.getText() ); if ( val != null ) status.setText( "Remove: " + val.toString() );

2001-2007, Adriano Caminha, www.templojava.org

12

Java Notas de Aulas Captulo 7: Utilitrios Java e Colees else status.setText( "Remove: " + lName.getText() + " not in table" ); } } ); southPanel.add( remove ); JButton empty = new JButton( "Empty" ); empty.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { status.setText( "Empty: " + table.isEmpty() ); } } ); southPanel.add( empty ); JButton containsKey = new JButton( "Contains key" ); containsKey.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { status.setText( "Contains key: " + table.containsKey( lName.getText() ) ); } } ); southPanel.add( containsKey ); JButton clear = new JButton( "Clear table" ); clear.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { table.clear(); status.setText( "Clear: Table is now empty" ); } } ); southPanel.add( clear ); JButton listElems = new JButton( "List objects" ); listElems.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { StringBuffer buf = new StringBuffer();

2001-2007, Adriano Caminha, www.templojava.org

13

Java Notas de Aulas Captulo 7: Utilitrios Java e Colees

for ( Enumeration enum = table.elements(); enum.hasMoreElements(); ) buf.append( enum.nextElement() ).append( '\n' ); display.setText( buf.toString() ); } } ); southPanel.add( listElems ); JButton listKeys = new JButton( "List keys" ); listKeys.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { StringBuffer buf = new StringBuffer(); for ( Enumeration enum = table.keys(); enum.hasMoreElements(); ) buf.append( enum.nextElement() ).append( '\n' ); JOptionPane.showMessageDialog( null, buf.toString(), "Display", JOptionPane.PLAIN_MESSAGE ); } } ); southPanel.add( listKeys ); Container c = getContentPane(); c.add( northPanel, BorderLayout.NORTH ); c.add( new JScrollPane( display ), BorderLayout.CENTER ); c.add( southPanel, BorderLayout.SOUTH ); setSize( 540, 300 ); show(); } public static void main( String args[] ) { HashtableTest app = new HashtableTest(); app.addWindowListener( new WindowAdapter() { public void windowClosing( WindowEvent e ) { System.exit( 0 );

2001-2007, Adriano Caminha, www.templojava.org

14

Java Notas de Aulas Captulo 7: Utilitrios Java e Colees } } ); } } class Employee { private String first, last; public Employee( String fName, String lName ) { first = fName; last = lName; } public String toString() { return first + " " + last; } }
/************************************************************************** * (C) Copyright 1999 by Deitel & Associates, Inc. and Prentice Hall. * * All Rights Reserved. * * Comentrios por Adriano Caminha * *************************************************************************/

Classe Properties
uma Hashtable persistente, ou seja, pode ser gravada em um arquivo. Criando uma Properties vazia: Properties t = new Properties ();

Mtodos de Properties
t.getProperty(chave) retorna um elemento da tabela. Retornar uma

referncia para o objeto ou null se no existir.


t.store(output, Descrio) salva o contedo no arquivo output

(objeto de FileOutputStream).
t.load(input) restaura o contedo a partir do arquivo input (objeto de

FileInputStream).
t.propertiesNames() retorna uma Enumeration contendo o conjunto

de nomes de propriedades.

2001-2007, Adriano Caminha, www.templojava.org

15

Java Notas de Aulas Captulo 7: Utilitrios Java e Colees

Exemplo: PropertiesTest (Deitel)


import import import import import java.io.*; java.util.*; java.awt.*; java.awt.event.*; javax.swing.*;

public class PropertiesTest extends JFrame { private JLabel status; private Properties table; private JTextArea display; public PropertiesTest() { super( "Properties Test" ); table = new Properties(); Container c = getContentPane(); JPanel northPanel = new JPanel(); northPanel.setLayout( new BorderLayout() ); JPanel northSubPanel = new JPanel(); JPanel southPanel = new JPanel(); northSubPanel.add( new JLabel( "Property value" ) ); final JTextField propVal = new JTextField( 10 ); northSubPanel.add( propVal ); northPanel.add( northSubPanel, BorderLayout.NORTH ); northSubPanel.add( new JLabel( "Property name (key)" ) ); final JTextField propName = new JTextField( 10 ); northSubPanel.add( propName ); display = new JTextArea( 4, 35 ); JButton put = new JButton( "Put" ); put.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { Object val = table.put( propName.getText(), propVal.getText() ); if ( val == null ) showStatus( "Put: " + propName.getText() + " " + propVal.getText() ); else showStatus( "Put: " + propName.getText() + " " + propVal.getText() + "; Replaced: " + val.toString() );

2001-2007, Adriano Caminha, www.templojava.org

16

Java Notas de Aulas Captulo 7: Utilitrios Java e Colees

listProperties(); } } ); southPanel.setLayout( new GridLayout( 1, 5 ) ); southPanel.add( put ); JButton clear = new JButton( "Clear" ); clear.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { table.clear(); showStatus( "Table in memory cleared" ); listProperties(); } } ); southPanel.add( clear ); JButton getProperty = new JButton( "Get property" ); getProperty.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { Object val = table.getProperty( propName.getText() ); if ( val != null ) showStatus( "Get property: " + propName.getText() + " " + val.toString() ); else showStatus( "Get: " + propName.getText() + " not in table" ); listProperties(); } } ); southPanel.add( getProperty ); JButton save = new JButton( "Save" ); save.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { try {

2001-2007, Adriano Caminha, www.templojava.org

17

Java Notas de Aulas Captulo 7: Utilitrios Java e Colees FileOutputStream output; output = new FileOutputStream( "props.dat" ); table.store( output, "Sample Properties" ); output.close(); listProperties(); } catch( IOException ex ) { showStatus( ex.toString() ); } } } ); southPanel.add( save ); JButton load = new JButton( "Load" ); load.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { try { FileInputStream input; input = new FileInputStream( "props.dat" ); table.load( input ); input.close(); listProperties(); } catch( IOException ex ) { showStatus( ex.toString() ); } } } ); southPanel.add( load ); status = new JLabel(); northPanel.add( status, BorderLayout.SOUTH ); c.add( northPanel, BorderLayout.NORTH ); c.add( new JScrollPane( display ), BorderLayout.CENTER ); c.add( southPanel, BorderLayout.SOUTH ); setSize( 550, 225 ); show(); } public void listProperties() {

2001-2007, Adriano Caminha, www.templojava.org

18

Java Notas de Aulas Captulo 7: Utilitrios Java e Colees StringBuffer buf = new StringBuffer(); String pName, pVal; Enumeration enum = table.propertyNames(); while( enum.hasMoreElements() ) { pName = enum.nextElement().toString(); pVal = table.getProperty( pName ); buf.append( pName ).append( '\t' ); buf.append( pVal ).append( '\n' ); } display.setText( buf.toString() ); } public void showStatus( String s ) { status.setText( s ); } public static void main( String args[] ) { PropertiesTest app = new PropertiesTest(); app.addWindowListener( new WindowAdapter() { public void windowClosing( WindowEvent e ) { System.exit( 0 ); } } ); } }
/************************************************************************** * (C) Copyright 1999 by Deitel & Associates, Inc. and Prentice Hall. * * All Rights Reserved. * * Comentrios por Adriano Caminha * *************************************************************************/

Classe Arrays
Fornece mtodos static para manipulao de arrays simples.

Mtodos de Arrays
Arrays.fill(array, elemento) preenche todo o array com o

elemento.
2001-2007, Adriano Caminha, www.templojava.org

19

Java Notas de Aulas Captulo 7: Utilitrios Java e Colees

Arrays.sort(array) classifica o array.

busca o elemento retornando o ndice se foi localizado ou um nmero negativo indicando a posio aps a que deveria estar o elemento. necessrio classificar antes o array.
Arrays.binarySearch(array, elemento) Arrays.equals(array1, array2) verifica a igualdade de dois arrays. Arrays.asList(array) retorna uma estrutura List a partir do array.

Exemplo: UsingArrays (Deitel)


import java.util.*; public class UsingArrays { private int intValues[] = { 1, 2, 3, 4, 5, 6 }; private double doubleValues[] = { 8.4, 9.3, 0.2, 7.9, 3.4 }; private int filledInt[], intValuesCopy[]; public UsingArrays() { filledInt = new int[ 10 ]; intValuesCopy = new int[ intValues.length ]; Arrays.fill( filledInt, 7 ); Arrays.sort( doubleValues ); System.arraycopy( intValues, 0, intValuesCopy, 0, intValues.length ); } public void printArrays() { System.out.print( "doubleValues: " ); for ( int k = 0; k < doubleValues.length; k++ ) System.out.print( doubleValues[ k ] + " " ); System.out.print("\nintValues: " ); for ( int k = 0; k < intValues.length; k++ ) System.out.print( intValues[ k ] + " " ); System.out.print("\nfilledInt: " ); for ( int k = 0; k < filledInt.length; k++ ) System.out.print( filledInt[ k ] + " " ); System.out.print("\nintValuesCopy: " ); for ( int k = 0; k < intValuesCopy.length; k++ ) System.out.print( intValuesCopy[ k ] + " " ); System.out.println();

2001-2007, Adriano Caminha, www.templojava.org

20

Java Notas de Aulas Captulo 7: Utilitrios Java e Colees } public int searchForInt( int value ) { return Arrays.binarySearch( intValues, value ); } public void printEquality() { boolean b = Arrays.equals( intValues, intValuesCopy ); System.out.println( "intValues " + ( b ? "==" : "!=" ) + " intValuesCopy" ); b = Arrays.equals( intValues, filledInt ); System.out.println( "intValues " + ( b ? "==" : "!=" ) + " filledInt" ); } public static void main( String args[] ) { UsingArrays u = new UsingArrays(); u.printArrays(); u.printEquality(); int n = u.searchForInt( 5 ); System.out.println( ( n >= 0 ? "Found 5 at "5 not found" ) + " in n = u.searchForInt( 8763 ); System.out.println( ( n >= 0 ? "Found 8763 + n : "8763 not found" + " in intValues" ); } }
/************************************************************************** * (C) Copyright 1999 by Deitel & Associates, Inc. and Prentice Hall. * * All Rights Reserved. * * Comentrios por Adriano Caminha * *************************************************************************/

element " + n : intValues" ); at element " )

Interface Collection
o topo da hierarquia de colees. Deriva as interfaces Set (sem duplicatas) e List.

2001-2007, Adriano Caminha, www.templojava.org

21

Java Notas de Aulas Captulo 7: Utilitrios Java e Colees

Fornece mtodos para manipulao de colees. Fornece o mtodo para gerao do objeto Iterator, para percorrer as colees como as Enumerations mas podendo remover elementos.

Classe Collections
Fornece mtodos static para manipulao de colees polimorficamente, para pesquisar, classificar, etc.

Interface List
uma Collection ordenada que pode conter duplicatas. So baseadas em zero. Fornece mtodos para manipulao de elementos utilizando seus ndices, alm de obter um ListIterator para acessar os elementos. implementada por ArrayList, LinkedList e Vector.

Classe ArrayList
a implementao de array redimensionvel de uma List. O comportamento semelhante ao de um Vector no-syncronyzed. LinkedList uma implementao de lista encadeada de uma List. Criando uma ArrayList vazia: ArrayList aList = new ArrayList ();

Mtodos de ArrayList aList.add(elemento) adiciona o elemento. aList.get(indice) recupera o valor do elemento. aList.size() quantidade de elementos.

Classe Iterator
Para criar um Iterator a partir de uma Collection c:

2001-2007, Adriano Caminha, www.templojava.org

22

Java Notas de Aulas Captulo 7: Utilitrios Java e Colees

Iterator i = c.iterator (); Mtodos de Iterator:


i.hasNext() retorna true se houver um prximo elemento. i.next() retorna uma referncia para o prximo elemento. i.remove() remove o prximo elemento.

Exemplo: CollectionTest (Deitel)


import java.util.*; import java.awt.Color; public class CollectionTest { private String colors[] = { "red", "white", "blue" }; public CollectionTest() { ArrayList aList = new ArrayList(); aList.add( Color.magenta ); for ( int k = 0; k < colors.length; k++ ) aList.add( colors[ k ] ); aList.add( Color.cyan ); System.out.println( "\nArrayList: " ); for ( int k = 0; k < aList.size(); k++ ) System.out.print( aList.get( k ) + " " ); removeStrings( aList ); System.out.println( "\n\nArrayList after calling removeStrings: " ); for ( int k = 0; k < aList.size(); k++ ) System.out.print( aList.get( k ) + " " ); } public void removeStrings( Collection c ) { Iterator i = c.iterator(); while ( i.hasNext() ) if ( i.next() instanceof String ) i.remove(); }

2001-2007, Adriano Caminha, www.templojava.org

23

Java Notas de Aulas Captulo 7: Utilitrios Java e Colees

public static void main( String args[] ) { new CollectionTest(); } }


/************************************************************************** * (C) Copyright 1999 by Deitel & Associates, Inc. and Prentice Hall. * * All Rights Reserved. * * Comentrios por Adriano Caminha * *************************************************************************/

Exerccios: 1. Desenvolver aplicativos utilizando as seguintes colees para armazenamento e organizao dos dados na memria: a) Vector, b) HashTable, c) Properties e d) ArrayList Utilize como tema um controle de estoque de produtos de um supermercado. Crie classes representando quatro tipos de produtos diferentes (arroz, feijo, caf e acar) e um programa principal para ler dados, armazenar na coleo, listar produtos, buscar produto e outras funes, dependendo da coleo utilizada em cada verso. Estude os mtodos de cada coleo pelos livros e pela API de Java 5.0. 2. Implemente um aplicativo utilizando a coleo Stack para armazenamento e organizao de uma pilha de nmeros inteiros. Utilize os mtodos da coleo para imprimir a pilha, buscar a posio de um elemento na pilha, etc. 3. Implemente um aplicativo utilizando vetores simples para armazenamento e organizao de nmeros reais (double). Utilize os mtodos da classe Arrays para preencher todo o vetor com um certo nmero, ordenar o vetor, etc.

2001-2007, Adriano Caminha, www.templojava.org

24

Você também pode gostar