سؤال

I'm working on a University assignment, and I have to store elements in an array of the "Comparable" type. Eg:

protected Comparable storage[];

The elements that will be stored in this array are going to be either all integers, or all strings, but they're obviously created with the "Comparable" type as opposed to being created as int, or String.

What I'm having problems doing is comparing these values. At any given point, say the array is filled with "Comparable" elements that are actually integers, how can I compare them? I get that I have to use the compareTo() method, but what would the implementation look like? I've looked at the Java document online, and it has simply confused me even more.

Just to summarize, at any given point, the array might have "Comparable" type elements that are actually all integers, or all the elements will be Strings that were also made with the "Comparable" type. There's no mixing and matching of the integer and Strings in the array, it's just one or the other. I want to know how I would make the compareTo() method so that I can easily compare two elements in the array, or any two "Comparable" elements for that matter, and return say a 1, -1, or 0 if one is greater/less than the other

Would appreciate any help. I'm completely lost.

هل كانت مفيدة؟

المحلول

You do not need to implement the compareTo methods for the Integer and String classes because they are already implemented and used. All you need to do is fill the array of comparables and that's it, if you call sort on them they will be properly sorted unless the array has mixed types of elements (strings and integers) which you mentioned that wouldn't be the case.

In the documentation you will find that both classes already implement comparable:

. http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html?is-external=true

http://docs.oracle.com/javase/7/docs/api/java/lang/String.html?is-external=true

Because these classes implement the interface according to polymorphism you can insert them in the mentioned array without any problems.

Strings are compared bases on the String class implementation of the compareTo method which according to the documentation mentioned would be using lexicographic order or they are compared lexicographically.

http://en.wikipedia.org/wiki/Lexicographical_order

Which basically means alphabetic order if all characters are lower case or all characters are upper case, and the characters with lower ascii value becoming smaller in comparison.

نصائح أخرى

You need not to implement/override the compareTo method. When you will call compareTo, this method will be called on either Integer/String class.

If you were filling the array with your own custom class type then u were required to override compareTo method,not with your current assignment requirement. Maybe u can take this challenge to learn more about Comparable in java.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top