Add a class for storing sorted items
This commit is contained in:
parent
882130f703
commit
447e63837b
1 changed files with 46 additions and 0 deletions
46
app/src/main/java/ch/nuth/zhaw/exbox/MySortedList.java
Normal file
46
app/src/main/java/ch/nuth/zhaw/exbox/MySortedList.java
Normal 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in a new issue