Download Collection Classes

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Arrays
• Construct array:
new double[10]
• Store in variable of type double[]
double[] data = new double[10];
Copying Arrays
Copying an array reference yields a second reference to the same array
double[] data = new double[10];
double[] prices = data;
Or copy array elements
• System.arraycopy(from, fromStart, to, toStart, count);
Partially Filled Arrays
Partially Filled Arrays
• Array length = maximum number of elements in array
• Quite often, array is partially filled
• Need companion variable to keep track of current size
double[] data = new double[DATA_LENGTH];
int dataSize = 0;
• Update dataSize as array is filled:
data[dataSize] = x;
dataSize++;
•
Partially Filled Arrays
• Remember to stop at dataSize when looking at array
elements:
for (int i = 0; i < dataSize; i++)
sum = sum + data[i];
• Be careful not to overfill the array
if (dataSize >= data.length)
System.out.println("Sorry--array full");
• Can grow the array:
double newData = new double[2 * data.length];
System.arraycopy(data, 0, newData, 0, data.length);
data = newData;
IntList.java
/** This class provides storage for a quantity of unique,
unordered int values and actions which can be performed
on those values.
*/
public class IntList{
private int[] data;
//instance variable is array
private int dataSize = 0; // keep track of quantity of data
private int[] data;
private int dataSize = 0;
/**
Constructs an empty list.
*/
public IntList() {
final int DATA_LENGTH = 100;
data = new int[DATA_LENGTH];
}
public IntList( int max) { //overloaded constructor for user
data = new int[max]; // flexability
}
/** add a value to list
@param newval a data value
(Precondition: list is not full)
(Postcondition: list has one more int value)
*/
public void add(int newval) {
data[dataSize] = newval;
dataSize++;
}
/** get a value from list
@param index a data value
(Precondition: list index < size of list)
(Postcondition: list does not change)
*/
public int get(int index) {
return data[index] ;
}
/** determines if the list is full
@return true if list is full, false otherwise
(Postcondition: list is unchanged)
*/
public boolean isFull( ) {
return dataSize == data.length;
}
/** determines if the list is empty
@return true if list is emtpy, false otherwise
(Postcondition: list is unchanged)
*/
public boolean isEmpty( ) {
return dataSize == 0;
}
/** return size of the list
(Postcondition: list is unchanged)
*/
public int size( ) {
return dataSize;
}
/** remove specified element from list
@param newval a data value
@remove newval from list
(Precondition: newval is in list)
(Postcondition: list contains one less value
*/
public void remove(int newval) {
int index = 0; // start looking at beginning
while ( data[index] != newval)
index++;
data[index] = data[dataSize-1];
dataSize--;
}
/** checks if list contains specified element
@param newval a data value
@return true if newval is in list
(Postcondition: list is not changed)
*/
public boolean contains(int newval) {
int index = 0; // start looking at beginning
while (index < dataSize && data[index] != newval)
index++;
if (dataSize < index) //was it found??
return true;
else
//or instead of if/else statement, just
return false;
// return (dataSize < index);
}
/** finds largest element in list
Return: largest int in the list
(Precondition: list is not empty )
(Postcondition: list contains one less value)
*/
public int largest ( ) {
int lrgIndex = 0; // assume largest is the first
//look thru the rest
for (int index = 1; index < dataSize; index++)
if (data[lrgIndex] < data[index])
lrgIndex = index;
return data[lrgIndex];
}
//now return it
File IntListTest.java
import java.util.Random;
public class IntListTest {
public static void main(String[] args) {
Random generator = new Random();
Intlist thelist = new IntList(50);
double x = generator.nextDouble();
if (! thelist.isFull() && !thelist.contains( (int) x )
thelist.add( (int) x);
else
System.out.println(“no element added” );
// output largest
if ( ! thelist.isEmpty() )
System.out.println(“largest is list is “ + thelist.largest() );
else
System.out.println(“list has no elements !!”);
// remove some values from list
String strval = JOptionPane.showInputDialog
(“enter value to remove ”);
while (strval != null) {
int value = Integer.parseInt(strval);
if (thelist.contains(value) )
thelist.remove(value);
else
System.out.println( valuel + “ not in list” );
strval = JOptionPane.showInputDialog(“enter value to remove”);
}
What if we didn’t want our list to be a fixed
size???
It could grow……………
public void add(int newval) {
if (dataSize >= data.length) {
// make a new array of twice the size
int[] newData = new int[2 * data.length];
// copy all elements from data to newData
System.arraycopy(data, 0, newData, 0, data.length);
// store a reference to the new array in data
data = newData;
}
data[dataSize] = newval;
dataSize++;
}
What if we didn’t want our list to store a fixed
type???
It could be generic with little modification..
Replace all parameter occurrances of the word int with Object
public class ObjList{
private Object[] data;
private int dataSize = 0;
// this array stores any kind of object
public ObjList( int max) {
data = new Object[max];
}
public void add(Object newval) {
data[dataSize] = newval;
dataSize++;
}
public Object get(int index) {
return data[index] ;
}
One problem:
remove needs to compare 2 objects for
equality
One problem:
remove needs to compare 2 objects for
equality
public void remove(Object newval) {
int index = 0;
while ( data[index] != newval) //cannot use == or !=
index++;
// to compare objects
data[index] = data[dataSize-1];
dataSize--;
}
can call compareTo method, and require that objects which are
stored in our list implement the Comparable interface…
public void remove(Object newval) {
int index = 0;
while ( data[index].compareTo( newval) != 0)
index++;
data[index] = data[dataSize-1];
dataSize--;
}
Two other problems:
contains needs to compare 2 objects for
equality
can fix this in same way
largest needs to compare 2 objects for
order
can also use compareTo to solve this
public Object largest ( ) {
int lrgIndex = 0; // assume largest is the first
//look thru the rest
for (int index = 1; index < dataSize; index++)
if (data[lrgIndex] < ( data[index]) )
lrgIndex = index;
return data[lrgIndex];
//now return it
}
FIX IT:
if (data[lrgIndex] .compareTo( data[index]) < 0)
public class Dog implements Comparable{
private String name;
private int age;
private int x; y; //x,y drawing position
public Dog(int newage) {
age = newage ; }
public Dog (String nm, int newage, int xpos, int ypos){
name = nm;
age = newage;
x = xpos;
y = ypos;
}
// Dog objects can be compared
public int compareTo (Object obj){
Dog dobj = (Dog) obj;
return age - dobj.age;
}
public void draw(Graphics g){ //etc……………..
For example, Dog objects can be stored in our list………
public class DogApp{
public static void main(String[] args) {
List thelist = new ObjList(50);
Dog mydog = new Dog (“SPOT”, 5, 50,50);
if (!thelist.full()){
thelist.add(mydog);
….. Code creates and adds more Dog objects…
int age = Integer.parseInt
(JOptionPane.showInput Dialog(“age of dog to delete”));
}
Dog temp = new Dog(age);
//remove all dogs of given age
while( thelist.contains(temp))
thelist.remove(temp);
Now we can store Strings, Dogs and any other type of object that
implements the Comparable interface in our ObjList.
What about int values??? Will our application still work??
NO. Because ints are not objects.
but we can make them objects……….
Converting ints to objects
• Java provides wrapper classes Integer, Double, Boolean
Character, etc.
• An object of class type Integer can ‘wrap’ an int value
in an object
Integer wrapper = new Integer(55); //wrap the int
int unwrapped = wrapper.intValue(); //get int back
Can store wrapper in the list!!
• mylist.add(wrapper);
//can now add it
•
//can get it but remember
•
that method returns Object
• Integer ival = (Integer) mylist.get(i);
unwrapped = ival.intValue();
The java.util.* package contains a class type which can be used to maintain a list
of objects…………. ArrayList
http://java.sun.com/j2se/1.4.2/docs/api/index.html
Array Lists
• Provided by java.util package
• Size is not fixed
• Can store objects
• Look at spec…
http://java.sun.com/j2se/1.4.2/docs/api/index.html
Adding Elements
•
•
add adds a new value before the index add(i, c)
where i is an int, c is an object
Setting Elements
* set overwrites an existing value set(i, M);
Retrieving Array List Elements
ArrayList dogSet() = new dogSet();
Dog mydog = new Dog();
dogSet.set(5) = mydog;
• Use get to retrieve element --must cast to correct type
dogSet.get(5).draw(); // no!!
Dog temp = (Dog) dogSet.get(5);
temp.draw();
• Error if index is out of range:
int n = dogSet.size();
Dog adog = (Dog)dogSet.get(n); // ERROR
// legal index values are 0...n-1
Removing Elements
•
remove(i) removes an element at an index
Would this run using ArrayList??
import java.util.Random;
public class IntListTest {
public static void main(String[] args) {
Random generator = new Random();
ArrayList thelist = new ArrayList();
double x = generator.nextDouble();
thelist.add((int) x);
// code which adds more elements
while( thelist.contains(x))
thelist.remove( thelist.indexOf(x));
No, because ArrayLists store objects……………..
Use wriapper classes to store primitive values in an ArrayList..
• Array lists store objects
• Use wrapper classes to store numbers
• Double wrapper = new Double(29.95);
double unwrapped = wrapper.doubleValue()
• ArrayList data = new ArrayList();
data.add(wrapper);
unwrapped = ((Double).data.get(i)).doubleValue();
Would this work with ArrayList as the data type??
public class DogApp{
public static void main(String[] args) {
ArrayList thelist = new ArrayLIst();
Dog mydog = new Dog (“SPOT”, 5, 50,50);
thelist.add(mydog);
// Code creates and adds more Dog objects…
while( thelist.contains(mydog))
thelist.remove(thelist.indexOf(mydog));
}
Yes, as long as the Dog class overrrides equals ……………