I have trying to get this down to the bar minimum. I am trying to cast the desired object array to a array of comparable. This is all required by the assignment.
I am getting a runtime error that I can not perform the desired cast. What do I need to provide the compiler in order to allow for this casting. I can not change
the signature of the method however nothing about the class has been specified do I need to implement comparable? Also I don not now what the client is passing
so how would I write a generic compareTo method to compare object of unknown types. Thanks for any help.
And, just as important, it will give yousome idea where the Exception occurs.
Do you really have to have Object as the type of that parameter?
And welcome to the Ranch
I added code tags to your post. Always use the tags: doesn't it look better.
posted 5 years ago
Yes I had to make a Common Elements class that would use Object for a ADT & Algorithms class. What I didn't understand is that the client would already cast the array to a sub class of object like string or int prior to to passing the array to the method findCommonElements(). I will be sure to tag in the future. I am finding that I need to expand my network of Java companions since I am an online student and the school forums aren't active enough to help in the finer details of things like generics and ADT. I can read and repeat the text book but I am still learning the finer details of implementation and coding. Also the runtime error was saying that you can't cast object to comparable. I believe you would have to implement Comparable in order to do something to that effect as well as override the any methods used since it is an Interface. Feel free to correct any misconceptions I may have.
posted 5 years ago
An int is not a subtype of Object. It is a primitive.
Otherwise, yes, your array elements must all implement Comparable which means having a compareTo method which fulfils the general contract in Comparable. They also have to be mutually comparable otherwise the comparisons won't work, and you will suffer a different Exception. You can read about comparisons in the Java Tutorials.
I would query that assignment. In my opinion it is bad design to have to cast anything and you should require a Comparable argument. Then the error can be found at compile time. You cannot unfortunately put generics into the type of an array.
Curse your sudden but inevitable betrayal! And this tiny ad too!