Vous êtes sur la page 1sur 7

Lecture 2

variable used to store an object


instantiate an object
deadDillo is not equal to anotherDeadDillo (have same field values, but not the same object)
true if anotherDeadDillo = deadDillo

new JUnit 4 test

@Test
public void testBabyDilloCanShelter() {
assertFalse(babyDillo.canShelter(babyDillo));
}

@Test
public void testHugeDeadDilloCanShelter() {
assertTrue(babyDillo.canShelter(hugeDeadDillo));
}

@Test
public void testEdgeCaseDilloCanShelter() {
assertFalse(babyDillo.canShelter(edgeCaseDillo));
}

assertEquals(4,4);

@Test
public void testMyBoaAnotherBoaLikesSameFood() {
assertFalse(myBoa.likesSameFood(anotherBoa);
}

@Test
public void testMyBoaAnotherBoaLikesSameFood() {
assertTrue(myBoa.likesSameFood(myBoa);
}

test empty strings (still true)

put instances of objects in testing


interface only has method header (method is different in each class)
abstract class has the whole method (same method in each class using abstract class)
abstract class can also contain fields and constructer

put super(length); in class using abstract class

subclasses inherit fields from super class

supers are first line of constructer


can only inherit from one superclass

true root of all java classes is the class Object


class implicitly extents Object if doesn’t extend another class

assign a parameter to a field (this.isDead = isItDead


super calls the constructor of the abstract class

overloading (have more than one constructor for a class) or overloaded constructor
-can just rearrange parameters of constructor

two ways to call objects


Request reqHamlet = new Request(hamlet, 1234);
Request reqHamletAgain = hamlet.makeRequest(1235); // allows for chaining methods

reqHamlet.book // Book
hamlet // Book

empty or default constructor (don’t have to call)


public EmptyList() {}

public int countBooks() {


return 1 + restOfList.countBooks(); // recursion
}

boolean timeToReplace(Book aBook) {


return aBook.checkout().timesOut > 400;
}

for linked lists ALWAYS


import java.util.LinkedList;

LinkedList<Book> books;

public int countAllTheBooks() {


return books.size;
}

LinkedList<Integer> numbers; // instead of <int>


linked list add: .add(param), .addFirst(param), .addLast(param)
also .removeFirst, .removeLast

public boolean findABook(String title) {


for (Book aBook : Books) {
if (aBook.title.equals(myTitle))
{
return true;
}
}
return else;
}

LONGER way to count (can count num of books with given title)

int numOfBooks = 0;
//accumulator
for(book aBook : this.books) {
if (book title matches my title) {
numOfBooks++;
}
}
return numOfBooks;

// overriding a method (same signature)

public Book checkOut() {


super.checkOut();
return null;
}

public Book checkOut() {


//mutator
this.timesOut++
this.isAvailable = false;
return this;
}

//overloading (method has same name but different parameters, usually within same class)
public Book checkOut(String title) {
return null;
}

// return words longer than a given length


public LinkedList<String> wordsLongerThan (int low) {
LinkedList<String> longList = new LinkedList<String>();
for (String aWord : this.words) {
if (aWord.length > low)
longList.add(aWord);
}
return longList;
}
// OVERRIDING write our own equals method (parameter must be class type)
public boolean equals (Book otherBook) {
if (this.title.equals(otherBook.title) && this.callNum.equals(otherBook.callNum))
return true;
else
return false;
}

@Before
public void setUp() {
lib = new Library();
lib.addBook(hamlet).addBook(alice).addBook(harryPotter);
}

@Test
public void testCheckedOut() {
LinkedList<Book> result = new LinkedList<Book>();
hamlet.isAvailable = false;
alice.isAvailable = false;
result.add(hamlet);
result.add(alice);
assertEquals(result, lib.checkedOut());
}

checkOut take in linked list of CartItems and return double for price

split into three lists (shoes, hats, other)


if (object.name == …
sum method for list
element for loop

apply discounts and calculate total

LinkedList<ItemType> splitList (LinkedList<CartItem> shoppingCart) {


ItemType shoes = new ItemType();
ItemType hats = new ItemType();
ItemType other = new ItemType();

for (CartItem anItem : shoppingCart)


if (anItem.name.equals(“shoes”))
shoes.add(anItem)
else if (anItem.name.equals(“shoes”))
hats.add(anItem)
else (anItem.name.equals(“shoes”))
other.add(anItem)
}

LinkedList<ItemType> newCart = new LinkedList<ItemType>();


newCart.add(shoes);
newCart.add(hats);
newCarts.add(other);

}
class ItemType {
LinkedList<CartItem> typeOfItem;

ItemType() {
this.typeOfItem = new LinkedList<CartItem>();
}
}
———————————

double checkOut (LinkedList<CartItem> cart) {


double shoeCost;
int hatCount;

for (

employee team leastHealthy

-create team class with name, linked list of employees, total sick days
-sort employees into teams
-if team name matches any in the list of teams, add employee and its sick days to team
-else create new team and add employee
- using index based for loop, add team to right place in list (.add(int index, E element))
-return linked list of teams names

An abstract data type is a data abstraction where the implementation is hidden behind a set of operations.
The operations are precisely specified independent of any particular implementation.

A set is a collection of elements such that


there are no duplicate elements
there is no order
Operations of sets
addle: set element -> set
removeElt: set element -> set
hasElt: set element -> boolean
size: set -> int

interface ISet {
ISet addElt(int elt);
ISet removeElt (int elt);
boolean hasElt (int elt);
int size();
}

Two ways of thinking about sets


- there may be duplicates, but trust that the user will never know about them
- trust that there are no duplications in the list

How to define addElt()?


-add element to the front of the list
-or check if element is already in the list

add 12, add 4, add 12, add 12, add 9 -> list (9, 4, 12)

O(1) constant time for each operation


O(n) time directly proportional to number of elements in collection
O(n2) time directly proportional to O(n)

Binary Search Trees (DATA STRUCTURE)


in BST, every node has the following properties:
every element in the left subtree is smaller than (or equal to) the element in the root
every element in the right subtree is larger than (or equal to) the element in the root
both the left and right subtrees are BSTs
this rule is called the “invariant” and must be true at all times

thinking globally, acting locally

Most efficient if median is root of tree and root of every subtree is the median of the subtree

if double elements in the tree, only one more comparison

Maximum value of left subtree, or minimum value of right subtree

Heap
A heap is a binary tree (NOT a BST) such that the smallest item is the root of the tree and left and right
subtrees are heaps

Priority Queue
remove minimum, creates two sub-heaps
find new min, now have 3 heaps
merge two smallest heaps

Encapsulation Rule
Don’t ask for the information you need to do the work. Ask the object that has the information to do the
work for you.

public boolean checkPassword(int password) {


return this.password == password;
}

if (cust.checkPassword(withPwd))

private int password;

access modifiers: public, private, package

General Rule: all FIELDS are private, all METHODS are public

Getters & setters


public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}

Hashing
Desire
We want to store objects in some structure and be able to retrieve them extremely quickly
the number of items to store might be big
Why?
reduce access time dow to nearly O(1)
Idea
shrink the address space to fit the population size

HashMap<key, value>
HashMap<String, LinkedList<Contact>)
.get(string) and .put(aContact.name, aContact)

HashMap and HashTable are the same for this class

Designing Hash Functions


The Perfect Hash Function: Fast and no collisions
Common Hash Functions:
digit selection: eg. last 4 digits of phone number
division: modulo
Character keys

Technique: external chaining

What a Hash Code does: takes an index value and turns it into a hash value?

Vous aimerez peut-être aussi