1 / 9

CS 211 Generics

CS 211 Generics. Today’s lecture. Review of generics Go over examples. Generics. What problem does using generics solve? What do they look like? What do they mean?. Problem: "lost" types.

teresa
Download Presentation

CS 211 Generics

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CS 211Generics

  2. Today’s lecture • Review of generics • Go over examples

  3. Generics • What problem does using generics solve? • What do they look like? • What do they mean?

  4. Problem: "lost" types • This issue would always arise when we remove things from the ArrayList. It's even more annoying with the for-each syntax:ArrayListpersonList = new ArrayList();// add many Person objects//NOT ALLOWED: for (Person p : personList) {p.whatever(); } • Instead, we must cast later, like this: // allowed, but annoying, harder to read, and error-prone. for (Object p : personList){ ((Person) p).whatever(); }

  5. Declaring Generic Types We can add a generic type to a class definition: public class Foo <T> { // T can be any where: like field types.public T someField; public Foo(T t) {this.someField = t; } // can use T now for return types and param types. public TdoStuff(T t, int x) { … }}

  6. Generics Example: ArrayList Here is an idealized definition of ArrayList. Fake versions are marked with †. public class ArrayList<E> { private int size; private E[] items; public ArrayList(){ items = new E[10]; //† size = 0; } public E get(inti) { return items[i]; } public void set(inti, E e) { items[i] = e; } public void add (E e) { if (size>=items.length) { E[] longer = new E[items.length*2]; //† for (inti=0; i<items.length; i++){ longer[i] = items[i]; } items = longer; } items[size++] = e; } }

  7. Generics Example: ArrayList Let's look at how we actually get to use generics with ArrayList:→ we need to instantiate the class's type parameter: //instantiate the type parameter with <>'s: ArrayList<String>slist = new ArrayList<String>(); //now use all methods without having to specify again. slist.add("hello"); slist.add("goodbye"); String elt = slist.get(0); System.out.println("some element: " + elt); System.out.println("the list: " + slist);

  8. Let’s go over the examples

  9. Questions?

More Related