From 447e63837b8c3ff0277312c557dbc414f0dacb96 Mon Sep 17 00:00:00 2001 From: Manuel Thalmann Date: Wed, 28 Sep 2022 10:34:36 +0200 Subject: [PATCH] Add a class for storing sorted items --- .../java/ch/nuth/zhaw/exbox/MySortedList.java | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 app/src/main/java/ch/nuth/zhaw/exbox/MySortedList.java diff --git a/app/src/main/java/ch/nuth/zhaw/exbox/MySortedList.java b/app/src/main/java/ch/nuth/zhaw/exbox/MySortedList.java new file mode 100644 index 0000000..ec4cdd1 --- /dev/null +++ b/app/src/main/java/ch/nuth/zhaw/exbox/MySortedList.java @@ -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; + } + } + } + } + } +}