Add a class for storing sorted items

This commit is contained in:
Manuel Thalmann 2022-09-28 10:34:36 +02:00
parent 882130f703
commit 447e63837b

View file

@ -0,0 +1,46 @@
package ch.nuth.zhaw.exbox;
/**
* Represents a list with the ability to sort elements.
*/
public class MySortedList extends MyList {
@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public boolean add(Object item) {
if (isEmpty()) {
return super.add(item);
} else {
IListNode currentNode = getAnchor().getNextNode();
while (true) {
int comparisonResult;
try {
if (item instanceof Comparable x &&
currentNode.getItem() instanceof Comparable y) {
comparisonResult = x.compareTo(y);
} else {
throw new UnsupportedOperationException();
}
} catch (Exception e) {
comparisonResult = 0;
}
if (comparisonResult == 0) {
insertAfter(currentNode, item);
return true;
} else if (comparisonResult < 0) {
insertAfter(currentNode.getPreviousNode(), item);
return true;
} else {
currentNode = currentNode.getNextNode();
if (currentNode == getAnchor()) {
insertAfter(currentNode.getPreviousNode(), item);
return true;
}
}
}
}
}
}