What is a list?
Abstract Data Types & Interfaces
Polymorphism
/* Abstraction of a list that holds double values */
public interface List{
/* Methods are NOT implemented, they are abstract */
/* A class that is a list MUST have these methods */
/* inserts value into this list at the end */
public void insert(double value);
/* inserts at the specified index */
public void insert(double value, int index);
/* finds the value and removes it from the list */
public void remove(double value);
/* finds the value and returns its index, if present */
public int find(double value);
/* overwrites the item at a specified index */
public void setAt(int index, double value);
/* returns the item at specified index */
public double getAt(int index);
}
/* A class that IS a list */
//implements keywork means this object is a list
//and thus MUST contain and implement all of the methods
//in the List interface
public class Vector implements List{
private double[] theList;
public void insert(double value){
/* This class will actually implement this */
/* and actually do the inserting*/
}
public int find(double value){
for(int i = 0; i < theList.length; i++){
if(theList[i] == value) return i;
}
return -1; //didn't find it
}
/* Other list methods would be implemented below */
}
public class SortingMethods{
public static void sort(List theList){
/* CODE TO SORT LIST IS OMITTED */
/* This code must perform the sort by */
/* ONLY using methods in the interface, why? */
}
public static void main(String[] args){
Vector myVector = new Vector();
/* Add some things to the list */
/* This call works because of polymorphism */
/* myVector is a Vector which IS a list*/
sort(myVector);
}
}
List myList = new Vector(); //why does this work?
Object something = new String(); //a string IS an object
List myList2 = new List(); //does NOT work, why?
Vector myList3 = new List(); //does NOT work, why?
Click the center of the target
Close window