• Non ci sono risultati.

Package java.util Il package java.util contiene molte classi di uso frequente.

N/A
N/A
Protected

Academic year: 2021

Condividi "Package java.util Il package java.util contiene molte classi di uso frequente."

Copied!
14
0
0

Testo completo

(1)

Package java.util

Il package java.util contiene molte classi di uso frequente.

AbstractCollection AbstractList AbstractMap AbstractQueue

AbstractSequentialList AbstractSet ArrayDeque (Added by Java SE 6.) ArrayList Arrays BitSet Calendar Collections Currency

Date Dictionary EnumMap EnumSet EventListenerProxy EventObject FormattableFlags Formatter GregorianCalendar HashMap HashSet Hashtable IdentityHashMap LinkedHashMap LinkedHashSet LinkedList ListResourceBundle Locale

Observable PriorityQueue Properties PropertyPermission PropertyResourceBundle Random ResourceBundle Scanner ServiceLoader (Added by Java SE 6.)

SimpleTimeZone Stack StringTokenizer Timer TimerTask TimeZone TreeMap TreeSet UUID Vector WeakHashMap

Interfacce in java.util

Collection List Queue

Comparator ListIterator RandomAccess

Deque (Added by Java SE 6.) Map Set

Enumeration Map.Entry SortedMap

EventListener NavigableMap (Added by Java SE 6.) SortedSet Formattable NavigableSet (Added by Java SE 6.)

Iterator Observer

(2)

ArrayList (dynamic array)

•An ArrayList is a re-sizable array, also called a dynamic array.

•It grows its size to accommodate new elements and shrinks the size when the elements are removed.

•ArrayList internally uses an array to store the elements.

The elements can be retrieved by their index.

•Java ArrayList allows duplicate and null values.

•Java ArrayList is an ordered collection. It maintains the insertion order of the elements.

You cannot create an ArrayList of primitive types like int , char etc.

You need to use boxed types like Integer , Character , Boolean etc.

(3)

// Demonstrate ArrayList.

import java.util.*;

class ArrayListDemo {

public static void main(String args[]) { // Create an array list.

ArrayList<String> al = new ArrayList<String>();

System.out.println("Initial size of al: " + al.size());

// Add elements to the array list.

al.add("C");

al.add("A"); // it adds "A" at the end of the list al.add("E");

al.add("B");

al.add("D");

al.add("F");

al.add(1, "A2"); // it adds one value with index 1 shifting the others System.out.println("Size of al after additions: " +

al.size());

// Display the array list.

System.out.println("Contents of al: " + al);

// Remove elements from the array list.

al.remove("F"); // removes first occurrence of "F"

al.remove(2); // removes value with index 2 System.out.println("Size of al after deletions: " + al.size());

System.out.println("Contents of al: " + al);

} }

ArrayListDemo.main({ });

Initial size of al: 0

Size of al after additions: 7

Contents of al: [C, A2, A, E, B, D, F]

Size of al after deletions: 5 Contents of al: [C, A2, E, B, D]

(4)

//Demonstrate Arrays import java.util.*;

public class ProvaArrays{

public static void main(){

int[] V ={3,5,9,-1}; // initially 4 variables in V

V=Arrays.copyOf(V,6); // it copies the array and augments its size to 6 for (int i=0; i<V.length; i++)

System.out.println("V["+i+"]="+V[i]);

} }

V[0]=3 V[1]=5 V[2]=9 V[3]=-1 V[4]=0 V[5]=0

(5)

ArrayDeque (‘Doubled Ended QUEue’) class to implement double linked list which can realize both Stacks and Queues (it has operators to work at the two ends)

//demonstrate ArrayDeque for implementing a Stack import java.util.*;

public class ArrayDequeDemo {

public static void main(String args[]) {

ArrayDeque<String> adq = new ArrayDeque<String>();

// Use an ArrayDeque like a stack.

adq.push("A");

adq.push("B");

adq.push("D");

adq.push("E");

adq.push("F");

System.out.print("Popping the stack: ");

while(adq.peek() != null) // check if the stack is empty

System.out.print(adq.pop() + " "); //pop() returns the last value inserted and // removes it

System.out.println();

} }

ArrayDequeDemo.main({ });

Popping the stack: F E D B A

(6)

Java Collections Framework

The Java Collections Framework standardizes the way in which groups of objects are handled.

Introduced in Java 1.2.

Algorithms operate on collections and are defined as static methods within the Collections class.

Thus, they are available for all collections.

Iterator interface. An iterator offers a general-purpose, standardized way of accessing the elements within a collection, one at a time.

Each collection implements Iterator. Thus, the elements of any collection class can be accessed through the methods defined by Iterator, with similar cycles for different data structures, e.g. sets and lists.

All collections are now generic

Automatically perform the proper boxing and unboxing needed when storing or retrieving primitive types

All collection classes in the Collections Framework implement the Iterable interface, hence a collection can be cycled through by use of the for-each loop

(7)
(8)

Collection

Collection is a generic interface that has this declaration:

interface Collection<E>

E specifies the type of objects that the collection will hold.

Collection extends the Iterable interface. This means that all collections can be cycled through by use of the for-each style for loop.

The Queue interface extends Collection and declares the behavior of a queue Queue is a generic interface that has this declaration:

interface Queue<E>

Correspondence with our operators on queues (throws exception if there is a mistake):

Queue operators Coda<E> operators E element( ) E top()

E remove( ) dequeue() add(E obj) enqueue(E obj)

add returns ‘true’ if the operation is completed successfully

(9)

Cycles through the elements in a collection.

One way to do this is to employ an iterator, which is an object that implements either the Iterator or the ListIterator interface. Iterator enables you to cycle through a collection, obtaining or removing elements.

Iterator and ListIterator

are generic interfaces which are declared as shown here:

interface Iterator<E>

interface ListIterator<E>

Here, E specifies the type of objects being iterated.

Iterator enables to cycle through a collection, obtaining or removing elements.

ListIterator extends Iterator to allow bidirectional traversal of a list, and the modification of elements.

In general, to use an iterator to cycle through the contents of a collection, follow these steps:

1. Obtain an iterator to the start of the collection by calling the collection’s iterator( ) method.

2. Set up a loop that makes a call to hasNext( ). Have the loop iterate as long as hasNext( ) returns true.

3. Within the loop, obtain each element by calling next( ).

(10)

// Demonstrate iterators.

import java.util.*;

class IteratorDemo {

public static void main(String args[]) { // Create an array list.

ArrayList<String> al = new ArrayList<String>();

// Add elements to the array list.

al.add("C");

al.add("A");

al.add("E");

al.add("B");

al.add("D");

al.add("F");

// Use iterator to display contents of al.

System.out.print("Original contents of al: ");

Iterator<String> itr = al.iterator();

while(itr.hasNext()) { // with iterator

String element = itr.next(); // values cannot be modified if (element=="A") itr.remove(); // values can be removed System.out.print(element + " ");

}

System.out.println();

// Modify objects being iterated.

ListIterator<String> litr = al.listIterator();

while(litr.hasNext()) { // with listIterators String element = litr.next();

litr.set(element + "+"); // values can be modified }

System.out.print("Modified contents of al: ");

itr = al.iterator();

while(itr.hasNext()) {

String element = itr.next();

(11)

System.out.print(element + " ");

}

System.out.println();

// Now, display the list backwards.

System.out.print("Modified list backwards: ");

while(litr.hasPrevious()) {

String element = litr.previous();

System.out.print(element + " ");

}

System.out.println();

}}

The output is:

Original contents of al: C A E B D F Modified contents of al: C+ E+ B+ D+ F+

Modified list backwards: F+ D+ B+ E+ C+

The For-Each Alternative to Iterators

The following example uses a for loop to sum the contents of a collection:

The for-each loop can be used to cycle through a collection or an array.

Syntax of for-each loop:

for(data_type item : collection) { ….. }

(12)

import java.util.*;

class ForEachDemo {

public static void main(String args[]) { // Create an array list for integers.

ArrayList<Integer> vals = new ArrayList<Integer>();

// Add values to the array list.

vals.add(1);

vals.add(2);

vals.add(3);

vals.add(4);

vals.add(5);

// Use for loop to display the values.

System.out.print("Original contents of vals: ");

for(int v : vals) System.out.print(v + " ");

} }

System.out.println();

// Now, sum the values by using a for loop.

int sum = 0;

for(int v : vals) sum += v;

System.out.println("Sum of values: " + sum);

}}

The output from the program is:

Original contents of vals: 1 2 3 4 5 Sum of values: 15

The for loop is substantially shorter and simpler to use than the iterator- based approach.

However, it can only be used to cycle through a collection in the forward direction, and the contents of the collection cannot be modified.

(13)

Storing User-Defined Classes in Collections

consider the following example that uses a LinkedList to store mailing addresses:

// A simple mailing list example.

import java.util.*;

class Address {

private String name;

private String street;

private String city;

private String state;

private String code;

Address(String n, String s, String c, String st, String cd) {

name = n;

street = s;

city = c;

state = st;

code = cd;

}

public String toString() {

return name + "\n" + street + "\n" + city + " " + state + " " + code;

}}

class MailList {

public static void main(String args[]) {

LinkedList<Address> ml = new LinkedList<Address>();

// Add elements to the linked list.

ml.add(new Address("J.W. West", "11 Oak Ave", "Urbana", "IL", "61801"));

ml.add(new Address("Ralph Baker", "1142 Maple Lane", "Mahomet", "IL", "61853"));

ml.add(new Address("Tom Carlton", "867 Elm St",

(14)

"Champaign", "IL", "61820"));

// Display the mailing list.

for(Address element : ml)

System.out.println(element + "\n");

System.out.println();

} }

The output from the program is shown here:

J.W. West 11 Oak Ave Urbana IL 61801 Ralph Baker 1142 Maple Lane Mahomet IL 61853 Tom Carlton

867 Elm St

Champaign IL 61820

Riferimenti

Documenti correlati

Note that some keys default to this value every listing, namely the keys which can be used on individual listings only.... Regarding the parameters, please keep in mind

 The hdfs command can be executed in a Linux shell to read/write/modify/delete the content of the distributed file system..  The parameters/arguments of hdfs command are used

Crea un oggetto di tipo File File denominato denominato nome nome a partire dalla directory dir a partire dalla directory dir (descritta tramite una stringa)..

Linear Algebra

Javascript, Python, Ruby, but also Lisp, etc...) -Type inference for generics, diamond operator -Fork/Join Framework for parallel programming. (aiuta a creare task paralleli, fa

• FileOutputStream implementa questi metodi nel caso parti- colare in cui l’output è un file, il cui nome è passato al costrut- tore di FileOutputStream ; in alternativa si

Per usare un oggetto di tipo OutputWindow, il metodo OutputWindow main main deve prima crearne uno. La classe OutputWindow OutputWindow definisce le caratteristiche dei

Il metodo readString readString () () di un oggetto di tipo InputWindow InputWindow apre un pannello con un messaggio (“ Insert Insert a string a string”) che chiede di inserire