Kotlinlearncs.online LogoJava
Return to List

Homework: String Length Comparable Parameterized

Created By: Geoffrey Challen
/ Version: 2021.10.0

Create a public class named MyString. MyString should provide a public constructor that accepts a single String argument. You should reject null Strings in your constructor using assert.

MyString should also implement the Java Comparable<MyString> interface, returning 1 for a positive result and -1 for a negative result. Normally Strings are compared lexicographically: "aaa" comes before "z". MyString should compare instances based on the length of its stored String. So MyString("aaa") should come after MyString("z"), since "aaa" is longer than "z".

You will probably need to review the documentation for Comparable. Because we are using the type parameter MyString to the Comparable interface, compareTo accepts an MyString as an argument. The MyString passed to compareTo will not be null.

Related Lessons

Stuck? You may find these lessons helpful: