• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Bear Bibeault
  • Paul Clapham
  • Jeanne Boyarsky
Sheriffs:
  • Junilu Lacar
  • Knute Snortum
  • Henry Wong
Saloon Keepers:
  • Ron McLeod
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
Bartenders:
  • Frits Walraven
  • Joe Ess
  • salvin francis

A better way to create and sort an array of objects?

 
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have completed this assignment the best way I know. The question is, is there a more efficient way to do this, without using more advanced Java concepts?
Here is the class:


And here is a sample implementation:


I appreciate any wise suggestions.
Thanks.
 
Saloon Keeper
Posts: 6571
61
Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
My interpretation of your requirements is that your sort method should take a second parameter, which is the field to sort on.
 
Master Rancher
Posts: 3656
34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Define an interface with one method that returns true if arg1 > arg2.  Define classes that implement the interface for each of the comparisons to be made.
Merge all the sort methods into one method that takes an instance of the interface and uses its method to compare two args.  Call that method with instances of the your class that do the comparisons.
 
Bartender
Posts: 1845
10
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I would take another look at the instructions in the comment.


What you have is five different methods, all very similar to one another

public static SchoolTextBook [] sortTextBooksByAuthor(SchoolTextBook [] textBookArray)
public static SchoolTextBook [] sortTextBooksByTitle(SchoolTextBook [] textBookArray)
public static SchoolTextBook [] sortTextBooksByIsbn(SchoolTextBook [] textBookArray)
public static SchoolTextBook [] sortTextBooksByPageCount(SchoolTextBook [] textBookArray)
public static SchoolTextBook [] sortTextBooksByPrice(SchoolTextBook [] textBookArray)

The only difference between these methods is the if statement you use to compare the two items.

Can you write one method that looks like this:
public static SchoolTextBook [] sortTextBooks(SchoolTextBook [] textBookArray, String sortProperty)
The difference is that you don't have the same code repeated 5 times with subtle variations.
It is more efficient in the amount of code you write if nothing else :-)

You could probably write a helper method:
boolean bookIsGreaterThanAnother(SchoolTextBook book1, SchoolTextBook book2, String property)
book1 and book2 are the books to compare
property is the property of the bean to use to compare
returns true if book1 is "greater than" book2, otherwise false.

You could then replace the if statement with that method.


One thing I have noted is your method signature could be


You are actually editing the textBookArray in place, and don't need to return it explicitly.
This makes it clearer to anybody looking at it.  Otherwise they might assume that it returns a "sorted" array while leaving the original unsorted.

In terms of efficiency, you could look at your algorithm for sorting.  You have used the "Bubble Sort" algorithm here.
It is not a very efficient algorithm for sorting.  You might research other possible search algorithms (google and wikipedia will be of great help here and will explain it better than I ever could)
 
Marshal
Posts: 66949
255
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can you think how you would write Comparators<Book> like compareByAuthor, etc., Stephan? I think it would match common Java® practice better than creating one's own classes. But it is the same concept.

OP: Have a look at the Java™ Tutorials; I think that section will be helpful. You will have to find some way of going from the String to the Comparator. One possibility is a switch statement.
 
Ray Bell
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First of all, the comment about taking two parameters was one that I wrote, thinking at first that I could do things that way. I ended up creating separate methods because of the subtle differences a) between comparing strings and comparing numbers and b)using the different getmethods depending on the choice.

I like the idea of changing it to a static method, which leads to simpler code in the implementation. I will do that.

I looked at the possibility of using a comparator. The question is if this would really create more efficient, simpler code than the 5 methods I have right now in the class?

I will take a closer look at some of the specific suggestions here and see if I can figure out how to make them work.

Re: bubble sort. let's just leave that alone for now...

Thanks everyone.
 
Campbell Ritchie
Marshal
Posts: 66949
255
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Ray Bell wrote:. . . I like the idea of changing it to a static method . . .

I think you should only write static methods when you have a good explanation for their being static. I don't think you have supplied such an explanation.

I looked at the possibility of using a comparator. The question is if this would really create more efficient, simpler code than the 5 methods I have right now in the class?

Yes. Your code is full or repetitions as it stands. You can supply five Comparators<Book> and pass them all to the same method.

. . . Re: bubble sort. let's just leave that alone for now...

Why? What sort of algorithm are you using at present?

Thanks everyone.

That's a pleasure
 
Ray Bell
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here is how I tried to implement one of the suggestions


I am having problems as follows:
SchoolTextBookTry.java:207: error: cannot find symbol
       if(book1.sortProperty.compareTo(book2.sortProperty) > 0)
                                            ^
 symbol:   variable sortProperty
 location: variable book2 of type SchoolTextBookTry
SchoolTextBookTry.java:207: error: cannot find symbol
       if(book1.sortProperty.compareTo(book2.sortProperty) > 0)
               ^
 symbol:   variable sortProperty
 location: variable book1 of type SchoolTextBookTry
2 errors

Also, I am confused as to when I should be calling the methods static, and also when I should use void, and when I should use a type, with a return.

I plan to try using the comparator for this as well, once I can get it to work this way.
Thanks for all your help and suggestions.
 
Norm Radder
Master Rancher
Posts: 3656
34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

SchoolTextBookTry.java:207: error: cannot find symbol
       if(book1.sortProperty.compareTo(book2.sortProperty) > 0)
                                            ^
 symbol:   variable sortProperty
 location: variable book2 of type SchoolTextBookTry


There isn't a variable named sortProperty in the SchoolTextBookTry class.

I'm not sure how that approach will work.  I don't see how a String (sortProperty) can be used to access a variable inside of an instance of a class (book2)  (except if a Map was used).
 
Carey Brown
Saloon Keeper
Posts: 6571
61
Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Are you familiar with interfaces? You could make a Compare interface the specifies a method that will compare two SchoolTextBook objects. Then you'd need several classes that implement that interface, such as CompareAuthor etc.. Then create a Compare variable and assign to it a new CompareXXX object depending on your "choice" variable. Finally, use that Compare variable to do the actual comparison.

 
Ray Bell
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for clarifying for me that there is no way to take a string property and turn it into a getproperty() inside the method. Based on the last couple of responses, it seems to me that I have two choices: either keep the 5 different methods for sorting in the SchoolTextBook class, as I did originally, or create 5 comparator methods in an interface. Please correct me if I'm wrong, but it seems to me that the second way, creating an interface with 5 comparators, would take more code, and be more complex to write and implement. The advantage to doing that is that I could theoretically reuse that interface with any class or method, is that correct?

I have not yet used interfaces or comparators yet...
 
Norm Radder
Master Rancher
Posts: 3656
34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

creating an interface with 5 comparators, would take more code,


It would not take more code.  The Comparators would have at most a couple of lines of code.  There would only be ONE sort method, instead of one for each field to sort on.
If it is allowed in the assignment to use the Arrays class's sort method, you would not need any of your own sort methods.

I have not yet used interfaces or comparators yet...


Time to try using interfaces and  Comparator
 
Marshal
Posts: 7346
498
Mac OS X VI Editor BSD Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Few somewhat other observations.

1. Probably isn't optimal to call class a SchoolTextBook. Book is a book, and that is pretty much it. Call it Book. That way you don't bound yourself to school domain.

2. In the same class you have a field 'isbn'. ISBN varies based the year book was released. There could be either 10 or 13 digits. You don't seem validating that - that is the one and truly reliable figure to identify the book (if valid).

3. All your sort methods return sorted array, BUT, what they also do, they modify originally passed array. That might be a problem. Safer and more reliable way is, write methods so they wouldn't have side effects. To achieve that you could make a copy of passed in array and then sort it, that way you wouldn't modify original array - which is less error prone as it may be dependant in some other place - which may be an indication of a problem too.

4. Your indentation quite good, but isn't perfect. Some braces starting from line 79 (not all) are shifted by 1 space too far to the left. You also have some formatting issues, where there are some empty lines (sometimes 2, sometimes 3) without any logical explanation why.

5. Line 200 is way too long. Please split it to several lines, so it would occupy around 80 characters width.

6. Line 202. Closing brace is also seem to be off.

7. 202 lines. Might be too long as for a class? Maybe some duplicated code? Yes there are. Look at those swap actions when sorting books. All those swaps would be a one method used over and over, that would shorten your code right away by 10 lines.

8. All those sorting methods's loops look duplicated. Two for loops + if. Two for loops + if. Two for loops + if. Maybe can become a helper method? So would get shortened about another 50 lines or so.

9. After loop 'for' you don't place space character before opening '(' round bracket. There really supposed to be a space.

10. Don't call variables "someArray" (textBookArray). Array is an implementation detail, that may change, so you'd need to change not only the data structure but all variables referencing it too.
 
Ray Bell
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes! That is exactly where I started. Trying to use Arrays.sort and coming across this new term Comparable, Comparator, etc. So, you are saying I should go back, create 5 comparators, use one method with two inputs, and choose a comparator based on the second input - property. Right, Sherriff? Ok, I will hit the tutorials and try to figure this out... Do I need an interface or can I just put the comparators into my Book class?

Thanks to the last contributor for the detailed feedback, this is really important for me to get this help in improving my work. Just wondering if you can please clarify one thing. Are you saying I can leave out the [] sign and everything will work just the same?

I appreciate all of your help.
 
Campbell Ritchie
Marshal
Posts: 66949
255
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Ray Bell wrote:. . . coming across this new term Comparable, Comparator, etc.

Did you find out anything useful in the Java Tutorials link I posted on Friday?

. . . I should go back, create 5 comparators, use one method with two inputs, and choose a comparator based on the second input - property.  . . .

Yes. The code Carey showed yesterday gives identical functionality to a Comparator<Book> only it is specialised to Books only whereas you can write a Comparator for any kind of object. It should be in the tutorials link I gave you.

can I just put the comparators into my Book class? . . .

You can have Comparators anywhere. Maybe the book class will have ready‑made Comparators, maybe AUTHOR_COMPARATOR or PAGE_COUNT_COMPARATOR. The String class has one rather like that. Or you can create Comparator instances wherever you are doing the sorting

I can leave out the [] sign and everything will work just the same?

When you pass the name of an array, it doesn't include []
The type is Racehorse[] and the name stables doesn't include [].I hope I have answered the right question.

I appreciate all of your help.

That's a pleasure
 
If we don't do the shopping, we won't have anything for dinner. And I've invited this tiny ad:
Java file APIs (DOC, XLS, PDF, and many more)
https://products.aspose.com/total/java
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!