A apresentação está carregando. Por favor, espere

A apresentação está carregando. Por favor, espere

ArrayList e Genéricos Profs. PROG2 - UNISINOS.

Apresentações semelhantes


Apresentação em tema: "ArrayList e Genéricos Profs. PROG2 - UNISINOS."— Transcrição da apresentação:

1 ArrayList e Genéricos Profs. PROG2 - UNISINOS

2 ArrayList Implementação de Lista Sequencial pela API do Java Vantagem:
Podem crescer (serem redimensionadas) Arrays não podem import java.util.ArrayList; Veja

3 ArrayList Desvantagens: Menos eficiente que array
Só trabalha com objetos (e não com tipos básicos) Pode-se ter um ArrayList de Integer, mas não se pode ter um ArrayList de int. A partir da versão 1.5, isso não é mais um problema por causa da conversão automática de classes Wrappers (Integer, Double, Character, etc) para seus tipos primitivos (int, double, char): Unboxing e Outboxing

4 Conversão de Tipo Primitivo para seu Wrapper
Conversão realizada entre os objetos numéricos (Integer, Float) e o correspondente tipo primitivo de dado (integer, float). Tipo primitivo de dado = tipo básico A partir da versão Java 5.0 é automática (implícita) Autoboxing: Converte tipo básico para objeto numérico Ex: de int para Integer int i = 10; Integer i2 = i; Unboxing: Converte objeto numérico para tipo básico Ex: de Integer para int Integer i2 = new Integer(0); int i = i2;

5 Classe ArrayList Define um ArrayList de Strings:
ArrayList<String> list = new ArrayList<String>(); Capacidade inicial default é 10. Define um ArrayList de Aluno: ArrayList<Aluno> empList = new ArrayList<Aluno>( 20 ); Capacidade inicial é 20.

6 Classe ArrayList Substituindo (ou setando) um elemento em uma determinada posição: list.set( 12, “Hi, Mom.” ); Retornando um elemento de uma posição: System.out.println( list.get( 12 ) ); String s = list.get( 5 );

7 Classe ArrayList Inserindo um elemento no final do ArrayList
list.add( “One” ); list.add( “Two” ); list.add( “Three” ); “One” está na posição 0, “Two” está na posição 1, e “Three” está na posição 2.

8 ArrayList class Inserindo um elemento em uma determinada posição
i deve ser uma posição usada ou a primeira posição livre list.add( “One” ); list.add( “Two” ); list.add( “Three” ); list.add( 1, “Fred” ); “One” está na posição 0, “Fred” está na posição 1, “Two” está na posição 2, e “Three” está na posição 3.

9 Classe ArrayList Retornando tamanho da lista (quantidade de nós na lista): Método size() for (int i=0; i<list.size(); i++) { System.out.println( list.get(i) ); }

10 Métodos da classe ArrayList

11 Métodos da classe ArrayList
public ArrayList<Base_Type>( int initialCapacity ) public ArrayList<Base_Type>() Capacidade inicial default é 10 Ex: ArrayList<String> list = new ArrayList<String>();

12 Métodos da classe ArrayList
Métodos “Array-like” public Base_Type set ( int index, Base_Type newElement ) Onde 0<=index<size() (ou exceção) Ex: String s = list.set (0, “caderno”); public Base_Type get ( int index ) Ex: String s = list.get(0);

13 Métodos da classe ArrayList
Métodos para adicionar elementos public boolean add ( Base_Type newElement ) Adiciona o novo elemento no final size() cresce em 1 Capacidade aumenta se necessário Ex: boolean b = list.add(“caneta”);

14 Métodos da classe ArrayList
Métodos para adicionar elementos public void add ( int index, Base_Type newElement ) 0<=index<=size() Onde se index==size(), insere no final size() cresce em 1 Capacidade aumenta se necessário Quando 0<=index<size(), elemento na posição index é movido para index+1, na index+1 é movido para index+2, …, na size()-1 é movido para size() Ex: list.add(0,“caneta”);

15 Métodos da classe ArrayList
Métodos para remover elementos public Base_Type remove ( int index ) 0<=index<size() (ou exceção) Remove o elemento na posição index; copia para as posições à esquerda os elementos restantes em index+1 … size()-1. Ex: String s = list.remove(2);

16 Métodos da classe ArrayList
Methods to remove elements public boolean remove( Object theElement ) Se encontrada, remove a primeira ocorrência de theElement; copia para a esquerda os elementos restantes; size() se torna size()-1; Retorna true. Se não encontrada, retorna false. Ex: boolean b = list.remove(“caneta”); public void clear ( ) Remove todos os elementos; size() se torna 0 Ex: list.clear ();

17 Métodos da classe ArrayList
Métodos de Procura public boolean contains ( Object target ) Chama o método equals() de target True se ArrayList contém target; false caso contrário. Ex: boolean b = list.contains(“caneta”); public int indexOf ( Object target ) Retorna índice (posição) da primeira ocorrência de target em ArrayList; -1 caso contrário. Ex: int pos = list.indexOf(“caneta”); public int lastIndexOf ( Object target ) Realiza o mesmo que o anterior, com a diferença que é retornada a posição da última ocorrência. Ex: int pos = list.lastIndexOf(“caneta”);

18 Métodos da classe ArrayList
Gerenciamento da memória (tamanho & capacidade) public boolean isEmpty ( ) True se vazio; false caso contrário. Ex: boolean b = list.isEmpty(); public int size ( ) Retorna número de elementos (nós) em ArrayList Ex: int tam = list.size(); public void ensureCapacity ( int newCapacity ) Aumenta a capacidade (se necessário) Ex: list. ensureCapacity(20); public void trimToSize ( ) Reduz a capacidade para tamanho atual Ex: list. trimToSize();

19 Métodos da classe ArrayList
Para cópia public Object[] toArray ( ) Retorna um array contendo os elementos da lista. Ex: Object[] v = list.toArray(); public Object clone ( ) Retorna uma cópia de ArrayList. Ex: Object v = list.clone();

20 Métodos da classe ArrayList
Igualdade public boolean equals ( Object other ) Verdadeiro somente se ambos possuem o mesmo número de elementos e os mesmos elementos (na mesma ordem). Compara cada par de elementos chamando seu método equals() Ex: boolean b = list.equals(list2);

21 for-each loop for (Array_Base_Type var : Collection_Object) Statement;
Se myList for ArrayList de Strings. for (String element : myList) System.out.println( element );

22 for-each loop for-each também funciona com arrays:
// Retorna o soma dos elementos de a int sum ( int[] a ) { int result = 0; for (int item : a) result += item; return result; }

23 Biblioteca Java Classes da biblioteca Java que implementam listas em Java: java.util.Vector java.util.ArrayList (desde versão 1.2) Qual a diferença? Vector é sincronizado, assim todos os métodos da classe Vector são thread-safe (garante integridade dos dados quando mais de uma thread acessa). Sincronização tem um custo na performance, assim quando não é necessário sincronizar, melhor usar ArrayList Maiores explicações em: vector.html

24 Problem 1 In the sport of diving, seven judges award a score between [0.0,10.0]. The highest and lowest scores are discarded. The remaining scores are added together. The sum is then multiplied by the degree of difficulty [1.2,3.8] for that dive. The result is then multiplied by 0.6 to determine the diver’s score. Write a program that inputs the degree of difficulty and the 7 judges’ score, and outputs the diver’s score. You are required to use an ArrayList of Double for the judges’ scores.

25 Problem 2 Write a program that uses an ArrayList of parameter type Contact to store a database of contracts. The Contract class should store the contact’s first and last name, phone number, and address. Add appropriate accessor and mutator methods. Your program should present a textual menu that allows the user to add a contact, display all contacts, search for a specific contact and displays it, or search for a specific contact and give the user the option to delete it. The searches should find any contact where any member variable contains a target search string. For example, if “elmore” is the search target then any contact where the first name, last name, phone number, or address contains “elmore” should be returned for display or deletion. Use the “for-each” loop to iterate through the ArrayList.

26 Problem 3 Many GPS’ can record waypoints. The waypoint marks the coordinates of a location on a map along with a timestamp. Our GPS stores waypoints in terms of an (X,Y) coordinate on a map together with a timestamp t that records the number of seconds that have elapsed since the unit was turned on. Write a program that allows the user to enter as many waypoints as desired, storing each in an ArrayList of a class that you design. As waypoints are entered, calculate the average speed of the trip so far. (The distance between (0,0) to (1,0) is 0.1 miles.)

27 Problem 4 Write a generic class, MyMathClass, with a type parameter T where T is a numeric object type (e.g., Integer, Double, or any class that extends java.lang.Number). Add a method named standardDeviation that takes an ArrayList of type T and returns as a double the standard deviation of the values in the ArrayList. Use the doubleValue() method in the Number class to retrieve the value of each number as a double. Your program should generate a compile-time error if your standard deviation method is invoked on an ArrayList that is defined for non-numeric elements (e.g., String). Additionally, use the for-each in the standardDeviation method.

28 Problem 5 Create a generic class with a type parameter that simulates drawing an item at random out of a box. This class could be used for simulating a random drawing. For example the box might contain Strings representing names written on a slip of paper, or the box might contain Integers representing a random drawing for a lottery based on numeric lottery picks. Create an add method that allows the user of the class to add an object of the specified type along with an isEmpty method that determines whether or not the box is empty. Finally, your class should have a drawItem method that randomly selects an object from the box and returns it. If the user attempts to draw an item out of an empty box, return null. Write a main method that tests your class. To generate a random number x, where 0<=x<=1, use x = Math.random();.


Carregar ppt "ArrayList e Genéricos Profs. PROG2 - UNISINOS."

Apresentações semelhantes


Anúncios Google