Upgrade to Pro — share decks privately, control downloads, hide ads and more …

CSE205 Lecture 18

CSE205 Lecture 18

Object-Oriented Programming and Data Structures
Generics
(202204)

Javier Gonzalez-Sanchez

September 28, 2021
Tweet

More Decks by Javier Gonzalez-Sanchez

Other Decks in Programming

Transcript

  1. jgs CSE 205 Object-Oriented Programming and Data Structures Lecture 18:

    Generic-Data Types Dr. Javier Gonzalez-Sanchez [email protected] javiergs.engineering.asu.edu | javiergs.com PERALTA 230U Office Hours: By appointment
  2. Javier Gonzalez-Sanchez | CSE205 | Fall 2021 | 16 jgs

    I introduce you a List, a Linked List
  3. Javier Gonzalez-Sanchez | CSE205 | Fall 2021 | 23 jgs

    Definition § Generics or parameterized types. § The idea is to allow type (Integer, String, … etc., and user-defined types) to be a parameter to methods, classes, and interfaces. § Using Generics, it is possible to create classes that work with different data types. § An entity such as class, interface, or method that operates on a parameterized type is called a generic entity.
  4. Javier Gonzalez-Sanchez | CSE205 | Fall 2021 | 24 jgs

    Case 1 class Test<T> { T obj; Test(T obj) { obj = obj; } public T getObject() { return obj; } } class Main { public static void main(String[] args) { Test<Integer> iObj = new Test<Integer>(15); System.out.println(iObj.getObject()); Test<String> sObj = new Test<String>("Hello World!"); System.out.println(sObj.getObject()); } } // we can not use primitives like int, char or double.
  5. Javier Gonzalez-Sanchez | CSE205 | Fall 2021 | 25 jgs

    Case 2 public class GenericMethodTest { public static <E> void printArray( E[] inputArray ) { for(int i=0; i<inputArray.length;i++) { System.out.print(""+ inputArray[i]); } System.out.println(); } public static void main(String args[]) { Integer[] intArray = { 1, 2, 3, 4, 5 }; Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4 }; Character[] charArray = { 'H', 'E', 'L', 'L', 'O' }; System.out.println("Array integerArray contains:"); printArray(intArray); System.out.println("\nArray doubleArray contains:"); printArray(doubleArray); System.out.println("\nArray characterArray contains:"); printArray(charArray); } }
  6. Javier Gonzalez-Sanchez | CSE205 | Fall 2021 | 26 jgs

    Case 3 class Test<T, U> { T obj1; // An object of type T U obj2; // An object of type U Test(T obj1, U obj2) { this.obj1 = obj1; this.obj2 = obj2; } public void print() { System.out.println(obj1); System.out.println(obj2); } } class Main { public static void main (String[] args) { Test <String, Integer> obj = new Test<String, Integer>(”ABC", 15); obj.print(); }
  7. jgs CSE 205 Object-Oriented Programming and Data Structures Javier Gonzalez-Sanchez,

    Ph.D. [email protected] Fall 2021 Copyright. These slides can only be used as study material for the class CSE205 at Arizona State University. They cannot be distributed or used for another purpose.