Generic Collections Java Core презентация

Содержание


Презентации» Информатика» Generic Collections Java Core
Generic Collections
 Java CoreAgenda
 Wrapper Pattern
 Generic in Java
 Arrays in Java
 Collections inWrapper Pattern
 Non-generic Box class
 public class Box {
  privateWrapper Pattern
 public class Appl {
  public static void main(String[Wrapper Pattern
 Wrapper (or Decorator) is one of the most importantWrapper Pattern
 public class Appl {
  public static void main(String[Generic in Java
 Generics, introduced in Java SE 5.0
 A genericGeneric in Java
 To update the Box class to use generics,Generic in Java
 public class Box<T> {
   // TGeneric in Java
 public class Appl {
  public static voidGeneric in Java
 Java method can be parametrized, too: 
 	<T>Generic in Java
 Disadvantages
 Generic-fields can not be static.
 Static methodsArrays in Java
 class Car{ }; 			// minimal dummy class
 Car[Arrays in Java
 Most efficient way to hold references to objects.
Collections in Java
 Collection is a container of Objects, it groupsBenefits of collections
 reduces programming effort
 increases program speed and quality
Wrappers
 For all primitive types in Java are correspond type-wrappers (objectInterfaces
 There are data types that represent collections.
 Classes that implementCollections in Java
 The interface Collection<E> defined methods: 
 boolean add(ECollections in Java
 boolean isEmpty() – returns true, if the collectionInterfacesCollections in Java
 List – a list of objects. Objects canImplementations
 There are the implementations of the collection interfaces. In essence,List
 Since List is an interface you need to instantiate aArrayList
 Adding elements
 List list = new ArrayList();
 list.add("First element");
 list.add("SecondIterator
 Iterator – a helper object. Used to iterate over collectionArrayList
 Removing Elements
 	remove(Object element)
 	remove(int index)
 Cleaning a list
 	list.clear();
LinkedList
 LinkedList has the same functionality as the ArrayList.
 Different wayExample
 public static void main (String[ ] args) {
  Set
 A Set is a collection that does not contain anyExample
 import java.util.*;
 public class FindDups {
   public staticWrapper
 public class MyList {
   private ArrayList v =Sorting
 public static void main(String[] args) {
    int[]Class Arrays. Sorting
 import java.util.Arrays;
 public class Appl {
  Compare elements
 To specify the order of the following interfaces: ComparableCompare elements
 Comparator interface has two methods
   public intExample 1Example 1Example 1Example 2
 public class Employee {
   int tabNumber; 
Example 2
 static class NameComparator implements Comparator {
  public intExample 2
 public static void main(String[] args) {
 Set<Employee> set =Map
 The most commonly used Map implementations are HashMap and TreeMap.
MapPractical task 1
 Declare collection myCollection of 10 integers and fillPractical task 2
 In the main() method declare map employeeMap ofHomework
 Write parameterized methods union(Set set1, Set set2) and intersect(Set set1,Homework
 Write class Student that provides information about the name ofThe end



Слайды и текст этой презентации
Слайд 1
Описание слайда:
Generic Collections Java Core


Слайд 2
Описание слайда:
Agenda Wrapper Pattern Generic in Java Arrays in Java Collections in Java List, Set, Map Iterators Methods, sorting Practical tasks

Слайд 3
Описание слайда:
Wrapper Pattern Non-generic Box class public class Box { private Object obj; public void set(Object obj) { this.obj = obj; } public Object get( ) { return obj; } } Since its methods accept or return an Object, you are free to pass in whatever you want, provided that it is not one of the primitive types. There is no way to verify, at compile time, how the class is used.

Слайд 4
Описание слайда:
Wrapper Pattern public class Appl { public static void main(String[ ] args) { String text = "Hello World"; Box box = new Box(); box.set(text); Integer i = (Integer) box.get(); } } One part of the code may place an Integer in the box and expect to get Integers out of it, while another part of the code may mistakenly pass in a String, resulting in a runtime error.

Слайд 5
Описание слайда:
Wrapper Pattern Wrapper (or Decorator) is one of the most important design patterns. One class takes in another class, both of which extend the same abstract class, and adds functionality. public class WrapperBox { private Box box = new Box(); public void set(String text) { this.box.set(text); } public String get( ) { return box.get(); } }

Слайд 6
Описание слайда:
Wrapper Pattern public class Appl { public static void main(String[ ] args) { String text = "Hello World"; WrapperBox box = new WrapperBox(); box.set(text); Integer i = (Integer) box.get(); } } The basic idea of a wrapper is to call-forward to an underlying object, while simultaneously allowing for new code to be executed just before and/or just after the call.

Слайд 7
Описание слайда:
Generic in Java Generics, introduced in Java SE 5.0 A generic type is a generic class or interface that is parameterized over types. Generics add a way to specify concrete types to general purpose classes and methods that operated on Object before. With Java's Generics features you can set the type for classes. Generic class is defined with the following format: class Name<T1, T2, ..., Tn> { /* ... */ } The type parameter section, delimited by angle brackets (<>), follows the class name.

Слайд 8
Описание слайда:
Generic in Java To update the Box class to use generics, you create a generic type declaration by changing the code public class Box to public class Box<T> This introduces the type variable, T, that can be used anywhere inside the class. To instantiate this class, use the new keyword, as usual, but place <Integer> between the class name and the parenthesis: Box<Integer> integerBox = new Box<Integer>();

Слайд 9
Описание слайда:
Generic in Java public class Box<T> { // T stands for "Type". private T t; public void set(T t) { this.t = t; } public T get( ) { return t; } } All occurrences of Object are replaced by T. A type variable can be any non-primitive type you specify: any class type, any interface type, any array type, or even another type variable. The same technique can be applied to create generic interfaces.

Слайд 10
Описание слайда:
Generic in Java public class Appl { public static void main(String[ ] args) { String text = "Hello World"; Box<String> box = new Box<String>(); box.set(text); Integer i = (Integer) box.get(); } } Generics also provide compile-time type safety that allows programmers to catch invalid types at compile time.

Слайд 11
Описание слайда:
Generic in Java Java method can be parametrized, too: <T> getRandomElement(List<T> list) { … } As with class definitions, you often want to restrict the type parameter in the method. For example, a method which takes a list of Vehicles and returns the fastest vehicle in the list can have the following type. <T extends Vehicle> T getFastest(List<T> list) {…}

Слайд 12
Описание слайда:
Generic in Java Disadvantages Generic-fields can not be static. Static methods can not have generic parameters or use generic fields. Can not be made an explicit call to the constructor generic-type: class Optional<T> { T value = new T(); } The compiler does not know what constructor can be caused and the amount of memory to be allocated when an object.

Слайд 13
Описание слайда:
Arrays in Java class Car{ }; // minimal dummy class Car[ ] cars1; // null reference Car[ ] cars2 = new Car[10]; // null references for (int i = 0; i < cars2.length; i++) { cars2[i] = new Car( ); } // Aggregated initialization Car[ ] cars3 = {new Car( ), new Car( ), new Car( )}; cars1 = {new Car( ), new Car( ), new Car( )};

Слайд 14
Описание слайда:
Arrays in Java Most efficient way to hold references to objects. Advantages An array know the type it holds, i.e., compile-time type checking. An array knows its size, i.e., ask for the length. An array can hold primitive types directly. Disadvantages An array can only hold one type of objects (including primitives). Arrays are fixed size. How to add element inside?

Слайд 15
Описание слайда:
Collections in Java Collection is a container of Objects, it groups many Objects into a single one. Collections – dynamic arrays, linked lists, trees, sets, hash tables, stacks, queues. All collections frameworks contain the following: interfaces implementations algorithms (there are the methods such as searching and sorting)

Слайд 16
Описание слайда:
Benefits of collections reduces programming effort increases program speed and quality allows interoperability among unrelated APIs reduce effort to design new APIs helps to reuse the code

Слайд 17
Описание слайда:
Wrappers For all primitive types in Java are correspond type-wrappers (object types):

Слайд 18
Описание слайда:
Interfaces There are data types that represent collections. Classes that implement interfaces List<E> and Set<E>, implement the interface Iterable<E>.

Слайд 19
Описание слайда:
Collections in Java The interface Collection<E> defined methods: boolean add(E obj) – adds obj to the collection, it returns true, if the object is added; boolean addAll(Collection<? extends E> c) – adds all the elements; void clear() – removes all items from the collection; boolean contains(Object obj) – returns true, if the collection contains an element of obj; boolean equals(Object obj) – returns true, if the collections are equivalent;

Слайд 20
Описание слайда:
Collections in Java boolean isEmpty() – returns true, if the collection is empty; Iterator<E> iterator() – retrieves the iterator; boolean remove(Object obj) – removes the object from the collection; int size() – the number of items in the collection; Object[] toArray() – copies the collection to an array of objects; <T>T[] toArray(T a[]) – copies the elements of the collection to an array of objects of a particular type.

Слайд 21
Описание слайда:
Interfaces

Слайд 22
Описание слайда:
Collections in Java List – a list of objects. Objects can be added to the list (the method add()), replace the list (method set()), removed from the list (the method remove()), extract (method get()). There the ability to pass on the list of organizations with an iterator. Set – a set of objects. The same features as that of the List, but the object can be part of set only once. Double addition of one and the same object in the set is not change the set. Map – a map or associative array. In Map we add pair of objects (key, value). Accordingly, the search operation is a key value. Adding a couple with an existing key in the Map leads to the replacement, not to upload it. From Map can be obtain key and a list of values.

Слайд 23
Описание слайда:
Implementations There are the implementations of the collection interfaces. In essence, they are reusable data structures

Слайд 24
Описание слайда:
List Since List is an interface you need to instantiate a concrete implementation of the interface in order to use it. There are two general-purpose List implementations — ArrayList and LinkedList For example java.util.ArrayList java.util.LinkedList Here are a few examples of how to create a List instance: List listArr = new ArrayList(); List listLink = new LinkedList();

Слайд 25
Описание слайда:
ArrayList Adding elements List list = new ArrayList(); list.add("First element"); list.add("Second element"); list.add(0, "One more first element"); Access through index String element2 = list.get(1); Access through new for-loop for(Object object : list) { String element = (String) object; }

Слайд 26
Описание слайда:
Iterator Iterator – a helper object. Used to iterate over collection of objects. Iterators are based on the interface boolean hasNext() – checks whether there are elements in the collection Object next() – shows the next item in the collection void remove() – removes the last selected item from the collection. Collection interface has a method Iterator iterator(); Access through iterator Iterator iterator = list.iterator(); while(iterator.hasNext(){ String element = (String) iterator.next(); }

Слайд 27
Описание слайда:
ArrayList Removing Elements remove(Object element) remove(int index) Cleaning a list list.clear(); List size int size = list.size(); Generic List List<MyType> myType = new ArrayList<MyType>( ); myType.add(new MyType( )); MyType my = myType.get(0);

Слайд 28
Описание слайда:
LinkedList LinkedList has the same functionality as the ArrayList. Different way of implementation and efficiency of operations. Adding to the LinkedList is faster Pass through the list is almost as effective as the ArrayList, Arbitrary removal from the list is slower than ArrayList.

Слайд 29
Описание слайда:
Example public static void main (String[ ] args) { ArrayList cars = new ArrayList( ); for (int i = 0; i < 12; i++) { cars.add (new Car( )); } Iterator it = cars.iterator( ); while (it.hasNext( )) { System.out.println ((Car)it.next( )); } }

Слайд 30
Описание слайда:
Set A Set is a collection that does not contain any duplicate element. Element that are put in a set must override equals() method to establish uniqueness It is unsorted, unordered Set Can contain null

Слайд 31
Описание слайда:
Example import java.util.*; public class FindDups { public static void main(String args[ ]){ Set s = new HashSet( ); for (int i = 0; i < args.length; i++) { if (!s.add(args[i])) System.out.println("Duplicate detected: " + args[i]); } System.out.println(s.size( ) + " distinct words detected: " + s); } }

Слайд 32
Описание слайда:
Wrapper public class MyList { private ArrayList v = new ArrayList( ); public void add(MyType obj) { v.add(obj); } public MyType get(int index) { return (MyType)v.get(index); } public int size( ) { return v.size( ); } }

Слайд 33
Описание слайда:
Sorting public static void main(String[] args) { int[] x = new int[10]; for (int i = 0; i < x.length; i++) { Random rand = new Random(); x[i] = rand.nextInt(10); } Arrays.sort(x); for (int i = 0; i < x.length; i++) { System.out.println(x[i]); } } What is wrong in the code Write a new code for type double, etc. Do I need to constantly create "bicycle" ? You may use an existing solution

Слайд 34
Описание слайда:
Class Arrays. Sorting import java.util.Arrays; public class Appl { public static void main(String[ ] args) { Student[ ] students = new Student[3]; students[0] = new Student(52645, "Oksana"); students[1] = new Student(98765, "Bogdan"); students[2] = new Student(1354, "Orest"); Arrays.sort(students); for (int i = 0; i < students.length; i++) { System.out.println(students); } } }

Слайд 35
Описание слайда:
Compare elements To specify the order of the following interfaces: Comparable and Comparator public class MyType implements Comparable { String name; public int compareTo(Object obj) { return name.compareTo(((MyType)obj).name); } } Comparable to specify only one order. Method compareTo can return 0, if objects are equal <0 (-1), if first object is less than second object >0 (1), if first object is great than second object

Слайд 36
Описание слайда:
Compare elements Comparator interface has two methods public int compare(Object o1, Object o2) // and public boolean equals(Object obj) Methods compareTo and compare can throw an exception ClassCastException, if the object types are not compatible in the comparison.

Слайд 37
Описание слайда:
Example 1

Слайд 38
Описание слайда:
Example 1

Слайд 39
Описание слайда:
Example 1

Слайд 40
Описание слайда:
Example 2 public class Employee { int tabNumber; String name; static NameComparator nameComparator = new NameComparator( ); static TabComparator tabComparator = new TabComparator(); public static Comparator getNameComparator( ) { return nameComparator; } public static Comparator getTabComparator( ) { return tabComparator; }

Слайд 41
Описание слайда:
Example 2 static class NameComparator implements Comparator { public int compare(Object o1, Object o2) { return ((Employer)o1).name.compareTo(((Employer)o2).name); } } static class TabComparator implements Comparator { public int compare(Object o1, Object o2) { return ((Employer)o1).tabNumber – ((Employer)o2).tabNumber; } } . . . }

Слайд 42
Описание слайда:
Example 2 public static void main(String[] args) { Set<Employee> set = new TreeSet(Employee.getNameComparator()); set.add(new Employee(15, "Vasya")); set.add(new Employee(2, "Anna")); set.add(new Employee(40, "Alina")); System.out.println(set); Set<Employee> set1 = new TreeSet(Employee.getTabComparator()); set1.addAll(set); System.out.println(set1); }

Слайд 43
Описание слайда:
Map The most commonly used Map implementations are HashMap and TreeMap. Map mapA = new HashMap(); Map mapB = new TreeMap(); Adding elements mapA.put("key1", "one"); mapA.put("key2", "two"); String value2 = (String) mapA.get("key2"); Removing element mapA.remove(Object key);

Слайд 44
Описание слайда:
Map

Слайд 45
Описание слайда:
Practical task 1 Declare collection myCollection of 10 integers and fill it (from the console or random). Find and save in list newCollection all positions of element more than 5 in the collection. Print newCollection Remove from collection myCollection elements, which are greater then 20. Print result Insert elements 1, -3, -4 in positions 2, 8, 5. Print result in the format: “position – xxx, value of element – xxx” Sort and print collection Use next Collections for this tasks: List, ArrayList, LinkedList

Слайд 46
Описание слайда:
Practical task 2 In the main() method declare map employeeMap of pairs <Integer, String>. Add to employeeMap seven pairs (ID, name) of some persons. Display the map on the screen. Ask user to enter ID, then find and write corresponding name from your map. If you can't find this ID - say about it to user (use function containsKey()). Ask user to enter name, verify than you have name in your map and write corresponding ID. If you can't find this name - say about it to user (use function containsValue()).

Слайд 47
Описание слайда:
Homework Write parameterized methods union(Set set1, Set set2) and intersect(Set set1, Set set2), realizing the operations of union and intersection of two sets. Test the operation of these techniques on two pre-filled sets. Create map personMap and add to it ten persons of type <String, String> (lastName, firstName). Output the entities of the map on the screen. There are at less two persons with the same firstName among these 10 people? Remove from the map person whose firstName is ”Orest” (or other). Print result.

Слайд 48
Описание слайда:
Homework Write class Student that provides information about the name of the student and his course. Class Student should consists of properties for access to these fields constructor with parameters method printStudents (List students, Integer course), which receives a list of students and the course number and prints to the console the names of the students from the list, which are taught in this course (use an iterator) methods to compare students by name and by course In the main() method declare List students and add to the list five different students display the list of students ordered by name display the list of students ordered by course.

Слайд 49
Описание слайда:
The end


Скачать презентацию на тему Generic Collections Java Core можно ниже:

Похожие презентации