You are on page 1of 28

Slido

Vectors
CS 2100
Data Structures and Algorithms 1
Briana B. Morrison
Announcements
Lab:
• Quiz 2B Monday

Assignments:
• Assignment 4 Blackjack due today
• Assignment 5 Vector releases tomorrow
Other:
• Quiz 2A on Friday
• Review Thursday at 7pm in Olsson 005
slido.com #3491501
Today’s plan

VECTORS GENERIC CLASSES


slido.com #3491501
Abstract
• Means… this is the idea. You provide the implementation.
• A class that is abstract cannot be instantiated.
• If a class has any abstract methods, the entire class is abstract.
It cannot be instantiated
• A method that is abstract must have a concrete
implementation provided for it in a sub-class.
• Java compiler can verify required abstract methods are
overridden
• An abstract class can provide a default implementation for non-
abstract methods. (read: you can inherit concrete methods from
an abstract parent)

slido.com #3491501
List Interface

slido.com #3491501
Vectors Are
• A type of List
• Keeps things in order
• Allows random access
• A “resizable array” - stores data in an array but hides the need to
resize
• Maintains a ‘capacity’ // how many spaces
• Maintains a ‘capacityIncrement’ // how much to grow or
shrink when required
• Re-sizes as necessary as items are added
• Concrete classes provided by Java are the ArrayList and Vector
classes
• You will implement a limited Vector as HW 5
slido.com #3491501
Vector Performance
• A vector is a finite sequence of items such that:
1. Given any index, the item in the sequence at that index can be accessed or
modified in constant time.
2. An insertion or deletion at the back of the sequence takes only constant
time, on average.
capacity = n
capacityIncrement = 10
size =
0 1 2 3 4 … … … n-1 n

slido.com #3491501
Using Vectors

• Vectors make use of generic typing. This feature allows Java to type check the contents of a
container. Declare the type (must be a reference type) in angle brackets:
• Vector<Integer> list1 = new Vector<Integer>();
• ArrayList<Double> list2 = new ArrayList<Double>();

• Vector<Integer> will accept data of type Integer. Its type is a container with Integer objects.
• Vector<Integer> and Vector<String> are effectively different types

slido.com #3491501
Creating Vector Classes

• A Vector class stores data in an array and automatically resizes when full
• the capacityIncrement value determines how many elements are added when the
storage array grows
• If the capacityIncrement is set to 0, the storage array doubles in size
• a capacity value stores the size of the storage array
• a size value stores the number of data elements - always <= capacity

slido.com #3491501
Generics and
Abstract Classes
• An abstract class defines what a class is
• A generic can be used to qualify what can
be accepted
• Generics allow for better type checking on
containers
• A generic type is a generic class or interface
that is parameterized over types
• Defined using angle brackets: ArrayList<T>
• Specifies what kind of objects can be “used” by
Generics the class
• Ex: ArrayList<T> can store elements of type T
• Ex: Map<K, V> has keys of type K and values of type V

https://docs.oracle.com/javase/tutorial/java/generics/types.html

slido.com #3491501
12
Generics
An abstraction of data representation

Allows a datatype to be a parameter to methods, classes and


interfaces. For example, classes like HashSet, ArrayList,
HashMap, etc. use generics very well. We can use them for any
type.
Some references:
https://docs.oracle.com/javase/tutorial/java/generics/why.html
GeeksforGeeks - Generics in Java

slido.com #3491501
13
Why use Generics?
In a nutshell, generics enable types (classes and interfaces) to
be parameters when defining classes, interfaces and
methods. Much like the more familiar formal parameters used
in method declarations, type parameters provide a way for
you to re-use the same code with different inputs. The
difference is that the inputs to formal parameters are values,
while the inputs to type parameters are types.

https://docs.oracle.com/javase/tutorial/java/generics/why.html
slido.com #3491501
14
E - Element (used extensively by the Java
Generics – An Abstraction Collections Framework)
K - Key
(Ensuring type-safety) N - Number
T - Type
• There exists a Generic type V - Value
S,U,V etc. - 2nd, 3rd, 4th types
ArrayList<T> or Map<K, V>
It specifies what kind of objects can be “used” by the class/method/etc.
• List, Set and Map interfaces all accept Generic type specifiers
• For instance, ArrayList will accept any object, but this line
specifies Strings:
• ArrayList<String> myList = new ArrayList<String>();
• This allows the compiler to check for type safety
• All code you will write that deals with generics will be collection-related code!
• https://docs.oracle.com/javase/tutorial/java/generics/types.html
15
Generics Ensure Type-safety
• Without generics, the compiler would
happily allow you to put a Cat into an
ArrayList that was supposed to hold only Array List
Dog objects (ArrayList<Object> dogs…)
Object Object Object
• With generics, you can create type-safe
collections where more problems are
caught at compile-time instead of run-time
(ArrayList<Dog> dogs…)
Array List<Dog>

16
Generics – examples and why they matter
Use Example
• When you create an ArrayList, you have to tell it the type
Creating instances of
of objects allowed in the list
generified classes
• new ArrayList<Dog>()

Declaring and assigning • Assigning object instances to variables of generic types


variables of generic (polymorphism with generic types)
types • List<Dog> dogs = new ArrayList<Dog>()
• Passing arguments to methods that are declared to accept
Declaring (and generic parameter types
invoking) methods that
• void foo(List<Dog> list) {. . .}
take generic types
x.foo(dogs)
Using Generic Classes :
Understanding the ArrayList class declaration

18
Using the generic parameter with ArrayList
• This code:
ArrayList<String> thisList = new ArrayList<String>();
• Is treated by the compiler as:
We now have an ArrayList of Strings:
public class ArrayList<String> extends AbstractList<String>
… {
// Method declaration for adding elements
public boolean add(String o) {…}
// more code “T” is the convention for
} a generic type, unless it
is used in a collection
class where we use “E” for
19
the type of element
Example

slido.com #3491501
20
When does the substitutability property /
Polymorphism work with Generics? [mixing types]
• ArrayList<Animal> animals = new ArrayList<Animal>(); abstract class Animal {
• Since the reference and object types are exactly the public String makeNoise() {
same (ArrayList<Animal>), return “…”
this will compile! }
}
• ArrayList<Animal> dogLst = new ArrayList<Dog>(); class Dog extends Animal {
• Even through Dog extends Animal, substitutability/ public String makeNoise() {
polymorphism does NOT apply on the generic type return “Woof!”
inside the <>. }
• The reference (ArrayList<Animal>) is different type than }
the object’s type (ArrayList<Dog>)
(This will not compile!) class Cat extends Animal {
public String makeNoise() {
• List<Cat> kitties = new ArrayList<Cat>(); return “Meow!”
}
• The reference type (List<Cat>) is a superclass of the }
object’s type (ArrayList<Cat>).
• This is an application of polymorphism on the container
types. (This will compile!)
21
When does the substitutability property /
Polymorphism work with Generics? [mixing types]
• ArrayList<Cat> catdog = new ArrayList<Dog>(); abstract class Animal {
• For obvious reasons this does not work, since Cat and Dog public String makeNoise() {
are not related in any way. return “…”
(This will not compile!) }
}
• ArrayList<Cat> catLst = new ArrayList<Cat>(); class Dog extends Animal {
ArrayList<Animal> animals = catLst; public String makeNoise() {
• This will not compile, since the new reference animals return “Woof!”
type (ArrayList<Animal>) is not the same as the type of }
the object that variable catLst holds (ArrayList<Cat>); }
once more, polymorphism does not apply on the generic
type of the container type ArrayList.
class Cat extends Animal {
public String makeNoise() {
• ArrayList<Object> myObjects = new ArrayList<Animal>(); return “Meow!”
• Since the reference (ArrayList<Object>) is different type }
than the object’s type (ArrayList<Animal>); polymorphism }
does not apply on the generic type inside the <>.
(This will not compile!)
22
• public static void
How does takeAnimals(ArrayList<Animal> animals) {…}

Generics work
• Method parameters:
with method • If a method takes in an ArrayList of a certain type, that
parameters? is the ONLY type that will be accepted!
• Polymorphism and substitutability will not work in this
case (using the syntax given above)
• If Cat extends Animal, and we pass to method
takeAnimals an ArrayList of Cat, it will NOT compile
since it accepts an ArrayList of Animal.

23
Generics Example in method parameter (1)
public static void main(String[] args) { abstract class Animal {
public String makeNoise() {
ArrayList<Animal> animals = new ArrayList<Animal>(); return “…”
animals.add(new Dog(“Cleo")); }
animals.add(new Cat(“Ginger")); }

animals.add(new Dog(“Sandy")); class Dog extends Animal {


takeAnimals(animals); public String makeNoise() {
return “Woof!”
} }
Does this work? Yes! }

class Cat extends Animal {


public static void takeAnimals(ArrayList<Animal> animals) { public String makeNoise() {
for (Animal a : animals) { return “Meow!”
}
Vet.giveShot(a); } }
}

24
Generics Example in method parameter (2)
public static void main(String[] args) { abstract class Animal {
public String makeNoise() {
ArrayList<Animal> animals = new ArrayList<Animal>(); return “…”
animals.add(new Dog(“Cleo")); }
}
animals.add(new Cat(“Ginger"));
animals.add(new Dog(“Sandy")); class Dog extends Animal {
takeAnimals(animals); public String makeNoise() {
return “Woof!”
ArrayList<Cat> cats = new ArrayList<Cat>(); }
cats.add(new Cat(“Midnight”)); }
cats.add(new Cat(“Pringle”)); class Cat extends Animal {
takeAnimals(cats); Does this work? No!
public String makeNoise() {
} return “Meow!”
}
}
public static void takeAnimals(ArrayList<Animal> animals) {
for (Animal a : animals) {
Vet.giveShot(a); }
} 25
Generics Example in method parameter (2)
public static void main(String[] args) {
ArrayList<Animal> animals = new ArrayList<Animal>(); The method “takeAnimals”
animals.add(new Dog(“Cleo")); accepts ArrayList<Animal>
animals.add(new Cat(“Ginger")); Using generics it is NOT
animals.add(new Dog(“Sandy")); applicable for the argument
takeAnimals(animals);
ArrayList<Cat>!
ArrayList<Cat> cats = new ArrayList<Cat>();
cats.add(new Cat(“Midnight”));
(Must match!)
cats.add(new Cat(“Pringle”));
takeAnimals(cats); Does this work? No!
} Why? Type Safety!
public static void takeAnimals(ArrayList<Animal> animals) {
for (Animal a : animals) {
Vet.giveShot(a); }
} 26
How do you fix this?

Generics Example in method parameter (3)


public static void main(String[] args) {
ArrayList<Animal> animals = new ArrayList<Animal>();
animals.add(new Dog(“Cleo"));
animals.add(new Cat(“Ginger"));
animals.add(new Dog(“Sandy"));
takeAnimals(animals);
ArrayList<Cat> cats = new ArrayList<Cat>();
cats.add(new Cat(“Midnight”)); The wildcard “?” allows the
cats.add(new Cat(“Pringle”)); method to accept an ArrayList
takeAnimals(cats); of any subtype of Animal (such
} as Cats!)
public static void takeAnimals(ArrayList<? extends Animal> animals) {
for (Animal a : animals) {
Vet.giveShot(a); } Any type that extends Animal is now allowed!
} 27
Polymorphism Follow up – Which work?
List<String> myList = new Vector<String>();

Object something = new String();

List<Integer> myList2 = new List<Integer>();

Vector<Double> myList3 = new List<Double>();

List<Double> myList4 = new Vector<Integer>();

List<> myList5 = new ArrayList<Integer>();


slido.com #3491501

You might also like