Java NewElems Colections2013
Java NewElems Colections2013
Java NewElems Colections2013
Autobox, unbox
-tipuri primitive de date : byte, short, int, long, char, float, double and boolean -constante predefinite : POSITIVE_INFINITY,
NEGATIVE_INFINITY, NaN (Not a Number) -IEEE 754 standard pentru dimensiuni ale datelor
Instructiunea for-each
for(tip_variabila nume_variabila: nume_variabila_de_tip_sir){ //instructiuni }
si for(tip_variabila nume_variabila: nume_variabila_de_tip_colectie){ //instructiuni }
3
Exemple: int[] numere = {1,2,3,4,5,6,7,8,9,10}; for (int element : numere) { System.out.println("Elementul curent: " + element); }
import java.util.Iterator; import java.util.Vector; class Test { public static void main(String[] arguments) { String[] codes = { "alpha", "lambda", "gamma", "delta", "zeta" }; Vector list = new Vector(); for (int i = 0; i < codes.length; i++) { if (!list.contains(codes[i])) { list.add(codes[i]); } }
5
//varianta clasic de abordare for (Iterator ite = list.iterator(); ite.hasNext();) { String output = (String) ite.next(); System.out.println(output); } //varianta for-each for (Object s : list) { //String output = (String) ite.next(); System.out.println((String)s); } }}
6
Metode
-metode de tip utility :
import java.lang.Math.*; Math.pow(...); import static java.lang.Math.*; pow(...); import static java.lang.System.* out.println(test);// not System. out.println(test);
command line args. numele aplicatiei nu mai e primul parametru varargs parameters din JSE5
7
class VarArgs{ static void vaTest(intv){ System.out.println(No. of args=+ v.length + Contents:); for(int x:v) System.out.print(x+ ); System.out.println();}//vaTest public static void main(String args[]){ vaTest(10);//1 arg vaTest(1,2,3);//3 args vaTest();//no arg }//main }//class
9
Java Collections
In Java we have classes and interfaces to manage lists and collections A collection is a group of objects, from Object class (ordered or not). It is possible to insert, sort, search, etc. It is possible to have different types of objects in some collection, but usual are of same type
10
A collection is defined using an interface from the java.util package that is used to define a group, or a collection, of objects. It includes sets, lists and map. Because it is in the java.util package, it will be necessary to import the java.util package into any programs you write using a collection. Collections are a very important part of data storing.
11
13
Another way to build a collection interface is to use an object that already exists from a class. Rather than creating and keeping track of the value and suit of each card, we can simply keep track of the cards.
If we store the value and suit inside the class Card, any Card object will contain them, which is why it eliminates the need to use them in the Collections interface class.
14
15
Collection interface
No class offered by Java for collections, but Collection interface is inherited by other interfaces such as: BeanContext, BeanContextServices, List, Set and SortedSet.
16
public interface Collection { // Metode cu caracter general int size(); boolean isEmpty(); void clear(); Iterator iterator(); // Operatii la nivel de element boolean contains(Object element); boolean add(Object element); boolean remove(Object element); // Operatii la nivel de multime boolean containsAll(Collection c); boolean addAll(Collection c); boolean removeAll(Collection c); boolean retainAll(Collection c); // Metode de conversie in vector Object[] toArray(); Object[] toArray(Object a[]); }
17
List
List interface control an ordered collection of objects. Accepts duplicate objects. Classes that implement that interface: AbstractList, ArrayList, LinkedList, Vector
18
19
Set
Set interface, no duplicate objects Classes that implement the interface: AbstractSet HashSet LinkedHashSet TreeSet
20
SortedSet
SortedSet interface is part of java.util package. SortedSet interface can add value, add(value) elements. Value of SortedSet can get by Iterator interface. All elements inserted into a SortedSet must implement the Comparable interface (or be accepted by the specified Comparator). Furthermore, all such elements must be mutually comparable: e1.compareTo(e2) (or comparator.compare(e1, e2)) must not throw a typeMismatchException for any elements e1 and e2 in the SortedSet
21
public interface SortedSet extends Set { // Subliste SortedSet subSet(Object fromElement, Object toElement); SortedSet headSet(Object toElement); SortedSet tailSet(Object fromElement); // Capete Object first(); Object last(); Comparator comparator(); }
22
public class SortedSetTest { public static void main(String[] args) { // Create the sorted set by a TreeSet implementation SortedSet set = new TreeSet(); // Add elements to the set set.add("b"); set.add("c"); set.add("a"); // Iterating over the elements in the set Iterator it = set.iterator(); while (it.hasNext()) { // Get element Object element = it.next(); System.out.println(element.toString()); } } }
23
Map
Map interface will use an association Key/Value (Object). The key is unique. The association is:
depending on key depending on values depending the association key/value
24
public interface Map { // Metode cu caracter general ... // Operatii la nivel de element Object put(Object key, Object value); Object get(Object key); Object remove(Object key); boolean containsKey(Object key); boolean containsValue(Object value); // Operatii la nivel de multime void putAll(Map t); // Vizualizari ale colectiei public Set keySet(); public Collection values(); public Set entrySet(); }
25
Classes that implements Map interface: AbstractMap Attributes HashMap Hashtable IdentityHashMap RenderingHints TreeMap WeakHashMap
26
public interface SortedMap extends Map { // Extragerea de subtabele SortedMap subMap(Object fromKey, Object toKey); SortedMap headMap(Object toKey); SortedMap tailMap(Object fromKey); // Capete Object first(); Object last(); // Comparatorul folosit pentru ordonare Comparator comparator(); }
27
Common Characteristics
-allows null element -are serializable -clone() method is defined -toString() method is defined -allows to create iterators -have explicit empty constructors and constructors with collections as parameters
28
29
Generic Classes
A generic class is a special type of class that associates one or more non-specified Java types upon instantiation. Here is an example of how to initialize a generic class with 2 Java types: public class Example<Type1, Type2>{ private Type1 t1; private Type2 t2;} //You may include methods that set each of the types to the types that are initiated when a new object of this class is created.
30
When working with generic types, remember the following: The types must be identified at the instantiation of the class. Your class should contain methods that set the types inside the class to the types passed into the class upon creating an object of the class.
One way to look at generic classes is by understanding what is happening behind the code.
32
public class Example<Type1, Type2>{ private Type1 t1; private Type2 t2; } This code can be interpreted as a class that creates 2 objects, Type1 and Type2. Type1 and Type2 are not the type of objects required to be passed in upon initializing an object Example, they are simply placeholders, or variable names, for the actual type that is to be passed in. Using these placeholders allows for the class to include ANY Java type; they become whatever type is initialized with the object creation. Inside of the generic class, when you create an object of Type1 or Type2, you are actually creating objects of the types initialized when an Example object is created.
33
The only difference between creating an object from a regular class versus a generics class is <String, Integer>. This is how to tell the Example class what type of objects you are using with that particular object. In other words, Type1 is a String type, and Type2 is an Integer type. The benefit to having a generic class is that you can identify multiple objects of type Example with different types given for each one, so if we wanted to we could initialize another object Example with <Double, String>. 34
public class Card{ private int value; private char suit; public Card(int r,char s) { value=r; suit=s; } }//Card public class Collection<T>{ T[] cards; int index; //You would need to also //include a constructor here public void add(T c){ cards[index]=c; index++; } public T get(int in){ return cards[in]; }}
36
Not shown: The constructors will be different when you use the generics type because you will need to initialize the instance variables using the T type.
37
Lists
A list, in Java, is an ordered collection that may contain duplicate elements. In other words, List extends Collections. Important qualities of Lists are: They grow and shrink as you add and remove objects. They maintain a specific order. They allow duplicate elements
38
ArrayLists
Until now we have been using arrays inside a collections class to create our collections interface. When you use arrays, you are restricted to the size of the array that you initiate inside the constructor. ArrayLists are very similar to arrays except that you do not need to know the size of the arraylist when you initialize it like you would an array. You may alter the size of the arraylist by adding or removing elements. The only information you need when initializing an arraylist is the object type that it stores. The following code initializes an arraylist of Cards.
ArrayList<Card> Deck = new ArrayList<Card>();
39
The ArrayList class already exists in Java, and it contains many methods including the following:
40
Sets
A Set is a collection of elements that does not contain duplicates. For example, a set of integers 1, 2, 2, 3, 5, 3, 7 would be: {1, 2, 3, 5, 7} All elements of a set must be of the same type. For example, you can not have a set that includes integers and strings. But you could have a set of integers and a separate set of strings. We've already seen how Lists, which are a collection that may contain duplicates, are implemented through ArrayLists. Similarly, Sets are commonly implemented with something called a HashSet.
41
HashSets
A HashSet is similar to an ArrayList, but does not have any specific ordering. Example Imagine you have 35 coins in a bag. There is no special ordering of these coins in this bag, but we can search the bag at any time to see if it contains a certain coin. We can add coins to the bag, we can remove coins from the bag, and we always know how many coins are in the bag. Now, think of the bag as the HashSet. There is no ordering and therefore no indexes of the coins, so we cannot increment through or sort HashSets because even if we did, with one little shake of the bag the order is lost. HashSets have no guarantee that the order will be the same throughout time. HashSets are good to use when order is not important.
42
43
Maps
A Map is a collection that links a key to a value. Similar to how an array links an index to a value, a map links a key (one object) to a value (another object). Maps, like sets, cannot contain duplicates. This means each key can only exist once and can only link to a single value. Since Map is an interface, you must use one of the classes that implement Map such as HashMap to instantiate a Map.
45
HashMaps
HashMaps are Maps that link a Key to a Value. The Key and Value can be of any type, but their types must be consistent for every element in the HashMap. Below is a generic breakdown of how to initialize a HashMap.
HashMap<KeyType,ValueType> mapName = new HashMap<KeyType,ValueType>(); Let's say we wish to group together many different fruits and wish to be able to store and later retrieve their color. The first step to do this is initializing a HashMap. HashMap<String,String> fruitBowl = new HashMap<String,String>();
46
To add fruits to our fruitBowl, simply use the put(Key,Value) function of HashMaps. Let's add a few fruits to our fruitBowl: fruitBowl.put(Apple, Red); //adds the key Apple and its value Red to the HashMap
fruitBowl.put(Orange, Orange); //adds the key Orange and its value Orange to the HashMap
fruitBowl.put(Banana, Yellow); //adds the key Banana and its value Yellow to the HashMap
47
The Key of a HashMap can be thought of as the index linked to the element (even though it does not necessarily have to be an integer) Getting the value stored is easy once we understand that the key is the index: use the get(Key) method of HashMap. Let's say we wanted to get the color of the Banana in the fruit bowl. We could do the following:
String bananaColor = fruitBowl.get(Banana); This method searches through the HashMap until it finds a Key match to the parameter (until it finds Banana) and returns the Value for that Key (returns Yellow).
48
49
Queues
A Queue is a list of elements with a First In First Out (FIFO) ordering. When you enqueue an element, it adds it to the end of the list. When you dequeue an element, it returns the element at the front of the list and removes that element from the list. Examples: Picture a line at the movie theater, the first person there is the first person to get his/her ticket.
50
Stacks
Stacks are Queues that have the reverse ordering to the standard Queue. Instead of FIFO ordering (like a queue a line at the theater), the ordering of a stack is Last In First Out (this can be represented by the acronym LIFO). Imagine you have a pile of pancakes. Typically this would be called a stack of pancakes because the pancakes are added on top of the previous leaving the most recently added pancake at the top of the stack. To remove a pancake, you would have to take off the one that was most recently added the pancake on the top of the stack. If you tried to remove the pancake that was added first, you would most likely make a very large mess.
51
LinkedLists
A LinkedList is a list of elements that is dynamically stored. Like an ArrayList, it changes size and has an explicit ordering. But it doesnt use an array to store information. It uses an object known as a Node. Nodes are like roadmaps: they tell you where you are (the element you are looking at), and where you can go (the previous element and the next element).
53
Ultimately, we have a list of Nodes, which point to other Nodes and have an element attached to them. When we want to add a Node, we simply set its left Node to the one on its left, and its right Node to the one on its right. But dont forget to change the Nodes around it too! Let's say we wanted to add a 4th node to the end of this linked list.
54
A LinkedList is initialized in the same way as ArrayLists. The following code shows how to initialize a linked list of pancakes. LinkedList<Pancake> myStack = new LinkedList<Pancake>();
55
Enumerations
Enumerations (or enums) are a specification for a class where all instances of the class are created within the class. For example, say we wish to create a class Planet. We already know all of the planets in our solar system (Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, and Neptune Pluto is no longer considered a planet ). As long as we specify that the class is of type enum we can create these planets inside the class itself as if each was created outside of the class. Enums are good to use when you already know all possibilities of the class. The next few slides show the Planet class.
56
public enum Planet{ MERCURY(3.303E23,2.4397E6), VENUS(4.869E24,6.0518E6), EARTH(5.976E24,3.3781E6), MARS(6.421E23,3.3972E6), JUPITER(1.900E27,7.1492E7), SATURN(5.688E26,6.0268E7), URANUS(8.686E25,2.5559E7), NEPTUNE(1.024E26,2.4746E7); private final double mass; private final double radius; Planet(double m,double r){ //Each Planet has a constructor telling its mass and radius mass=m; radius=r; }
57
public double mass(){return mass;} //Its information is private, need methods to get the contents public double radius(){return radius;} public static final double G = 6.67300e-11; //G is used to calculate surface gravity public double surfaceGravity(){ //Surface gravity times a mass in kg equals weight on this return G*mass/(radius*radius); //Planets surface } public double surfaceWeight(double m){ return m*surfaceGravity(); } 58 }//Planet