1 / 5

Generic types for ArrayList

Generic types for ArrayList. Old Java (1.4 and older): ArrayList strings = new ArrayList(); strings.enqueue( “ hello ” ); String word = (String) strings.get(0); New (since 1.5): ArrayList<String> strings = new ArrayList <String>(); strings.add( “ hello ” );

clintonk
Download Presentation

Generic types for ArrayList

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. Generic types for ArrayList • Old Java (1.4 and older): ArrayList strings = new ArrayList(); strings.enqueue(“hello”); String word = (String) strings.get(0); • New (since 1.5): ArrayList<String> strings = new ArrayList <String>(); strings.add(“hello”); String word = strings.get(0);

  2. Advantages • Better readability • Better type-safety: no casts (runtime checks), compiler can catch problems

  3. Writing your own generic code • Formal type parameter public class Stack<E> { … } • convention: Short (single-char) uppercase • can be used wherever a Type is needed • will be replaced with actual Type

  4. Writing your own generic class public class Stack<E> { public void push(E element) { contents.add(element); } public E pop() { int top = contents.size()-1; E result = contents.get(top); contents.remove(top); return result; } private ArrayList<E> contents = new ArrayList<E>(); }

  5. Using your genetic class Stack<Student> students = new Stack<Student>();

More Related