This commit is contained in:
2025-04-29 17:51:52 +03:00
parent 9e95d7d514
commit 86ef6a2f43
21 changed files with 1272 additions and 0 deletions

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