In: Computer Science
Let's get some practice implementing a known interface. 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 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. Note that compareTo accepts an Object as an argument, but you can reject non-MyString arguments using assert.
Note: Could you plz go through this code and let me
know if u need any changes in this.Thank You
=================================
// MyString.java
public class MyString implements Comparable<MyString>
{
private String str;
/**
* @param str
*/
public MyString(String s) {
assert s==null : "Invalid
String";
this.str=s;
}
/**
* @return the str
*/
public String getStr() {
return str;
}
/**
* @param str
* the str to set
*/
public void setStr(String str) {
this.str = str;
}
@Override
public int compareTo(MyString other) {
if (this.str.length() <
other.getStr().length())
return -1;
else if (this.str.length() >
other.getStr().length())
return 1;
return 0;
}
}
=====================================
========================================
// Test.java
public class Test {
public static void main(String[] args) {
MyString ms1 = new
MyString("aaa");
MyString ms2 = new
MyString("z");
int res =
ms1.compareTo(ms2);
if (res == -1) {
System.out.println(ms2.getStr() + " is longer than " +
ms1.getStr());
} else if (res == 1) {
System.out.println(ms1.getStr() + " is longer than " +
ms2.getStr());
} else {
System.out.println(ms1.getStr() + " is same as " +
ms2.getStr());
}
}
}
========================================
========================================
Output:
=====================Could you plz rate me well.Thank You