Compare commits

...

6 Commits

Author SHA1 Message Date
86ef6a2f43 test&lab 2025-04-29 17:51:52 +03:00
9e95d7d514 assignment 2025-04-25 19:51:03 +03:00
f0b5074ac7 assignments 2025-04-09 02:32:02 +03:00
ec083c6254 datalab2 2025-03-11 17:24:33 +03:00
c18ba394ae Merge branch 'main' of ssh://ssh.ras-pi.tr/kaltinsoy/java
laptop update
2025-03-04 17:00:38 +03:00
bbf73e06a4 lab1 2025-03-04 15:53:39 +03:00
57 changed files with 3168 additions and 0 deletions

BIN
DataLabs/lab1/Box.class Normal file

Binary file not shown.

17
DataLabs/lab1/Box.java Normal file
View File

@ -0,0 +1,17 @@
public class Box<T> {
private T t;
public void set(T t){
this.t = t;
}
public T get(){
return t;
}
public String printContents(){
return t.toString();
}
}

BIN
DataLabs/lab1/Tuple.class Normal file

Binary file not shown.

42
DataLabs/lab1/Tuple.java Normal file
View File

@ -0,0 +1,42 @@
public class Tuple<T1, T2, T3> {
private T1 item1;
private T2 item2;
private T3 item3;
public Tuple(T1 item1, T2 item2, T3 item3){
this.item1 = item1;
this.item2 = item2;
this.item3 = item3;
}
public T1 getItem1(){
return item1;
}
public T2 getItem2(){
return item2;
}
public T3 getItem3(){
return item3;
}
public void setItem1(T1 item1) {
this.item1 = item1;
}
public void setItem2(T2 item2) {
this.item2 = item2;
}
public void setItem3(T3 item3) {
this.item3 = item3;
}
public String toString() {
return "item1" + item1 + "item2" + item2 + "item3" + item3;
}
}

View File

@ -0,0 +1,11 @@
public class TupleDemo {
public static void main(String[] args) {
Tuple <String, Integer, String> personTuple = new Tuple("John Doe", 21, "CS student");
Tuple <String, Double, Boolean> itemTuple = new Tuple("Tablet", 13123, 1);
System.out.println(personTuple.getItem1() + personTuple.getItem2() + personTuple.getItem3());
}
}

View File

@ -0,0 +1,9 @@
public class demoSwap{
public static void main(String[] main) {
Integer[] intArray = {1, 2, 3, 4, 5};
swap.swap(intArray, 1, 3);
System.out.print("New array: ");
swap.printArray(intArray);
}
}

BIN
DataLabs/lab1/swap.class Normal file

Binary file not shown.

16
DataLabs/lab1/swap.java Normal file
View File

@ -0,0 +1,16 @@
public class swap {
public static <T> void swap(T[] array, int i1, int i2) {
T temp = array[i1];
array[i1] = array[i2];
array[i2] = temp;
}
public static <T> void printArray(T[] array) {
for (T element: array) {
System.out.print(element + " ");
}
System.out.println();
}
}

Binary file not shown.

102
DataLabs/lab2/ArrayBag.java Normal file
View File

@ -0,0 +1,102 @@
public class ArrayBag<T> implements BagInterface<T> {
private T[] t;
private int size;
private int capacity;
private static final int DEFAULT_CAPACITY = 25;
public ArrayBag(int capacity) {
this.size = 0;
this.capacity = capacity;
this.t = (T[]) new Object[capacity];
}
public ArrayBag() {
this(DEFAULT_CAPACITY);
}
public int getCurrentSize() {
return size;
}
public boolean isEmpty() {
return size == 0;
}
public boolean add(T newEntry) {
if (isFull()) {
return false;
}
t[size] = newEntry;
size++;
return true;
}
public T remove() {
if (isEmpty()) {
return null;
}
T temp = t[size - 1];
t[size - 1] = null;
size--;
return temp;
}
public boolean remove(T anEntry) {
int index = getIndexOf(anEntry);
if (index >= 0) {
t[index] = t[size - 1];
t[size - 1] = null;
size--;
return true;
}
return false;
}
public void clear() {
while(!isEmpty()) {
t[size - 1] = null;
size--;
}
}
public int getFrequencyOf(T anEntry) {
int temp = 0;
for(int i = 0; i < size; i++) {
if(t[i] == anEntry) {
temp++;
}
}
return temp;
}
public boolean contains(T anEntry) {
if(getFrequencyOf(anEntry) > 0) {
return true;
} else {
return false;
}
}
public T[] toArray() {
T[] newArray = (T[]) new Object[size];
for(int i = 0; i < size; i++) {
newArray[i] = t[i];
}
return newArray;
}
private int getIndexOf(T anEntry) {
for(int i = 0; i < size; i++) {
if(t[i] == anEntry) {
return i;
}
}
return -1;
}
public boolean isFull() {
return capacity == size;
}
}

View File

@ -0,0 +1,241 @@
/** A demonstration of the class ArrayBag
@author Frank M. Carrano
@version 4.0
*/
public class ArrayBagDemo
{
public static void main(String[] args)
{
String[] contentsOfBag = {"A", "A", "B", "A", "C", "A"};
// Tests on an empty bag
BagInterface<String> aBag = new ArrayBag<>(contentsOfBag.length);
System.out.println("Testing an initially empty bag:");
testIsEmpty(aBag, true);
String[] testStrings1 = {"", "B"};
testFrequency(aBag, testStrings1);
testContains(aBag, testStrings1);
testRemove(aBag, testStrings1);
// Adding strings
System.out.println("Adding " + contentsOfBag.length +
" strings to an initially empty bag with" +
" the capacity to hold more than " +
contentsOfBag.length + " strings:");
testAdd(aBag, contentsOfBag);
// Tests on a bag that is not empty
testIsEmpty(aBag, false);
String[] testStrings2 = {"A", "B", "C", "D", "Z"};
testFrequency(aBag, testStrings2);
testContains(aBag, testStrings2);
// Removing strings
String[] testStrings3 = {"", "B", "A", "C", "Z"};
testRemove(aBag, testStrings3);
System.out.println("\nClearing the bag:");
aBag.clear();
testIsEmpty(aBag, true);
displayBag(aBag);
// Filling an initially empty bag to capacity
System.out.println("\nTesting an initially empty bag that " +
" will be filled to capacity:");
aBag = new ArrayBag<String>(7);
String[] contentsOfBag2 = {"A", "B", "A", "C", "B", "C", "D"};
testAdd(aBag, contentsOfBag2);
System.out.println("Try to add another string to the full bag:");
if (aBag.add("another string"))
System.out.println("Added a string beyond the bag's capacity: ERROR!");
else
System.out.println("The method add cannot add another string: OK");
} // end main
// Tests the method add.
private static void testAdd(BagInterface<String> aBag, String[] content)
{
System.out.print("Adding ");
for (int index = 0; index < content.length; index++)
{
aBag.add(content[index]);
System.out.print(content[index] + " ");
} // end for
System.out.println();
displayBag(aBag);
} // end testAdd
// Tests the two remove methods.
private static void testRemove(BagInterface<String> aBag, String[] tests)
{
for (int index = 0; index < tests.length; index++)
{
String aString = tests[index];
if (aString.equals("") || (aString == null))
{
// test remove()
System.out.println("\nRemoving a string from the bag:");
String removedString = aBag.remove();
System.out.println("remove() returns " + removedString);
}
else
{
// test remove(aString)
System.out.println("\nRemoving \"" + aString + "\" from the bag:");
boolean result = aBag.remove(aString);
System.out.println("remove(\"" + aString + "\") returns " + result);
} // end if
displayBag(aBag);
} // end for
} // end testRemove
// Tests the method isEmpty.
// correctResult indicates what isEmpty should return.
private static void testIsEmpty(BagInterface<String> aBag, boolean correctResult)
{
System.out.print("Testing isEmpty with ");
if (correctResult)
System.out.println("an empty bag:");
else
System.out.println("a bag that is not empty:");
System.out.print("isEmpty finds the bag ");
if (correctResult && aBag.isEmpty())
System.out.println("empty: OK.");
else if (correctResult)
System.out.println("not empty, but it is empty: ERROR.");
else if (!correctResult && aBag.isEmpty())
System.out.println("empty, but it is not empty: ERROR.");
else
System.out.println("not empty: OK.");
System.out.println();
} // end testIsEmpty
// Tests the method getFrequencyOf.
private static void testFrequency(BagInterface<String> aBag, String[] tests)
{
System.out.println("\nTesting the method getFrequencyOf:");
for (int index = 0; index < tests.length; index++)
{
String aString = tests[index];
if (!aString.equals("") && (aString != null))
{
System.out.println("In this bag, the count of " + tests[index] +
" is " + aBag.getFrequencyOf(tests[index]));
} // end if
} // end for
} // end testFrequency
// Tests the method contains.
private static void testContains(BagInterface<String> aBag, String[] tests)
{
System.out.println("\nTesting the method contains:");
for (int index = 0; index < tests.length; index++)
{
String aString = tests[index];
if (!aString.equals("") && (aString != null))
{
System.out.println("Does this bag contain " + tests[index] +
"? " + aBag.contains(tests[index]));
} // end if
} // end for
} // end testContains
// Tests the method toArray while displaying the bag.
private static void displayBag(BagInterface<String> aBag)
{
System.out.println("The bag contains " + aBag.getCurrentSize() +
" string(s), as follows:");
Object[] bagArray = aBag.toArray();
for (int index = 0; index < bagArray.length; index++)
{
System.out.print(bagArray[index] + " ");
} // end for
System.out.println();
} // end displayBag
} // end ArrayBagDemo
/*
Testing an initially empty bag:
Testing isEmpty with an empty bag:
isEmpty finds the bag empty: OK.
Testing the method getFrequencyOf:
In this bag, the count of B is 0
Testing the method contains:
Does this bag contain B? false
Removing a string from the bag:
remove() returns null
The bag contains 0 string(s), as follows:
Removing "B" from the bag:
remove("B") returns false
The bag contains 0 string(s), as follows:
Adding 6 strings to an initially empty bag with the capacity to hold more than 6 strings:
Adding A A B A C A
The bag contains 6 string(s), as follows:
A A B A C A
Testing isEmpty with a bag that is not empty:
isEmpty finds the bag not empty: OK.
Testing the method getFrequencyOf:
In this bag, the count of A is 4
In this bag, the count of B is 1
In this bag, the count of C is 1
In this bag, the count of D is 0
In this bag, the count of Z is 0
Testing the method contains:
Does this bag contain A? true
Does this bag contain B? true
Does this bag contain C? true
Does this bag contain D? false
Does this bag contain Z? false
Removing a string from the bag:
remove() returns A
The bag contains 5 string(s), as follows:
A A B A C
Removing "B" from the bag:
remove("B") returns true
The bag contains 4 string(s), as follows:
A A C A
Removing "A" from the bag:
remove("A") returns true
The bag contains 3 string(s), as follows:
A A C
Removing "C" from the bag:
remove("C") returns true
The bag contains 2 string(s), as follows:
A A
Removing "Z" from the bag:
remove("Z") returns false
The bag contains 2 string(s), as follows:
A A
Clearing the bag:
Testing isEmpty with an empty bag:
isEmpty finds the bag empty: OK.
The bag contains 0 string(s), as follows:
Testing an initially empty bag that will be filled to capacity:
Adding A B A C B C D
The bag contains 7 string(s), as follows:
A B A C B C D
Try to add another string to the full bag:
The method add cannot add another string: OK
*/
/*
Exception in thread "main" java.lang.SecurityException: Attempt to create a bag whose capacity exceeds 3
at ArrayBag.<init>(ArrayBag.java:38)
at ArrayBagDemo.main(ArrayBagDemo.java:12)
*/

Binary file not shown.

View File

@ -0,0 +1,48 @@
/**
An interface that describes the operations of a bag of objects.
@author Frank M. Carrano
@version 4.0
*/
public interface BagInterface<T>
{
/** Gets the current number of entries in this bag.
@return The integer number of entries currently in the bag. */
public int getCurrentSize();
/** Sees whether this bag is empty.
@return True if the bag is empty, or false if not. */
public boolean isEmpty();
/** Adds a new entry to this bag.
@param newEntry The object to be added as a new entry.
@return True if the addition is successful, or false if not. */
public boolean add(T newEntry);
/** Removes one unspecified entry from this bag, if possible.
@return Either the removed entry, if the removal.
was successful, or null. */
public T remove();
/** Removes one occurrence of a given entry from this bag.
@param anEntry The entry to be removed.
@return True if the removal was successful, or false if not. */
public boolean remove(T anEntry);
/** Removes all entries from this bag. */
public void clear();
/** Counts the number of times a given entry appears in this bag.
@param anEntry The entry to be counted.
@return The number of times anEntry appears in the bag. */
public int getFrequencyOf(T anEntry);
/** Tests whether this bag contains a given entry.
@param anEntry The entry to locate.
@return True if the bag contains anEntry, or false if not. */
public boolean contains(T anEntry);
/** Retrieves all entries that are in this bag.
@return A newly allocated array of all the entries in the bag.
Note: If the bag is empty, the returned array is empty. */
public T[] toArray();
} // end BagInterface

BIN
DataLabs/lab2/Lab3.docx Normal file

Binary file not shown.

Binary file not shown.

143
DataLabs/lab3/ArrayBag.java Normal file
View File

@ -0,0 +1,143 @@
public class ArrayBag<T> implements BagInterface<T> {
private T[] t;
private int size;
private int capacity;
private static final int DEFAULT_CAPACITY = 25;
public ArrayBag(int capacity) {
this.size = 0;
this.capacity = capacity;
this.t = (T[]) new Object[capacity];
}
public ArrayBag() {
this(DEFAULT_CAPACITY);
}
public int getCurrentSize() {
return size;
}
public boolean isEmpty() {
return size == 0;
}
public boolean add(T newEntry) {
if (isFull()) {
// return false;
resize();
}
t[size] = newEntry;
size++;
return true;
}
public T remove() {
if (isEmpty()) {
return null;
}
T temp = t[size - 1];
t[size - 1] = null;
size--;
return temp;
}
public boolean remove(T anEntry) {
int index = getIndexOf(anEntry);
if (index >= 0) {
t[index] = t[size - 1];
t[size - 1] = null;
size--;
return true;
}
return false;
}
public void clear() {
while(!isEmpty()) {
t[size - 1] = null;
size--;
}
}
public int getFrequencyOf(T anEntry) {
int temp = 0;
for(int i = 0; i < size; i++) {
if(t[i] == anEntry) {
temp++;
}
}
return temp;
}
public boolean contains(T anEntry) {
if(getFrequencyOf(anEntry) > 0) {
return true;
} else {
return false;
}
}
public T[] toArray() {
T[] newArray = (T[]) new Object[size];
for(int i = 0; i < size; i++) {
newArray[i] = t[i];
}
return newArray;
}
private int getIndexOf(T anEntry) {
for(int i = 0; i < size; i++) {
if(t[i] == anEntry) {
return i;
}
}
return -1;
}
public boolean isFull() {
return capacity == size;
}
public void resize() {
int newCapacity = 2 * capacity;
T[] newArray = (T[]) new Object[newCapacity];
for (int i = 0; i < size; i++) {
newArray[i] = t[i];
}
t = newArray;
capacity = newCapacity;{}
}
public ArrayBag<T> union(ArrayBag<T> otherBag) {
ArrayBag<T> result = new ArrayBag<>(this.size + otherBag.size);
for(int i = 0; i < this.size; i++){
result.add(this.t[i]);
}
for(int i = 0; i < otherBag.size; i++){
result.add(otherBag.t[i]);
}
return result;
}
public ArrayBag<T> intersection(ArrayBag<T> otherBag) {
ArrayBag<T> result = new ArrayBag<>(Math.min(this.size, otherBag.size));
for(int i = 0; i < this.size; i++) {
T temp = this.t[i];
if(otherBag.contains(temp)) {
result.add(temp);
otherBag.remove(temp);
}
}
return result;
}
}

View File

@ -0,0 +1,241 @@
/** A demonstration of the class ArrayBag
@author Frank M. Carrano
@version 4.0
*/
public class ArrayBagDemo
{
public static void main(String[] args)
{
String[] contentsOfBag = {"A", "A", "B", "A", "C", "A"};
// Tests on an empty bag
BagInterface<String> aBag = new ArrayBag<>(contentsOfBag.length);
System.out.println("Testing an initially empty bag:");
testIsEmpty(aBag, true);
String[] testStrings1 = {"", "B"};
testFrequency(aBag, testStrings1);
testContains(aBag, testStrings1);
testRemove(aBag, testStrings1);
// Adding strings
System.out.println("Adding " + contentsOfBag.length +
" strings to an initially empty bag with" +
" the capacity to hold more than " +
contentsOfBag.length + " strings:");
testAdd(aBag, contentsOfBag);
// Tests on a bag that is not empty
testIsEmpty(aBag, false);
String[] testStrings2 = {"A", "B", "C", "D", "Z"};
testFrequency(aBag, testStrings2);
testContains(aBag, testStrings2);
// Removing strings
String[] testStrings3 = {"", "B", "A", "C", "Z"};
testRemove(aBag, testStrings3);
System.out.println("\nClearing the bag:");
aBag.clear();
testIsEmpty(aBag, true);
displayBag(aBag);
// Filling an initially empty bag to capacity
System.out.println("\nTesting an initially empty bag that " +
" will be filled to capacity:");
aBag = new ArrayBag<String>(7);
String[] contentsOfBag2 = {"A", "B", "A", "C", "B", "C", "D"};
testAdd(aBag, contentsOfBag2);
System.out.println("Try to add another string to the full bag:");
if (aBag.add("another string"))
System.out.println("Added a string beyond the bag's capacity: ERROR!");
else
System.out.println("The method add cannot add another string: OK");
} // end main
// Tests the method add.
private static void testAdd(BagInterface<String> aBag, String[] content)
{
System.out.print("Adding ");
for (int index = 0; index < content.length; index++)
{
aBag.add(content[index]);
System.out.print(content[index] + " ");
} // end for
System.out.println();
displayBag(aBag);
} // end testAdd
// Tests the two remove methods.
private static void testRemove(BagInterface<String> aBag, String[] tests)
{
for (int index = 0; index < tests.length; index++)
{
String aString = tests[index];
if (aString.equals("") || (aString == null))
{
// test remove()
System.out.println("\nRemoving a string from the bag:");
String removedString = aBag.remove();
System.out.println("remove() returns " + removedString);
}
else
{
// test remove(aString)
System.out.println("\nRemoving \"" + aString + "\" from the bag:");
boolean result = aBag.remove(aString);
System.out.println("remove(\"" + aString + "\") returns " + result);
} // end if
displayBag(aBag);
} // end for
} // end testRemove
// Tests the method isEmpty.
// correctResult indicates what isEmpty should return.
private static void testIsEmpty(BagInterface<String> aBag, boolean correctResult)
{
System.out.print("Testing isEmpty with ");
if (correctResult)
System.out.println("an empty bag:");
else
System.out.println("a bag that is not empty:");
System.out.print("isEmpty finds the bag ");
if (correctResult && aBag.isEmpty())
System.out.println("empty: OK.");
else if (correctResult)
System.out.println("not empty, but it is empty: ERROR.");
else if (!correctResult && aBag.isEmpty())
System.out.println("empty, but it is not empty: ERROR.");
else
System.out.println("not empty: OK.");
System.out.println();
} // end testIsEmpty
// Tests the method getFrequencyOf.
private static void testFrequency(BagInterface<String> aBag, String[] tests)
{
System.out.println("\nTesting the method getFrequencyOf:");
for (int index = 0; index < tests.length; index++)
{
String aString = tests[index];
if (!aString.equals("") && (aString != null))
{
System.out.println("In this bag, the count of " + tests[index] +
" is " + aBag.getFrequencyOf(tests[index]));
} // end if
} // end for
} // end testFrequency
// Tests the method contains.
private static void testContains(BagInterface<String> aBag, String[] tests)
{
System.out.println("\nTesting the method contains:");
for (int index = 0; index < tests.length; index++)
{
String aString = tests[index];
if (!aString.equals("") && (aString != null))
{
System.out.println("Does this bag contain " + tests[index] +
"? " + aBag.contains(tests[index]));
} // end if
} // end for
} // end testContains
// Tests the method toArray while displaying the bag.
private static void displayBag(BagInterface<String> aBag)
{
System.out.println("The bag contains " + aBag.getCurrentSize() +
" string(s), as follows:");
Object[] bagArray = aBag.toArray();
for (int index = 0; index < bagArray.length; index++)
{
System.out.print(bagArray[index] + " ");
} // end for
System.out.println();
} // end displayBag
} // end ArrayBagDemo
/*
Testing an initially empty bag:
Testing isEmpty with an empty bag:
isEmpty finds the bag empty: OK.
Testing the method getFrequencyOf:
In this bag, the count of B is 0
Testing the method contains:
Does this bag contain B? false
Removing a string from the bag:
remove() returns null
The bag contains 0 string(s), as follows:
Removing "B" from the bag:
remove("B") returns false
The bag contains 0 string(s), as follows:
Adding 6 strings to an initially empty bag with the capacity to hold more than 6 strings:
Adding A A B A C A
The bag contains 6 string(s), as follows:
A A B A C A
Testing isEmpty with a bag that is not empty:
isEmpty finds the bag not empty: OK.
Testing the method getFrequencyOf:
In this bag, the count of A is 4
In this bag, the count of B is 1
In this bag, the count of C is 1
In this bag, the count of D is 0
In this bag, the count of Z is 0
Testing the method contains:
Does this bag contain A? true
Does this bag contain B? true
Does this bag contain C? true
Does this bag contain D? false
Does this bag contain Z? false
Removing a string from the bag:
remove() returns A
The bag contains 5 string(s), as follows:
A A B A C
Removing "B" from the bag:
remove("B") returns true
The bag contains 4 string(s), as follows:
A A C A
Removing "A" from the bag:
remove("A") returns true
The bag contains 3 string(s), as follows:
A A C
Removing "C" from the bag:
remove("C") returns true
The bag contains 2 string(s), as follows:
A A
Removing "Z" from the bag:
remove("Z") returns false
The bag contains 2 string(s), as follows:
A A
Clearing the bag:
Testing isEmpty with an empty bag:
isEmpty finds the bag empty: OK.
The bag contains 0 string(s), as follows:
Testing an initially empty bag that will be filled to capacity:
Adding A B A C B C D
The bag contains 7 string(s), as follows:
A B A C B C D
Try to add another string to the full bag:
The method add cannot add another string: OK
*/
/*
Exception in thread "main" java.lang.SecurityException: Attempt to create a bag whose capacity exceeds 3
at ArrayBag.<init>(ArrayBag.java:38)
at ArrayBagDemo.main(ArrayBagDemo.java:12)
*/

Binary file not shown.

View File

@ -0,0 +1,48 @@
/**
An interface that describes the operations of a bag of objects.
@author Frank M. Carrano
@version 4.0
*/
public interface BagInterface<T>
{
/** Gets the current number of entries in this bag.
@return The integer number of entries currently in the bag. */
public int getCurrentSize();
/** Sees whether this bag is empty.
@return True if the bag is empty, or false if not. */
public boolean isEmpty();
/** Adds a new entry to this bag.
@param newEntry The object to be added as a new entry.
@return True if the addition is successful, or false if not. */
public boolean add(T newEntry);
/** Removes one unspecified entry from this bag, if possible.
@return Either the removed entry, if the removal.
was successful, or null. */
public T remove();
/** Removes one occurrence of a given entry from this bag.
@param anEntry The entry to be removed.
@return True if the removal was successful, or false if not. */
public boolean remove(T anEntry);
/** Removes all entries from this bag. */
public void clear();
/** Counts the number of times a given entry appears in this bag.
@param anEntry The entry to be counted.
@return The number of times anEntry appears in the bag. */
public int getFrequencyOf(T anEntry);
/** Tests whether this bag contains a given entry.
@param anEntry The entry to locate.
@return True if the bag contains anEntry, or false if not. */
public boolean contains(T anEntry);
/** Retrieves all entries that are in this bag.
@return A newly allocated array of all the entries in the bag.
Note: If the bag is empty, the returned array is empty. */
public T[] toArray();
} // end BagInterface

Binary file not shown.

View File

@ -0,0 +1,48 @@
/**
An interface that describes the operations of a bag of objects.
@author Frank M. Carrano
@version 4.0
*/
public interface BagInterface<T>
{
/** Gets the current number of entries in this bag.
@return The integer number of entries currently in the bag. */
public int getCurrentSize();
/** Sees whether this bag is empty.
@return True if the bag is empty, or false if not. */
public boolean isEmpty();
/** Adds a new entry to this bag.
@param newEntry The object to be added as a new entry.
@return True if the addition is successful, or false if not. */
public boolean add(T newEntry);
/** Removes one unspecified entry from this bag, if possible.
@return Either the removed entry, if the removal.
was successful, or null. */
public T remove();
/** Removes one occurrence of a given entry from this bag.
@param anEntry The entry to be removed.
@return True if the removal was successful, or false if not. */
public boolean remove(T anEntry);
/** Removes all entries from this bag. */
public void clear();
/** Counts the number of times a given entry appears in this bag.
@param anEntry The entry to be counted.
@return The number of times anEntry appears in the bag. */
public int getFrequencyOf(T anEntry);
/** Tests whether this bag contains a given entry.
@param anEntry The entry to locate.
@return True if the bag contains anEntry, or false if not. */
public boolean contains(T anEntry);
/** Retrieves all entries that are in this bag.
@return A newly allocated array of all the entries in the bag.
Note: If the bag is empty, the returned array is empty. */
public T[] toArray();
} // end BagInterface

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,132 @@
/**
A class of bags whose entries are stored in a chain of linked nodes.
The bag is never full.
@author Frank M. Carrano
@version 4.0
*/
public final class LinkedBag<T> implements BagInterface<T>
{
private Node firstNode; // Reference to first node
private int numberOfEntries;
public LinkedBag()
{
firstNode = null;
numberOfEntries = 0;
} // end default constructor
/** Adds a new entry to this bag.
@param newEntry The object to be added as a new entry.
@return True. */
public boolean add(T newEntry) // OutOfMemoryError possible
{
// Add to beginning of chain:
Node newNode = new Node(newEntry);
newNode.next = firstNode; // Make new node reference rest of chain
// (firstNode is null if chain is empty)
firstNode = newNode; // New node is at beginning of chain
numberOfEntries++;
return true;
} // end add
/** Retrieves all entries that are in this bag.
@return A newly allocated array of all the entries in this bag. */
public T[] toArray()
{
// The cast is safe because the new array contains null entries.
@SuppressWarnings("unchecked")
T[] result = (T[])new Object[numberOfEntries]; // Unchecked cast
int index = 0;
Node currentNode = firstNode;
while ((index < numberOfEntries) && (currentNode != null))
{
result[index] = currentNode.data;
index++;
currentNode = currentNode.next;
} // end while
return result;
// Note: The body of this method could consist of one return statement,
// if you call Arrays.copyOf
} // end toArray
/** Sees whether this bag is empty.
@return True if the bag is empty, or false if not. */
public boolean isEmpty()
{
return numberOfEntries == 0;
} // end isEmpty
/** Gets the number of entries currently in this bag.
@return The integer number of entries currently in the bag. */
public int getCurrentSize()
{
return numberOfEntries;
} // end getCurrentSize
// STUBS:
/** Removes one unspecified entry from this bag, if possible.
@return Either the removed entry, if the removal
was successful, or null. */
public T remove()
{
T top = firstNode.data;
firstNode = firstNode.next;
numberOfEntries--;
return top;
} // end remove
/** Removes one occurrence of a given entry from this bag.
@param anEntry The entry to be removed.
@return True if the removal was successful, or false otherwise. */
public boolean remove(T anEntry)
{
return false; // STUB
} // end remove
/** Removes all entries from this bag. */
public void clear()
{
// STUB
} // end clear
/** Counts the number of times a given entry appears in this bag.
@param anEntry The entry to be counted.
@return The number of times anEntry appears in the bag. */
public int getFrequencyOf(T anEntry)
{
return 0; // STUB
} // end getFrequencyOf
/** Tests whether this bag contains a given entry.
@param anEntry The entry to locate.
@return True if the bag contains anEntry, or false otherwise. */
public boolean contains(T anEntry)
{
return false; // STUB
} // end contains
private class Node
{
private T data; // Entry in bag
private Node next; // Link to next node
private Node(T dataPortion)
{
this(dataPortion, null);
} // end constructor
private Node(T dataPortion, Node nextNode)
{
data = dataPortion;
next = nextNode;
} // end constructor
} // end Node
} // end LinkedBag1

View File

@ -0,0 +1,85 @@
/** A test of the methods add, toArray, isEmpty, and getCurrentSize,
as defined in the first draft of the class LinkedBag.
@author Frank M. Carrano
@version 4.0
*/
public class LinkedBagDemo
{
public static void main(String[] args)
{
System.out.println("Creating an empty bag.");
BagInterface<String> aBag = new LinkedBag<>();
testIsEmpty(aBag, true);
displayBag(aBag);
String[] contentsOfBag = {"A", "D", "B", "A", "C", "A", "D"};
testAdd(aBag, contentsOfBag);
testIsEmpty(aBag, false);
} // end main
// Tests the method isEmpty.
// Precondition: If the bag is empty, the parameter empty should be true;
// otherwise, it should be false.
private static void testIsEmpty(BagInterface<String> bag, boolean empty)
{
System.out.print("\nTesting isEmpty with ");
if (empty)
System.out.println("an empty bag:");
else
System.out.println("a bag that is not empty:");
System.out.print("isEmpty finds the bag ");
if (empty && bag.isEmpty())
System.out.println("empty: OK.");
else if (empty)
System.out.println("not empty, but it is: ERROR.");
else if (!empty && bag.isEmpty())
System.out.println("empty, but it is not empty: ERROR.");
else
System.out.println("not empty: OK.");
} // end testIsEmpty
// Tests the method add.
private static void testAdd(BagInterface<String> aBag, String[] content)
{
System.out.print("Adding the following " + content.length +
" strings to the bag: ");
for (int index = 0; index < content.length; index++)
{
if (aBag.add(content[index]))
System.out.print(content[index] + " ");
else
System.out.print("\nUnable to add " + content[index] +
" to the bag.");
} // end for
System.out.println();
displayBag(aBag);
} // end testAdd
// Tests the method toArray while displaying the bag.
private static void displayBag(BagInterface<String> aBag)
{
System.out.println("The bag contains the following string(s):");
Object[] bagArray = aBag.toArray();
for (int index = 0; index < bagArray.length; index++)
{
System.out.print(bagArray[index] + " ");
} // end for
System.out.println();
} // end displayBag
} // end LinkedBagDemo1
/*
Creating an empty bag.
Testing isEmpty with an empty bag:
isEmpty finds the bag empty: OK.
The bag contains the following string(s):
Adding the following 7 strings to the bag: A D B A C A D
The bag contains the following string(s):
D A C A B D A
Testing isEmpty with a bag that is not empty:
isEmpty finds the bag not empty: OK.
*/

View File

@ -0,0 +1,149 @@
/**
A class that implements the ADT queue by using an expandable
circular array with one unused location.
@author Frank M. Carrano
@author Timothy M. Henry
@version 4.0
*/
public final class ArrayQueue<T> implements QueueInterface<T>
{
private T[] queue; // Circular array of queue entries and one unused location
private int frontIndex;
private int backIndex;
private boolean initialized = false;
private static final int DEFAULT_CAPACITY = 50;
private static final int MAX_CAPACITY = 10000;
public ArrayQueue()
{
this(DEFAULT_CAPACITY);
} // end default constructor
public ArrayQueue(int initialCapacity)
{
checkCapacity(initialCapacity);
// The cast is safe because the new array contains null entries
@SuppressWarnings("unchecked")
T[] tempQueue = (T[]) new Object[initialCapacity + 1];
queue = tempQueue;
frontIndex = 0;
backIndex = initialCapacity;
initialized = true;
} // end constructor
public void enqueue(T newEntry)
{
checkInitialization();
ensureCapacity();
backIndex = (backIndex + 1) % queue.length;
queue[backIndex] = newEntry;
} // end enqueue
public T getFront()
{
checkInitialization();
if (isEmpty())
throw new EmptyQueueException();
else
return queue[frontIndex];
} // end getFront
public T dequeue()
{
checkInitialization();
if (isEmpty())
throw new EmptyQueueException();
else
{
T front = queue[frontIndex];
queue[frontIndex] = null;
frontIndex = (frontIndex + 1) % queue.length;
return front;
} // end if
} // end dequeue
// Doubles the size of the array queue if it is full
// Precondition: checkInitialization has been called.
private void ensureCapacity()
{
if (frontIndex == ((backIndex + 2) % queue.length)) // if array is full,
{ // double size of array
T[] oldQueue = queue;
int oldSize = oldQueue.length;
int newSize = 2 * oldSize;
checkCapacity(newSize);
// The cast is safe because the new array contains null entries
@SuppressWarnings("unchecked")
T[] tempQueue = (T[]) new Object[2 * oldSize];
queue = tempQueue;
for (int index = 0; index < oldSize - 1; index++)
{
queue[index] = oldQueue[frontIndex];
frontIndex = (frontIndex + 1) % oldSize;
} // end for
frontIndex = 0;
backIndex = oldSize - 2;
} // end if
} // end ensureCapacity
public boolean isEmpty()
{
return frontIndex == ((backIndex + 1) % queue.length);
} // end isEmpty
// Throws an exception if this object is not initialized.
private void checkInitialization()
{
if (!initialized)
{
throw new SecurityException ("ArrayQueue object is not initialized properly.");
}
}
// Throws an exception if the client requests a capacity that is too large.
private void checkCapacity(int capacity)
{
if (capacity > MAX_CAPACITY)
{
throw new IllegalStateException("Attempt to create a queue " +
"whose capacity exceeds " +
"allowed maximum.");
}
}
// Question 3, Chapter 11
public void clear()
{
checkInitialization();
if (!isEmpty())
{ // deallocates only the used portion
for (int index = frontIndex; index != backIndex; index = (index + 1) % queue.length)
{
queue[index] = null;
}
queue[backIndex] = null;
}
frontIndex = 0;
backIndex = queue.length - 1;
}
/*
// Question 4, Chapter 11
public void clear()
{
while (!isEmpty())
{
dequeue();
}
}
*/
} // end ArrayQueue

View File

@ -0,0 +1,13 @@
/** A class of runtime exceptions thrown when an attempt is made
to access or remove the front of a queue. @author Frank M. Carrano
*/
public class EmptyQueueException extends RuntimeException {
public EmptyQueueException() {
this(null);
} // end default
public EmptyQueueException(String message) {
super(message);
} // end constructor
} // end EmptyQueueException

BIN
DataLabs/lab5/Lab5.docx Normal file

Binary file not shown.

View File

@ -0,0 +1,101 @@
/**
A class that implements the ADT queue by using a chain of nodes
that has both head and tail references.
@author Frank M. Carrano
@author Timothy M. Henry
@version 4.0
*/
public final class LinkedQueue<T> implements QueueInterface<T>
{
private Node firstNode; // References node at front of queue
private Node lastNode; // References node at back of queue
public LinkedQueue()
{
firstNode = null;
lastNode = null;
} // end default constructor
public void enqueue(T newEntry)
{
Node newNode = new Node(newEntry, null);
if (isEmpty())
firstNode = newNode;
else
lastNode.setNextNode(newNode);
lastNode = newNode;
} // end enqueue
public T getFront()
{
if (isEmpty())
throw new EmptyQueueException();
else
return firstNode.getData();
} // end getFront
public T dequeue()
{
T front = getFront(); // Might throw EmptyQueueException
assert firstNode != null;
firstNode.setData(null);
firstNode = firstNode.getNextNode();
if (firstNode == null)
lastNode = null;
return front;
} // end dequeue
public boolean isEmpty()
{
return (firstNode == null) && (lastNode == null);
} // end isEmpty
public void clear()
{
firstNode = null;
lastNode = null;
} // end clear
private class Node
{
private T data; // Entry in queue
private Node next; // Link to next node
private Node(T dataPortion)
{
data = dataPortion;
next = null;
} // end constructor
private Node(T dataPortion, Node linkPortion)
{
data = dataPortion;
next = linkPortion;
} // end constructor
private T getData()
{
return data;
} // end getData
private void setData(T newData)
{
data = newData;
} // end setData
private Node getNextNode()
{
return next;
} // end getNextNode
private void setNextNode(Node nextNode)
{
next = nextNode;
} // end setNextNode
} // end Node
} // end LinkedQueue

View File

@ -0,0 +1,29 @@
/**
An interface for the ADT queue.
@author Frank M. Carrano
@author Timothy M. Henry
@version 4.0
*/
public interface QueueInterface<T>
{
/** Adds a new entry to the back of this queue.
@param newEntry An object to be added. */
public void enqueue(T newEntry);
/** Removes and returns the entry at the front of this queue.
@return The object at the front of the queue.
@throws EmptyQueueException if the queue is empty before the operation. */
public T dequeue();
/** Retrieves the entry at the front of this queue.
@return The object at the front of the queue.
@throws EmptyQueueException if the queue is empty. */
public T getFront();
/** Detects whether this queue is empty.
@return True if the queue is empty, or false otherwise. */
public boolean isEmpty();
/** Removes all entries from this queue. */
public void clear();
} // end QueueInterface

View File

@ -0,0 +1,29 @@
public class StockLedger {
private QueueInterface<StockPurchase> ledger;
public StockLedger() {
ledger = new LinkedQueue<>();
}
public void buy(int sharesBought, double pricePerShare){
while(!SharesBought) {
StockPurchase purchase = new StockPurchase(pricePerShare);
ledger.enqueue(purchase);
sharesBought--;
}
}
public double sell(int sharesSold, double pricePerShare){
double saleAmount = sharesSold*pricePerShare;
double totalCost = 0;
while (!sharesSold){
StockPurchase share = ledger.dequeue();
double shareCost = share.getCostPerShare();
totalCost += shareCost;
sharesSold--;
}
return saleAmount - totalCost;
}
}

View File

@ -0,0 +1,276 @@
package dictionary;
import java.util.Arrays;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
A class that implements the ADT dictionary by using a resizable array.
The dictionary is unsorted and has distinct search keys.
@author Frank M. Carrano
@author Timothy M. Henry
@version 4.0
*/
public class ArrayDictionary<K, V> implements DictionaryInterface<K, V>
{
protected Entry<K, V>[] dictionary; // Array of unsorted entries
protected int numberOfEntries;
private boolean initialized = false;
private final static int DEFAULT_CAPACITY = 25;
private static final int MAX_CAPACITY = 10000;
public ArrayDictionary()
{
this(DEFAULT_CAPACITY); // Call next constructor
} // end default constructor
public ArrayDictionary(int initialCapacity)
{
checkCapacity(initialCapacity);
// The cast is safe because the new array contains null entries
@SuppressWarnings("unchecked")
Entry<K, V>[] tempDictionary = (Entry<K, V>[])new Entry[initialCapacity];
dictionary = tempDictionary;
numberOfEntries = 0;
initialized = true;
} // end constructor
public V add(K key, V value)
{
checkInitialization();
if ((key == null) || (value == null))
throw new IllegalArgumentException("Cannot add null to a dictionary.");
else
{
V result = null;
int keyIndex = locateIndex(key);
if (keyIndex < numberOfEntries)
{
// Key found, return and replace entry's value
result = dictionary[keyIndex].getValue(); // Get old value
dictionary[keyIndex].setValue(value); // Replace value
}
else // Key not found; add new entry to dictionary
{
// Add at end of array
dictionary[numberOfEntries] = new Entry<>(key, value);
numberOfEntries++;
ensureCapacity(); // Ensure enough room for next add
} // end if
return result;
} // end if
} // end add
// Returns the array index of the entry that contains key, or
// returns numberOfEntries if no such entry exists.
private int locateIndex(K key)
{
// Sequential search
int index = 0;
while ( (index < numberOfEntries) && !key.equals(dictionary[index].getKey()) )
index++;
return index;
} // end locateIndex
public V remove(K key)
{
checkInitialization();
V result = null;
int keyIndex = locateIndex(key);
if (keyIndex < numberOfEntries)
{
// Key found; remove entry and return its value
result = dictionary[keyIndex].getValue();
dictionary[keyIndex] = dictionary[numberOfEntries - 1];
dictionary[numberOfEntries - 1] = null;
numberOfEntries--;
} // end if
// Else result is null
return result;
} // end remove
public V getValue(K key)
{
checkInitialization();
V result = null;
int keyIndex = locateIndex(key);
if (keyIndex < numberOfEntries)
{
result = dictionary[keyIndex].getValue(); // Key found; return value
} // end if
return result;
} // end getValue
public boolean contains(K key)
{
return getValue(key) != null;
} // end contains
public boolean isEmpty()
{
return numberOfEntries == 0;
} // end isEmpty
public int getSize()
{
return numberOfEntries;
} // end getSize
public final void clear()
{
checkInitialization();
// Clear entries but retain array; no need to create a new array
for (int index = 0; index < numberOfEntries; index++)
dictionary[index] = null;
numberOfEntries = 0;
} // end clear
protected void ensureCapacity()
{
if (numberOfEntries >= dictionary.length)
{
int newCapacity = 2 * dictionary.length;
checkCapacity(newCapacity);
dictionary = Arrays.copyOf(dictionary, newCapacity);
} // end if
} // end ensureCapacity
// Throws an exception if this object is not initialized.
protected void checkInitialization()
{
if (!initialized)
{
throw new SecurityException ("ArrayDictionary object is not initialized properly.");
}
}
// Throws an exception if the client requests a capacity that is too large.
protected void checkCapacity(int capacity)
{
if (capacity > MAX_CAPACITY)
{
throw new IllegalStateException("Attempt to create a HashedDictionary " +
"whose capacity exceeds " +
"allowed maximum.");
}
}
public Iterator<K> getKeyIterator()
{
return new KeyIterator();
} // end getKeyIterator
public Iterator<V> getValueIterator()
{
return new ValueIterator();
} // end getValueIterator
protected class Entry<S, T>
{
private S key;
private T value;
protected Entry(S searchKey, T dataValue)
{
key = searchKey;
value = dataValue;
} // end constructor
protected S getKey()
{
return key;
} // end getKey
protected T getValue()
{
return value;
} // end getValue
protected void setValue(T dataValue)
{
value = dataValue;
} // end setValue
} // end Entry
// Since iterators implement Iterator, methods must be public.
// Same as SortedArrayDictionary.
private class KeyIterator implements Iterator<K>
{
private int currentIndex;
private KeyIterator()
{
currentIndex = 0;
} // end default constructor
public boolean hasNext()
{
return currentIndex < numberOfEntries;
} // end hasNext
public K next()
{
K result = null;
if (hasNext())
{
Entry<K,V> currentEntry = dictionary[currentIndex];
result = currentEntry.getKey();
currentIndex++;
}
else
{
throw new NoSuchElementException();
} // end if
return result;
} // end next
public void remove()
{
throw new UnsupportedOperationException();
} // end remove
} // end KeyIterator
private class ValueIterator implements Iterator<V>
{
private int currentIndex;
private ValueIterator()
{
currentIndex = 0;
} // end default constructor
public boolean hasNext()
{
return currentIndex < numberOfEntries;
} // end hasNext
public V next()
{
V result = null;
if (hasNext())
{
Entry<K,V> currentEntry = dictionary[currentIndex];
result = currentEntry.getValue();
currentIndex++;
}
else
{
throw new NoSuchElementException();
} // end if
return result;
} // end next
public void remove()
{
throw new UnsupportedOperationException();
} // end remove
} // end getValueIterator
} // end dictionary.ArrayDictionary

View File

@ -0,0 +1,60 @@
package dictionary;
import java.util.Iterator;
/**
An interface for a dictionary with distinct search keys.
@author Frank M. Carrano
@author Timothy M. Henry
@version 4.0
*/
public interface DictionaryInterface<K, V>
{
/** Adds a new entry to this dictionary. If the given search key already
exists in the dictionary, replaces the corresponding value.
@param key An object search key of the new entry.
@param value An object associated with the search key.
@return Either null if the new entry was added to the dictionary
or the value that was associated with key if that value
was replaced. */
public V add(K key, V value);
/** Removes a specific entry from this dictionary.
@param key An object search key of the entry to be removed.
@return Either the value that was associated with the search key
or null if no such object exists. */
public V remove(K key);
/** Retrieves from this dictionary the value associated with a given
search key.
@param key An object search key of the entry to be retrieved.
@return Either the value that is associated with the search key
or null if no such object exists. */
public V getValue(K key);
/** Sees whether a specific entry is in this dictionary.
@param key An object search key of the desired entry.
@return True if key is associated with an entry in the dictionary. */
public boolean contains(K key);
/** Creates an iterator that traverses all search keys in this dictionary.
@return An iterator that provides sequential access to the search
keys in the dictionary. */
public Iterator<K> getKeyIterator();
/** Creates an iterator that traverses all values in this dictionary.
@return An iterator that provides sequential access to the values
in this dictionary. */
public Iterator<V> getValueIterator();
/** Sees whether this dictionary is empty.
@return True if the dictionary is empty. */
public boolean isEmpty();
/** Gets the size of this dictionary.
@return The number of entries (key-value pairs) currently
in the dictionary. */
public int getSize();
/** Removes all entries from this dictionary. */
public void clear();
} // end dictionary.DictionaryInterface

BIN
DataLabs/lab6/Lab6.docx Normal file

Binary file not shown.

85
DataLabs/lab6/Name.java Normal file
View File

@ -0,0 +1,85 @@
package dictionary;
/**
A class that represents a person's name.
@author Frank M. Carrano
@author Timothy M. Henry
@version 4.0
*/
public class Name implements Comparable<Name> {
private String first; // First name
private String last; // Last name
public Name()
{
} // end default constructor
public Name(String firstName, String lastName)
{
first = firstName;
last = lastName;
} // end constructor
public void setName(String firstName, String lastName)
{
setFirst(firstName);
setLast(lastName);
} // end setName
public String getName()
{
return toString();
} // end getName
public void setFirst(String firstName)
{
first = firstName;
} // end setFirst
public String getFirst()
{
return first;
} // end getFirst
public void setLast(String lastName)
{
last = lastName;
} // end setLast
public String getLast()
{
return last;
} // end getLast
public void giveLastNameTo(Name aName)
{
aName.setLast(last);
} // end giveLastNameTo
public String toString()
{
return first + " " + last;
} // end toString
@Override
public int compareTo(Name name) {
int lastCmp = last.compareTo(name.last);
return (lastCmp != 0 ? lastCmp : first.compareTo(name.first));
}
@Override
public boolean equals(Object name) {
// If the object is compared with itself then return true
if (name == this) {
return true;
}
/* Check if o is an instance of Complex or not
"null instanceof [type]" also returns false */
if (!(name instanceof Name)) {
return false;
}
return compareTo( (Name)name ) == 0;
}
} // end Name

View File

@ -0,0 +1,104 @@
package dictionary;
/**
A class that implements the ADT dictionary by using a resizable sorted array.
The dictionary has distinct search keys.
@author Frank M. Carrano
@author Timothy M. Henry
@version 4.0
*/
public class SortedArrayDictionary<K extends Comparable<? super K>, V>
extends ArrayDictionary<K, V> implements DictionaryInterface<K, V>
{
/* < Constructors analogous to those in Listing 20-1. >
. . . */
public SortedArrayDictionary()
{
super(); // Call next constructor
} // end default constructor
public SortedArrayDictionary(int initialCapacity)
{
super(initialCapacity);
} // end constructor
// 20.11
/** Precondition: key and value are not null. */
public V add(K key, V value)
{
checkInitialization();
if ((key == null) || (value == null))
throw new IllegalArgumentException("Cannot add null to a dictionary.");
else
{
V result = null;
int keyIndex = locateIndex(key);
if ( (keyIndex < numberOfEntries) &&
key.equals(dictionary[keyIndex].getKey()) )
{
// Key found, return and replace entry's value
result = dictionary[keyIndex].getValue(); // Old value
dictionary[keyIndex].setValue(value); // Replace value
}
else // Key not found; add new entry to dictionary
{
makeRoom(keyIndex); // Make room for new entry
dictionary[keyIndex] = new Entry<K, V>(key, value); // Insert new entry in array
numberOfEntries++;
ensureCapacity(); // Ensure enough room for next add
} // end if
return result;
} // end if
} // end add
/* < Implementations of other methods in dictionary.DictionaryInterface. >
. . . */
// 20.12
// Returns the index of either the entry that contains key or
// the location that should contain key, if no such entry exists.
private int locateIndex(K key)
{
// Search until you either find an entry containing key or
// pass the point where it should be
int index = 0;
while ( (index < numberOfEntries) &&
key.compareTo(dictionary[index].getKey()) > 0 )
{
index++;
} // end while
return index;
} // end locateIndex
// Makes room for a new entry at a given index by shifting
// array entries towards the end of the array.
// Precondition: keyIndex is valid; list length is old length.
private void makeRoom(int keyIndex)
{
assert (keyIndex >= 1) && (keyIndex <= numberOfEntries + 1);
int newIndex = keyIndex;
int lastIndex = numberOfEntries;
// Move each entry to next higher index, starting at end of
// dictionary and continuing until the entry at newIndex is moved
for (int index = lastIndex; index >= newIndex; index--)
dictionary[index + 1] = dictionary[index];
} // end makeRoom
// Removes an entry at a given index by shifting array
// entries toward the entry to be removed.
private void removeArrayEntry(int keyIndex)
{
// . . . To be implemented
} // end removeArrayEntry
} // end dictionary.SortedArrayDictionary

View File

@ -0,0 +1,13 @@
import java.util.Iterator;
import java.util.Scanner;
public class TelephoneDirectory
{
private DictionaryInterface<Name, String> phoneBook;
public TelephoneDirectory()
{
//phoneBook = new SortedArrayDictionary<>();
phoneBook = new SortedLinkedDictionary<>(); //Currently Linked Directory
} // end default constructor

5
DataLabs/lab6/data.txt Normal file
View File

@ -0,0 +1,5 @@
Ali Koc 1234
Mehmet Sezgin 4567
Ayse Kahraman 8765
Ela Bekir 324242
Mehmet Sezgin 1111

9
Example.java Normal file
View File

@ -0,0 +1,9 @@
public class Example
{
public static <T> void displayArray(T[] anArray) {
for (T arrayEntrey : anArray) {
System.out.print(arrayEntry);
System.out.print(" ");
}
}
}

Binary file not shown.

View File

@ -0,0 +1,44 @@
public class StorageBox<T> {
private T[] items;
private int size;
private int capacity;
public StorageBox(int capacity) {
this.capacity = capacity;
this.size = 0;
this.items = (T[]) new Object[capacity];
}
public void addItem(T item) {
if(capacity == size) {
System.out.println("StorageBox is full");
return;
} else {
items[size] = item;
size++;
System.out.println("Item added: "+ item);
}
}
public T removeItem() {
if(size == 0) {
System.out.println("No more item left!");
return null;
} else {
T temp = items[size - 1];
items[size - 1] = null;
size--;
System.out.println("Removed Item: "+ temp);
return temp;
}
}
public void listItem() {
System.out.println("Items in StorageBox: ");
for(int i = 0; i < size; i++) {
System.out.print(items[i]+ " ");
}
}
}

View File

@ -0,0 +1,36 @@
public class demo {
public static void main(String[] args) {
StorageBox<String> box = new StorageBox<>(3);
StorageBox<Integer> box1 = new StorageBox<>(3);
box.addItem("Math");
box.addItem("Java");
box.addItem("Statistics");
box.addItem("capacityTest");
System.out.println();
box.listItem();
System.out.println(" ");
System.out.println();
box.removeItem();
box.removeItem();
box.removeItem();
box.removeItem();
box.removeItem();
box.removeItem();
System.out.println();;
box.listItem();
box1.addItem(1);
box1.addItem(2);
box1.addItem(3);
box1.addItem(4);
box1.listItem();
}
}

Binary file not shown.

View File

@ -0,0 +1,181 @@
import java.util.Arrays;
/**
* A class that implements a list of objects by using an array.
* Entries in a list have positions that begin with 1.
* Duplicate entries are allowed.
* @author Frank M. Carrano
*/
public class AList<T> implements ListInterface<T> {
private T[] list; // Array of list entries; ignore list[0]
private int numberOfEntries;
private boolean initialized = false;
private static final int DEFAULT_CAPACITY = 25;
private static final int MAX_CAPACITY = 10000;
public AList() {
this(DEFAULT_CAPACITY); // Call next constructor
} // end default constructor
public AList(int initialCapacity) {
// Is initialCapacity too small?
if (initialCapacity < DEFAULT_CAPACITY)
initialCapacity = DEFAULT_CAPACITY;
else // Is initialCapacity too big?
checkCapacity(initialCapacity);
// The cast is safe because the new array contains null entries
@SuppressWarnings("unchecked")
T[] tempList = (T[]) new Object[initialCapacity + 1];
list = tempList;
numberOfEntries = 0;
initialized = true;
} // end constructor
public void add(T newEntry) {
checkInitialization();
list[numberOfEntries + 1] = newEntry;
numberOfEntries++;
ensureCapacity();
} // end add
public void add(int newPosition, T newEntry) {
checkInitialization();
if ((newPosition >= 1) && (newPosition <= numberOfEntries + 1)) {
if (newPosition <= numberOfEntries) {
makeRoom(newPosition);
}
list[newPosition] = newEntry;
numberOfEntries++;
ensureCapacity();
} else {
throw new IndexOutOfBoundsException("Given position of add's new entry is out of bounds.");
}
} // end add
public T remove(int givenPosition) {
checkInitialization();
if ((givenPosition >= 1) && (givenPosition <= numberOfEntries)) {
T result = list[givenPosition];
if (givenPosition < numberOfEntries) {
removeGap(givenPosition);
}
list[numberOfEntries] = null;
numberOfEntries--;
return result;
} else {
throw new IndexOutOfBoundsException("Illegal position given to remove operation.");
}
} // end remove
public void clear() {
while (!isEmpty()) {
remove(numberOfEntries);
}
} // end clear
public T replace(int givenPosition, T newEntry) {
checkInitialization();
if ((givenPosition >= 1) && (givenPosition <= numberOfEntries)) {
T originalEntry = list[givenPosition];
list[givenPosition] = newEntry;
return originalEntry;
} else {
throw new IndexOutOfBoundsException("Illegal position given to replace operation.");
}
} // end replace
public T getEntry(int givenPosition) {
checkInitialization();
if ((givenPosition >= 1) && (givenPosition <= numberOfEntries)) {
return list[givenPosition];
} else {
throw new IndexOutOfBoundsException("Illegal position given to getEntry operation.");
}
} // end getEntry
public T[] toArray() {
checkInitialization();
// The cast is safe because the new array contains null entries
@SuppressWarnings("unchecked")
T[] result = (T[]) new Object[numberOfEntries];
for (int index = 0; index < numberOfEntries; index++) {
result[index] = list[index + 1];
} // end for
return result;
} // end toArray
public boolean contains(T anEntry) {
checkInitialization();
boolean found = false;
int index = 1;
while (!found && (index <= numberOfEntries)) {
if (anEntry.equals(list[index])) {
found = true;
}
index++;
} // end while
return found;
} // end contains
public int getLength() {
return numberOfEntries;
} // end getLength
public boolean isEmpty() {
return numberOfEntries == 0; // Or getLength() == 0
} // end isEmpty
// Doubles the capacity of the array list if it is full.
// Precondition: checkInitialization has been called.
private void ensureCapacity() {
int capacity = list.length - 1;
if (numberOfEntries >= capacity) {
int newCapacity = 2 * capacity;
checkCapacity(newCapacity); // Is capacity too big?
list = Arrays.copyOf(list, newCapacity + 1);
} // end if
} // end ensureCapacity
// Throws an exception if the client requests a capacity that is too large.
private void checkCapacity(int capacity) {
if (capacity > MAX_CAPACITY)
throw new IllegalStateException("Attempt to create a list whose capacity exceeds " +
"allowed maximum of " + MAX_CAPACITY);
} // end checkCapacity
// Throws an exception if receiving object is not initialized.
private void checkInitialization() {
if (!initialized)
throw new SecurityException("AList object is not initialized properly.");
} // end checkInitialization
// Makes room for a new entry at newPosition.
// Precondition: 1 <= newPosition <= numberOfEntries + 1;
// numberOfEntries is list's length before addition;
// checkInitialization has been called.
private void makeRoom(int newPosition) {
int newIndex = newPosition;
int lastIndex = numberOfEntries;
for (int index = lastIndex; index >= newIndex; index--) {
list[index + 1] = list[index];
}
} // end makeRoom
// Shifts entries that are beyond the entry to be removed to the
// next lower position.
// Precondition: 1 <= givenPosition < numberOfEntries;
// numberOfEntries is list's length before removal;
// checkInitialization has been called.
private void removeGap(int givenPosition) {
int removedIndex = givenPosition;
int lastIndex = numberOfEntries;
for (int index = removedIndex; index < lastIndex; index++) {
list[index] = list[index + 1];
}
} // end removeGap
} // end AList

View File

@ -0,0 +1,26 @@
import java.util.Arrays;
public class ListClient {
public static void main(String[] args) {
// Create an instance of AList
AList<String> list = new AList<>();
// Test isEmpty() on a new list
System.out.println("Is the list empty? " + list.isEmpty()); // Expected: true
// Test add(T newEntry)
list.add("Apple");
list.add("Banana");
list.add("Cherry");
System.out.println("After adding 3 items: " + Arrays.toString(list.toArray())); // Expected: [Apple, Banana, Cherry]
list.add(2, "Peach");
System.out.println(list.getEntry(2));
System.out.println("New List: "+ Arrays.toString(list.toArray()));
list.remove(2);
System.out.println("New List: "+ Arrays.toString(list.toArray()));
System.out.println("Changed item:"+list.replace(2, "Orange"));
System.out.println("New List: "+ Arrays.toString(list.toArray()));
System.out.println(list.contains("Apple"));
}
}

Binary file not shown.

View File

@ -0,0 +1,70 @@
public interface ListInterface<T> {
/**
* Adds a new entry to the end of the list.
* @param newEntry The object to be added as a new entry.
*/
void add(T newEntry);
/**
* Adds a new entry at a specified position within the list.
* @param newPosition An integer that specifies the desired position of the new entry.
* @param newEntry The object to be added as a new entry.
* @throws IndexOutOfBoundsException if newPosition is out of bounds.
*/
void add(int newPosition, T newEntry);
/**
* Removes the entry at a given position from the list.
* @param givenPosition An integer that indicates the position of the entry to be removed.
* @return A reference to the removed entry.
* @throws IndexOutOfBoundsException if givenPosition is out of bounds.
*/
T remove(int givenPosition);
/**
* Removes all entries from the list.
*/
void clear();
/**
* Replaces the entry at a given position in the list.
* @param givenPosition An integer that indicates the position of the entry to be replaced.
* @param newEntry The object that will replace the entry at the given position.
* @return The original entry that was replaced.
* @throws IndexOutOfBoundsException if givenPosition is out of bounds.
*/
T replace(int givenPosition, T newEntry);
/**
* Retrieves the entry at a given position in the list.
* @param givenPosition An integer that indicates the position of the desired entry.
* @return A reference to the indicated entry.
* @throws IndexOutOfBoundsException if givenPosition is out of bounds.
*/
T getEntry(int givenPosition);
/**
* Retrieves all entries that are in this list in the order in which they occur in the list.
* @return An array of all the entries in the list.
*/
T[] toArray();
/**
* Determines whether the list contains a given entry.
* @param anEntry The object that is the desired entry.
* @return True if the list contains anEntry, or false if not.
*/
boolean contains(T anEntry);
/**
* Gets the length of this list.
* @return The integer number of entries currently in the list.
*/
int getLength();
/**
* Determines whether this list is empty.
* @return True if the list is empty, or false if not.
*/
boolean isEmpty();
}

View File

@ -0,0 +1,110 @@
//Note: We are using the class LinkedStack instead of
// the class OurStack that the book uses.
/**
A class that checks whether the parentheses, brackets, and braces
in a string occur in left/right pairs.
@author Frank M. Carrano, Timothy M. Henry
@version 5.0 */
public class LinkedStack<T> implements StackInterface<T>
{
private Node firstNode; // Reference to first node
private int numberOfEntries;
public LinkedStack()
{
firstNode = null;
numberOfEntries = 0;
} // end default constructor
/** Adds a new entry to the top of this stack.
@param newEntry An object to be added to the stack. */
public void push(T newEntry)
{
// Add to beginning of chain:
Node newNode = new Node(newEntry);
newNode.setNextNode(firstNode); // Make new node reference rest of chain
// (firstNode is null if chain is empty)
firstNode = newNode; // New node is at beginning of chain
numberOfEntries++;
}
/** Removes and returns this stack's top entry.
@return The object at the top of the stack.
@throws EmptyStackException if the stack is empty before the operation. */
public T pop()
{
T result = null;
if (firstNode != null)
{
Node removingNode = firstNode;
result = removingNode.getData();
firstNode = firstNode.getNextNode();
numberOfEntries--;
}
return result;
}
/** Retrieves this stack's top entry.
@return The object at the top of the stack.
@throws EmptyStackException if the stack is empty. */
public T peek()
{
T result = null;
if (firstNode != null)
result = firstNode.getData();
return result;
}
/** Detects whether this stack is empty.
@return True if the stack is empty. */
public boolean isEmpty()
{
return numberOfEntries == 0;
}
/** Removes all entries from this stack. */
public void clear()
{
firstNode = null;
}
// @author Frank M. Carrano, Timothy M. Henry
// @version 5.0 */
private class Node
{
private T data; // Entry in bag
private Node next; // Link to next node
private Node(T dataPortion)
{
this(dataPortion, null);
} // end constructor
private Node(T dataPortion, Node nextNode)
{
data = dataPortion;
next = nextNode;
} // end constructor
private T getData()
{
return data;
} // end getData
private void setData(T newData)
{
data = newData;
} // end setData
private Node getNextNode()
{
return next;
} // end getNextNode
private void setNextNode(Node nextNode)
{
next = nextNode;
} // end setNextNode
} // end Node
} // end LinkedStack

View File

@ -0,0 +1,170 @@
public class Postfix {
public static String convertToPostfix(String infix) {
StackInterface<Character> operatorStack = new LinkedStack<>();
char[] postfixArray = new char[infix.length()]; // Max possible size
int postfixIndex = 0;
int index = 0;
char nextCharacter = ' ';
char topOperator = ' ';
while (index < infix.length()) {
nextCharacter = infix.charAt(index);
switch (nextCharacter) {
case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h':
postfixArray[postfixIndex++] = nextCharacter;
break;
case '^':
operatorStack.push(nextCharacter);
break;
case '+': case '-': case '*': case '/':
while (!operatorStack.isEmpty() &&
!isBigger(nextCharacter, operatorStack.peek())) {
postfixArray[postfixIndex++] = operatorStack.pop();
}
operatorStack.push(nextCharacter);
break;
case '(':
operatorStack.push(nextCharacter);
break;
case ')':
topOperator = operatorStack.pop();
while (topOperator != '(') {
postfixArray[postfixIndex++] = topOperator;
topOperator = operatorStack.pop();
}
break;
default:
break;
}
index++;
}
while (!operatorStack.isEmpty()) {
postfixArray[postfixIndex++] = operatorStack.pop();
}
// Create string only from the used portion of the array
return new String(postfixArray, 0, postfixIndex);
}
// Rest of the class remains the same (isBigger, precedenceLevel, evaluatePostfix, etc.)
private static boolean isBigger(char ch1, char ch2) {
return precedenceLevel(ch1) > precedenceLevel(ch2);
}
private static int precedenceLevel(char op) {
switch (op) {
case '(': return 0;
case '+': case '-': return 1;
case '*': case '/': return 2;
case '^': return 3;
default: throw new IllegalArgumentException("Operator unknown: " + op);
}
}
public static int evaluatePostfix(String postfix) {
StackInterface<Integer> valueStack = new LinkedStack<>();
int index = 0;
char nextCharacter = ' ';
Integer operandTwo, operandOne;
int result;
while (index < postfix.length()) {
nextCharacter = postfix.charAt(index);
switch (nextCharacter) {
case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h':
valueStack.push(getValue(nextCharacter));
break;
case '+': case '-': case '*': case '/': case '^':
operandTwo = valueStack.pop();
operandOne = valueStack.pop();
result = calculate(operandOne,operandTwo,nextCharacter);
valueStack.push(result);
break;
default: break;
}
index++;
}
return valueStack.peek();
}
private static Integer getValue(char op) {
Integer[] values = {2, 3, 4, 5, 6}; // a, b, c, d, e
return values[op-97];
}
private static Integer calculate(Integer opd1, Integer opd2, char opr) {
Integer intObj = 0;
switch (opr) {
case '+': intObj = opd1 + opd2; break;
case '-': intObj = opd1 - opd2; break;
case '*': intObj = opd1 * opd2; break;
case '/':
if (opd2.equals(0))
throw new ArithmeticException("Division by zero");
else
intObj = opd1 / opd2;
break;
case '^': intObj = (int) Math.pow(opd1, opd2); break;
default: break;
}
return intObj;
}
public static int evaluateInfix(String infix) {
StackInterface<Character> operatorStack = new LinkedStack<>();
StackInterface<Integer> valueStack = new LinkedStack<>();
int index = 0;
char nextCharacter = ' ';
char topOperator = ' ';
Integer operandTwo, operandOne;
int result;
while (index < infix.length()) {
nextCharacter = infix.charAt(index);
switch (nextCharacter) {
case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h':
valueStack.push(getValue(nextCharacter));
break;
case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
valueStack.push(Character.getNumericValue(nextCharacter));
break;
case '^':
operatorStack.push(nextCharacter);
break;
case '+': case '-': case '*': case '/':
while (!operatorStack.isEmpty() &&
!isBigger(nextCharacter, operatorStack.peek())) {
topOperator = operatorStack.pop();
operandTwo = valueStack.pop();
operandOne = valueStack.pop();
result = calculate(operandOne,operandTwo,topOperator);
valueStack.push(result);
}
operatorStack.push(nextCharacter);
break;
case '(':
operatorStack.push(nextCharacter);
break;
case ')':
topOperator = operatorStack.pop();
while (topOperator != '(') {
operandTwo = valueStack.pop();
operandOne = valueStack.pop();
result = calculate(operandOne,operandTwo,topOperator);
valueStack.push(result);
topOperator = operatorStack.pop();
}
break;
default: break;
}
index++;
}
while (!operatorStack.isEmpty()) {
topOperator = operatorStack.pop();
operandTwo = valueStack.pop();
operandOne = valueStack.pop();
result = calculate(operandOne,operandTwo,topOperator);
valueStack.push(result);
}
return valueStack.peek();
}
}

View File

@ -0,0 +1,45 @@
// @author Frank M. Carrano
// @author Timothy M. Henry
// @version 5.0
public class PostfixTest
{
public static void main(String arg[])
{
// Test convertToPostfix
System.out.println("Testing convertToPostfix");
String[] expressions = {"(a+b)/(c-d)","a/(b-c)*d","a-(b/(c-d)*e+f)^g",
"(a-b*c)/(d*e^f*g+h)"};
String[] qNums = {"a", "b", "c", "d"};
for (int i = 0; i < expressions.length; i++)
{
String postfix = Postfix.convertToPostfix(expressions[i]);
System.out.println(qNums[i]+". " + expressions[i] + " is converted to " + postfix);
}
System.out.println();
// Test evaluatePostfix
System.out.println("Testing evaluatePostfix");
String[] postfixes = {"a e + b d - /", "a b c * d * -","a b c - / d *",
"e b c a ^ * + d -"};
for (int i = 0; i < postfixes.length; i++)
{
int evaluation = Postfix.evaluatePostfix(postfixes[i]);
System.out.println(qNums[i]+". " + postfixes[i] + " is evaluated as " + evaluation);
}
System.out.println();
// Test evaluateInfix
System.out.println("Testing evaluateInfix");
String[] infixes = {"a+b*c-9", "(a+ e)/ (b- d)","a+(b+c*d)-e/2",
"e-b*c^a+d"};
for (int i = 0; i < postfixes.length; i++)
{
int evaluation = Postfix.evaluateInfix(infixes[i]);
System.out.println(qNums[i]+". " + infixes[i] + " is evaluated as " + evaluation);
}
}
}

View File

@ -0,0 +1,30 @@
/**
An interface for the ADT stack.
@author Frank M. Carrano
@author Timothy M. Henry
@version 5.0
*/
public interface StackInterface<T>
{
/** Adds a new entry to the top of this stack.
@param newEntry An object to be added to the stack. */
public void push(T newEntry);
/** Removes and returns this stack's top entry.
@return The object at the top of the stack.
@throws EmptyStackException if the stack is empty before the operation. */
public T pop();
/** Retrieves this stack's top entry.
@return The object at the top of the stack.
@throws EmptyStackException if the stack is empty. */
public T peek();
/** Detects whether this stack is empty.
@return True if the stack is empty. */
public boolean isEmpty();
/** Removes all entries from this stack. */
public void clear();
} // end StackInterface

View File

@ -0,0 +1,30 @@
/** An interface for the ADT deque.
@author Frank M. Carrano
*/
public interface DequeInterface<T>
{
/** Adds a new entry to the front/back of this deque.
@param newEntry An object to be added. */
public void addToFront(T newEntry);
public void addToBack(T newEntry);
/** Removes and returns the front/back entry of this deque.
@return The object at the front/back of the deque.
@throws EmptyQueueException if the deque is empty before the
operation. */
public T removeFront();
public T removeBack();
/** Retrieves the front/back entry of this deque.
@return The object at the front/back of the deque.
@throws EmptyQueueException if the deque is empty. */
public T getFront();
public T getBack();
/** Detects whether this deque is empty.
@return True if the deque is empty, or false otherwise. */
public boolean isEmpty();
/* Removes all entries from this deque. */
public void clear();
} // end DequeInterface

View File

@ -0,0 +1,17 @@
/**
A class of runtime exceptions thrown when an attempt is made to access
or remove the front of a queue
@author Hyunryung Kim
*/
public class EmptyQueueException extends RuntimeException
{
public EmptyQueueException()
{
this(null);
} // end default constructor
public EmptyQueueException(String message)
{
super(message);
} // end constructor
} // end EmptyQueueException

View File

@ -0,0 +1,156 @@
/**
A class that implements a deque of objects by using
a chain of doubly linked nodes.
@author Frank M. Carrano
*/
public final class LinkedDeque<T> implements DequeInterface<T>
{
private DLNode firstNode; // References node at front of queue
private DLNode lastNode; // References node at back of queue
public LinkedDeque()
{
firstNode = null;
lastNode = null;
} // end default constructor
/** Adds a new entry to the front/back of this deque.
@param newEntry An object to be added. */
public void addToFront(T newEntry)
{
DLNode newNode = new DLNode(null, newEntry, firstNode);
if (isEmpty())
lastNode = newNode;
else
firstNode.setPreviousNode(newNode);
firstNode = newNode;
} // end addToFront
public void addToBack(T newEntry)
{
DLNode newNode = new DLNode(lastNode, newEntry, null);
if (isEmpty())
firstNode = newNode;
else
lastNode.setNextNode(newNode);
// end if
lastNode = newNode;
} // end addToBack
/** Removes and returns the front/back entry of this deque.
@return The object at the front/back of the deque.
@throws EmptyQueueException if the deque is empty before the
operation. */
public T removeFront()
{
T front = getFront(); // Might throw an EmptyQueueException
assert firstNode != null;
firstNode = firstNode.getNextNode();
if (firstNode == null)
lastNode = null;
else
firstNode.setPreviousNode(null);
return front;
} // end removeFront
public T removeBack()
{
T back = getBack(); // Might throw an EmptyQueueException
assert lastNode != null;
lastNode = lastNode.getPreviousNode();
if (lastNode == null)
firstNode = null;
else
lastNode.setNextNode(null);
return back;
} // end removeBack
/** Retrieves the front/back entry of this deque.
@return The object at the front/back of the deque.
@throws EmptyQueueException if the deque is empty. */
public T getFront()
{
if (isEmpty())
throw new EmptyQueueException();
else
return firstNode.getData();
} // end getFront
public T getBack()
{
if (isEmpty())
throw new EmptyQueueException();
else
return lastNode.getData();
} // end getBack
/** Detects whether this deque is empty.
@return True if the deque is empty, or false otherwise. */
public boolean isEmpty()
{
return (firstNode == null && lastNode == null);
} // end isEmpty
/* Removes all entries from this deque. */
public void clear()
{
firstNode = null;
lastNode = null;
} // end clear
// @author Frank M. Carrano, Timothy M. Henry
// @version 5.0 */
private class DLNode
{
private T data; // Entry in bag
private DLNode previous; // Link to previous node
private DLNode next; // Link to next node
private DLNode(T dataPortion)
{
this(null, dataPortion, null);
} // end constructor
private DLNode(DLNode previousDLNode, T dataPortion, DLNode nextDLNode)
{
data = dataPortion;
previous = previousDLNode;
next = nextDLNode;
} // end constructor
private T getData()
{
return data;
} // end getData
private void setData(T newData)
{
data = newData;
} // end setData
private DLNode getNextNode()
{
return next;
} // end getNextDLNode
private void setNextNode(DLNode nextDLNode)
{
next = nextDLNode;
} // end setNextDLNode
private DLNode getPreviousNode()
{
return previous;
} // end getPreviousDLNode
private void setPreviousNode(DLNode previousDLNode)
{
previous = previousDLNode;
} // end setPreviousDLNode
} // end DLNode
} // end LinkedQueue

View File

@ -0,0 +1,54 @@
public class LinkedDequeDemo {
public static void main(String[] args) {
// Create a new LinkedDeque
LinkedDeque<String> deque = new LinkedDeque<>();
System.out.println("=== Testing LinkedDeque Operations ===");
System.out.println("Initial deque is empty: " + deque.isEmpty());
// Add elements to front and back
System.out.println("\nAdding elements to front and back:");
deque.addToFront("Front 1");
deque.addToBack("Back 1");
deque.addToFront("Front 2");
deque.addToBack("Back 2");
// Display front and back
System.out.println("Front element: " + deque.getFront());
System.out.println("Back element: " + deque.getBack());
// Remove elements
System.out.println("\nRemoving elements:");
System.out.println("Removed from front: " + deque.removeFront());
System.out.println("Removed from back: " + deque.removeBack());
// Display again
System.out.println("\nAfter removal:");
System.out.println("Front element: " + deque.getFront());
System.out.println("Back element: " + deque.getBack());
// Test isEmpty
System.out.println("\nDeque is empty: " + deque.isEmpty());
// Clear the deque
System.out.println("\nClearing the deque...");
deque.clear();
System.out.println("Deque is empty after clear: " + deque.isEmpty());
// Test exception handling
System.out.println("\nTesting exception handling:");
try {
System.out.println("Attempting to get front of empty deque...");
System.out.println(deque.getFront());
} catch (EmptyQueueException e) {
System.out.println("Caught EmptyQueueException: " + e.getMessage());
}
try {
System.out.println("Attempting to remove from back of empty deque...");
System.out.println(deque.removeBack());
} catch (EmptyQueueException e) {
System.out.println("Caught EmptyQueueException: " + e.getMessage());
}
}
}

21
test/ListInterface.java Normal file
View File

@ -0,0 +1,21 @@
public interface ListInterface<T>{
public void add(T newEntry);
public void add(int newPosition, T newEntry);
public T remove(int givenPosition);
public void clear();
public T replace(int givenPosition, T newEntry);
public T getEntry(int givenPosition);
public T[] toArray();
public boolean contains(T anEntry);
public int getLenght();
public boolean isEmpty();
}

122
test/Llist.java Normal file
View File

@ -0,0 +1,122 @@
public class LList<T> implements ListInterface<T>{
private Node firstNode;
private int numOfEntries;
public LList () {
initializeDataFields();
}
public void clear () {
initializeDataFields();
}
public void add (T newEntry) {
Node newNode = new Node(newEntry);
if (isEmpty) {
firstNode = newNode;
} else {
lastNode = getNodeAt(numOfEntries);
lastNode.setNextNode(newNode);
}
numOfEntries++;
}
public void add (int newPos, T newEntry) {
if((newPos < numOfEntries) && (newPos > 0)) {
Node newNode = new Node(newEntry);
if (newPos == 1) {
newNode.setNextNode(firstNode);
firstNode = newNode;
} else {
Node nodeBefore = getNodeAt(newPos - 1);
Node nodeAfter = nodeBefore.getNextNode();
newNode.setNextNode(nodeAfter);
nodeBefore.setNextNode(newNode);
}
numOfEntries++;
} else {
throw new e("Nope");
}
}
public boolean isEmpty(){
return ((numOfEntries > 0));
}
public T[] toArray () {
@SuppressWarnings("unchecked")
T[] result = (T[])new Object[numOfEntries];
Node currentNode = firstNode;
for (int i = 0; i < numOfEntries; i++) {
result[i] = currentNode.getData();
currentNode = currentNode.getNextNode();
}
return result;
}
public T remove (int givenPos) {
T result = null;
if (givenPos <= numOfEntries && givenPos > 0) {
if (!isEmpty()) {
if (givenPos == 1) {
result = firstNode.getData();
firstNode = firstNode.getNextNode();
} else {
Node nodeBefore = getNodeAt(givenPos - 1);
Node nodeToRemove = nodeBefore.getNextNode();
result = nodeToRemove.getData();
Node nodeAfter = nodeToRemove.getNextNode();
nodeBefore.setNextNode(nodeAfter);
}
numOfEntries--;
return result;
} else {
throw new e("NOOO");
}
}
}
public T replace (int givenPos, T newEntry) {
if(givenPos > 0 && givenPos <= numOfEntries) {
Node desiredNode = getNodeAt(givenPos);
T originalEntry = desiredNode.getData();
desiredNode.setData(newEntry);
return originalEntry;
} else {
throw new e("NOOOOOO");
}
}
// Start from node
private class Node {
private T data;
private Node next;
private Node (T dataPortion) {
this(dataPortion, null);
}
private Node (T dataPortion, Node nextNode) {
data = dataPortion;
next = nextNode;
}
private T getData () {
return data;
}
private void setData (T newData) {
data = newData;
}
private Node getNextNode () {
return next;
}
private Node setNextNode (Node nextNode) {
next = NextNode;
}
}
}