Upload
priscilla-mclaughlin
View
232
Download
0
Embed Size (px)
Citation preview
Big JavaBig JavaChapters 17-18Chapters 17-18
(ArrayList / Generic)(ArrayList / Generic)
Generic ProgrammingGeneric Programming
• The design and implementation of data structures and algorithms that work for multiple types.
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)
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
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
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; }
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
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
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
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
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
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).
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)
Graphical User Interfaces…
BorderLayoutBorderLayout
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.add(component, BorderLayout.NORTH);
NORTH
SOUTH
CENTER EASTWEST
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
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
Making Choices – Radios, Combos & Making Choices – Radios, Combos & ChecksChecks
Combo BoxCombo Box
editable – can type inyour own selection
Check Box & BorderCheck Box & Border
Many other border typesavailable – see API
Radio ButtonsRadio Buttons
Need ButtonGroup forgrouping, only one selected at a time
Control Panel for All ControlsControl Panel for All Controls
It’s easy once theother panels are created!
controls are going inthe bottom
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
Putting it togetherPutting it together
Same listener forall components
Reading AssignmentReading Assignment
• How To 18.1 Laying Out a User Interface, pages 799-801 – summarizes how to achieve an interface
MenusMenus
File MenusFile Menus
Creates menu item
Creates menu itemwith listener
Menu and ItemMenu and Item
Setting FontSetting Font
Note use of instancevariables for size,facename and style
Putting it all TogetherPutting it all Together
Create a JMenuBarand add menus to it