0

I just start my Java learning in my first year of University. One problem requires "Note that compareTo accepts an Object as an argument, but you can reject non-MyString arguments using assert."

So how can I reject these non String argument?

assert (object instanceof String)?

Hulk
  • 6,399
  • 1
  • 30
  • 52
  • 2
    You gave the answer yourself - try it out! But note: `object instanceof String` will also return `false` if `object` is `null`. – Jesper Oct 14 '20 at 14:17
  • 2
    Also note that while assert works fine for this while it is turned on, it can be [turned off via an option](https://stackoverflow.com/questions/11415160/how-to-enable-the-java-keyword-assert-in-eclipse-program-wise) at runtime and should therefore not be used as the only form of parameter validation in production code. Real code should usually throw an `IllegalArgumentException` instead. But you'll probably hear about that later in your course. – Hulk Oct 14 '20 at 14:23
  • 1
    You definitely want to talk to your instructor and ask him why they want you to use asserts, which have about zero relevance in real world java code. – GhostCat Oct 14 '20 at 14:33

1 Answers1

0

Yes, you can do it like that:

public boolean equals(Object other) {
   assert other instanceof MyString;
   // other checks
}

But as suggested: This will also reject that case that your argument is null. Which you sometimes want to check. So better would be in my opinion:

public boolean equals(Object other) {
   if (other == null) {
     return false;
   }
   // other checks
}

Most modern IDE will even provide an equals method for you including the corresponding hashCode.

jmizv
  • 1,172
  • 2
  • 11
  • 28
  • Thank you for your so fast reply!!! (I feel surprised that my question has been noticed by you.) – JinJinTwice Oct 14 '20 at 14:58
  • However, the question requires us 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. and 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". – JinJinTwice Oct 14 '20 at 15:01
  • When I use assert second instanceof MyStirng; in my method public int compareTo(Object second), it still gives me the error message cannot find symbol – JinJinTwice Oct 14 '20 at 15:02