30
Big Java Big Java Chapters 17-18 Chapters 17-18 (ArrayList / Generic) (ArrayList / Generic)

Big Java Chapters 17-18 (ArrayList / Generic). Generic Programming The design and implementation of data structures and algorithms that work for multiple

Embed Size (px)

Citation preview

Page 1: Big Java Chapters 17-18 (ArrayList / Generic). Generic Programming The design and implementation of data structures and algorithms that work for multiple

Big JavaBig JavaChapters 17-18Chapters 17-18

(ArrayList / Generic)(ArrayList / Generic)

Page 2: Big Java Chapters 17-18 (ArrayList / Generic). Generic Programming The design and implementation of data structures and algorithms that work for multiple

Generic ProgrammingGeneric Programming

• The design and implementation of data structures and algorithms that work for multiple types.

Page 3: Big Java Chapters 17-18 (ArrayList / Generic). Generic Programming The design and implementation of data structures and algorithms that work for multiple

Generic ClassGeneric Class

• Uses a type variable to achieve genericity

public class ArrayList<E>

{

public ArrayList() { . . .}

public void add(E element) { . . . }

}

may have one or more

Can instantiate type variable with class orinterface type, not primitive (use wrapper)

Page 4: Big Java Chapters 17-18 (ArrayList / Generic). Generic Programming The design and implementation of data structures and algorithms that work for multiple

ExampleExample

ArrayList<BankAccount> accounts1 = new ArrayList<BankAccount>();

LinkedList accounts2 = new LinkedList();

// intended for BankAccounts

accounts1.add(“my savings”);

// compiler error – WHY ?

accounts2.add(“my savings”);

// not detected

Page 5: Big Java Chapters 17-18 (ArrayList / Generic). Generic Programming The design and implementation of data structures and algorithms that work for multiple

Names for Type VariablesNames for Type Variables

• Often use short uppercase names, such as:

Type Name Meaning

E Element in collection

K Key type in map

V Value type in map

T General type

S,U Additional general types

Page 6: Big Java Chapters 17-18 (ArrayList / Generic). Generic Programming The design and implementation of data structures and algorithms that work for multiple

Example – useful return typeExample – useful return typepublic class Pair<T, S>{ public Pair(T firstElement, S, second Element) {

first = firstElement;second = second Element

} public T getFirst() { return first; } public S getSecond() { return second; } private T first; private S second; }

Page 7: Big Java Chapters 17-18 (ArrayList / Generic). Generic Programming The design and implementation of data structures and algorithms that work for multiple

Generic MethodsGeneric Methods

• Method with a type variable• Useful for methods that differ only by

one or more types• Can start with method that works on

a specific types, then make generic

Page 8: Big Java Chapters 17-18 (ArrayList / Generic). Generic Programming The design and implementation of data structures and algorithms that work for multiple

Generic Method ExampleGeneric Method Examplepublic static void print(String[] a){ for (String e : a) System.out.print(e + “ “); System.out.println();}

public static <E> void print(E[] a){ for (E e : a) System.out.print(e + “ “); System.out.println();}Rectangle[] rectangles = . . .;ArrayUtil.print(rectangles);

Method call based on parameters,doesn’t specify E explicitly

Assume in ArrayUtil class

Methods are not required to be static

Page 9: Big Java Chapters 17-18 (ArrayList / Generic). Generic Programming The design and implementation of data structures and algorithms that work for multiple

Constraining Type VariablesConstraining Type Variables

public static <E extends Comparable> E min(E[] a){ E smallest = a[0]; for (int i=0; i<a.length; i++) if (a[i].compareTo(smallest) < 0) smallest = a[i]; return smallest;}

could also do:<E extends Comparable & Cloneable>

if have more than one constraint

actually means extends or implements

Page 10: Big Java Chapters 17-18 (ArrayList / Generic). Generic Programming The design and implementation of data structures and algorithms that work for multiple

Genericity and InheritanceGenericity and Inheritance

• If SavingsAccount is a subclass of BankAccount, is ArrayList<SavingsAccount> a subclass of ArrayList<BankAccount>?

• NO. Necessary for type checking.

ArrayList<SavingsAccount> savingsAccounts =

new ArrayList<SavingsAccount>();

ArrayList<BankAccount> bankAccounts = savingsAccounts; // Not legal, but if it were…

BankAccount myChecking = new CheckingAccount();

BankAccounts.add(myChecking);

// just added checking account to savings account list

Page 11: Big Java Chapters 17-18 (ArrayList / Generic). Generic Programming The design and implementation of data structures and algorithms that work for multiple

Wildcard Types – Advanced TopicWildcard Types – Advanced Topic

• A wildcard type is a type that can remain unknown.

public void addAll(LinkedList<? extends E> other)

{

ListIterator<E> iter = other.listIterator();

while (iter.hasNext())

add(iter.next());

}

• Allows you to add any type that is a subtype of E.• Read Advanced Topic 17.1 for more details

Page 12: Big Java Chapters 17-18 (ArrayList / Generic). Generic Programming The design and implementation of data structures and algorithms that work for multiple

Raw TypesRaw Types

• The Java Virtual Machine (JVM) uses raw types in which type variables are replaced with ordinary types

• The compiler converts generic classes and type variables into regular classes/raw types for the JVM

• Type variables are replaced with Object, e.g., public Pair(Object firstElement, Object secondElement) { … }

• Type erasure enables generic classes to interoperate with legacy code (e.g., original ArrayList).

Page 13: Big Java Chapters 17-18 (ArrayList / Generic). Generic Programming The design and implementation of data structures and algorithms that work for multiple

LimitationsLimitations

• You cannot use type variables to define static fields, static methods or static inner classes

• You cannot create a new object of a type variable type (remember it is replaced with Object)

Page 14: Big Java Chapters 17-18 (ArrayList / Generic). Generic Programming The design and implementation of data structures and algorithms that work for multiple

Graphical User Interfaces…

Page 15: Big Java Chapters 17-18 (ArrayList / Generic). Generic Programming The design and implementation of data structures and algorithms that work for multiple

BorderLayoutBorderLayout

JPanel panel = new JPanel();

panel.setLayout(new BorderLayout());

panel.add(component, BorderLayout.NORTH);

NORTH

SOUTH

CENTER EASTWEST

Page 16: Big Java Chapters 17-18 (ArrayList / Generic). Generic Programming The design and implementation of data structures and algorithms that work for multiple

GridLayoutGridLayout

JPanel buttonPanel = new JPanel();

buttonPanel.setLayout(new GridLayout(4, 3));

buttonPanel.add(button7);

buttonPanel.add(button8);

7 8 9

4 5 6

1 2 3

0 . CE

Page 17: Big Java Chapters 17-18 (ArrayList / Generic). Generic Programming The design and implementation of data structures and algorithms that work for multiple

Nesting PanelsNesting PanelsJPanel keypadPanel = new JPanel();keypadPanel.setLayout(new BorderLayout());JPanel buttonPanel = new JPanel();buttonPanel.setLayout(new GridLayout(4, 3));buttonPanel.add(button7);buttonPanel.add(button8); …keypadPanel.add(buttonPanel, BorderLayout.CENTER);JTextField display = new JTextField();keypadPanel.add(display, BorderLayout.NORTH);

7 8 94 5 61 2 30 . CE

Page 18: Big Java Chapters 17-18 (ArrayList / Generic). Generic Programming The design and implementation of data structures and algorithms that work for multiple

Making Choices – Radios, Combos & Making Choices – Radios, Combos & ChecksChecks

Page 19: Big Java Chapters 17-18 (ArrayList / Generic). Generic Programming The design and implementation of data structures and algorithms that work for multiple

Combo BoxCombo Box

editable – can type inyour own selection

Page 20: Big Java Chapters 17-18 (ArrayList / Generic). Generic Programming The design and implementation of data structures and algorithms that work for multiple

Check Box & BorderCheck Box & Border

Many other border typesavailable – see API

Page 21: Big Java Chapters 17-18 (ArrayList / Generic). Generic Programming The design and implementation of data structures and algorithms that work for multiple

Radio ButtonsRadio Buttons

Need ButtonGroup forgrouping, only one selected at a time

Page 22: Big Java Chapters 17-18 (ArrayList / Generic). Generic Programming The design and implementation of data structures and algorithms that work for multiple

Control Panel for All ControlsControl Panel for All Controls

It’s easy once theother panels are created!

controls are going inthe bottom

Page 23: Big Java Chapters 17-18 (ArrayList / Generic). Generic Programming The design and implementation of data structures and algorithms that work for multiple

Controlling the FontControlling the Font

access check boxes to determine bold/italic settings

access radio buttons todetermine size settings – sometimesseparate field is used for this

repaint causes changes to bevisible

access combo box for font name

Page 24: Big Java Chapters 17-18 (ArrayList / Generic). Generic Programming The design and implementation of data structures and algorithms that work for multiple

Putting it togetherPutting it together

Same listener forall components

Page 25: Big Java Chapters 17-18 (ArrayList / Generic). Generic Programming The design and implementation of data structures and algorithms that work for multiple

Reading AssignmentReading Assignment

• How To 18.1 Laying Out a User Interface, pages 799-801 – summarizes how to achieve an interface

Page 26: Big Java Chapters 17-18 (ArrayList / Generic). Generic Programming The design and implementation of data structures and algorithms that work for multiple

MenusMenus

Page 27: Big Java Chapters 17-18 (ArrayList / Generic). Generic Programming The design and implementation of data structures and algorithms that work for multiple

File MenusFile Menus

Creates menu item

Creates menu itemwith listener

Page 28: Big Java Chapters 17-18 (ArrayList / Generic). Generic Programming The design and implementation of data structures and algorithms that work for multiple

Menu and ItemMenu and Item

Page 29: Big Java Chapters 17-18 (ArrayList / Generic). Generic Programming The design and implementation of data structures and algorithms that work for multiple

Setting FontSetting Font

Note use of instancevariables for size,facename and style

Page 30: Big Java Chapters 17-18 (ArrayList / Generic). Generic Programming The design and implementation of data structures and algorithms that work for multiple

Putting it all TogetherPutting it all Together

Create a JMenuBarand add menus to it