Data Structures and Algorithm Analysis in Java (Second Edition) Reading Notes Series
Function Class:
package com.itechzero.test;
/**
* ObjectCollection.java
*
* @author Techzero
* @Email [email protected]
* @Time 2014年10月26日 下午6:15:16
*/
public class ObjectCollection {
/**
* The array is used to store objects.
*/
private Object storedValue[] = null;
/**
* isEmpty() is used to judge whether the collection is empty.
*/
public boolean isEmpty() {
return storedValue == null ? true : false;
}
/**
* makeEmpty() is used to empty the collection.
*/
public void makeEmpty() {
storedValue = null;
}
/**
* insert(Object x) is used to insert an object into the collection.
*
* @param x
* The object to insert into the collection.
*/
public void insert(Object x) {
storedValue = storedValue == null ? new Object[1] : new Object[storedValue.length + 1];
storedValue[storedValue.length - 1] = x;
}
/**
* remove(Object x) is used to remove an object from the collection.
*
* @param x
* The object to remove from the collection.
*/
public void remove(Object x) {
if (storedValue != null) {
if (storedValue.length == 1) {
storedValue = null;
return;
}
int pos = -1;
for (int i = 0; i < storedValue.length; i++) {
if (storedValue[i].equals(x)) {
storedValue[i] = null;
pos = i;
break;
}
}
if (pos != -1) {
Object temp[] = storedValue;
storedValue = new Object[storedValue.length - 1];
for (int i = 0; i < temp.length; i++) {
if (i < pos) {
storedValue[i] = temp[i];
} else if (i == pos) {
continue;
} else {
storedValue[i - 1] = temp[i];
}
}
}
}
}
/**
* isPresent(Object x) is used to judge whether an object is in the collection.
*
* @param x
* The object to judge.
*/
public boolean isPresent(Object x) {
int pos = -1;
if (storedValue != null) {
for (int i = 0; i < storedValue.length; i++) {
if (storedValue[i].equals(x)) {
storedValue[i] = null;
pos = i;
break;
}
}
}
return pos == -1 ? false : true;
}
}
Test Class:
package com.itechzero.test;
/**
* ObjectCollectionTest.java
*
* @author Techzero
* @Email [email protected]
* @Time 2014年10月26日 下午6:26:48
*/
public class ObjectCollectionTest {
public static void main(String[] args) {
ObjectCollection collection = new ObjectCollection();
System.out.println("collection.isEmpty(): " + collection.isEmpty());
collection.insert(123);
System.out.println("collection.isEmpty(): " + collection.isEmpty());
collection.remove(123);
System.out.println("collection.isEmpty(): " + collection.isEmpty());
collection.insert(123);
System.out.println("collection.isEmpty(): " + collection.isEmpty());
System.out.println("collection.isPresent(123): " + collection.isPresent(123));
collection.makeEmpty();
System.out.println("collection.isEmpty(): " + collection.isEmpty());
System.out.println("collection.isPresent(123): " + collection.isPresent(123));
}
}
暂无评论