wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes Sorting arrays Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Sorting arrays" Watch "Sorting arrays" New topic
Author

Sorting arrays

Debra Simeroth
Ranch Hand

Joined: Jun 11, 2009
Posts: 33
I have a set of arrays related to inventory. One int array each to store product number and item count, one double array each for cost and total value of items, and one string array holding the item name. I need to sort the items alphabetically according to the string, without interfering with the other information. I am not sure how to approach this. Should I convert each item and its associated data in to a string representation and then sort, or should I try to use a sort or comparator method. I am a beginner, taking a class in Java and am not sure which method is best. We have not covered this yet, and references in the textbook are incomplete up to this point. Thanks in advance for your help.
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14074
    
  16

Do you mean that you have a number of arrays in such a way that the elements at position N in each array belong together? For example:

And now you want to sort all those arrays at the same time by item name?

Is the way you set the data up like this part of the assignment, or did you come up with this yourself?

Storing the data separately like this is very cumbersome and not object oriented. It would be much easier and better if you would create a class to hold all the information about an item, and then create an array of instances of that class, for example:

Now you could use the Arrays.sort(...) method to sort your array of Item objects. You'll need to implement a Comparator to compare the items by name.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
D. Ogranos
Ranch Hand

Joined: Feb 02, 2009
Posts: 214
You might consider merging your data. If I understand your situation correctly, you have several arrays of data which all belong together logically...why not write a class "DataItem" or similar, containing the name string, product number etc. Then make an array of that DataItem type. Once you have done that, you can have a look at java.util.Arrays, and use one of the sort() methods there (you will have to write a Comparator class for the sort). If things are unclear at any point, come back
Debra Simeroth
Ranch Hand

Joined: Jun 11, 2009
Posts: 33
I was under the impression that an array can only hold one type of data, e.g. all int, double, string, etc. In this assignment, the data has to be stored in an array. This approach seemed cumbersome to me too, but with the restrictions seemed to make sense. I am happy to rework the assignment into something that will really work well. Jesper, it looks like your ideas are by far the best, however, if an array is supposed to only store one type of data, how will that work? Will each item be imported into the array as a string? How will data operations work, for example if I want to add up the total dollar value of the products? Thanks again for your response!
D. Ogranos
Ranch Hand

Joined: Feb 02, 2009
Posts: 214
Note line 20 of Jesper's example: he declares an array of type "Item". This is the datatype he created in the class above. So, all elements in that array are of the same type, as required

Maybe you haven't had the lesson about objects in Java yet, but if you have an Item object (created with the line


), then you can access the elements in it by writing


Of course you must give it some value first:

Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19653
    
  18

A bit off-topic here, but I had to correct you:
Debra Simeroth wrote:I was under the impression that an array can only hold one type of data, e.g. all int, double, string, etc.

Not exactly. The rule is: the array can hold any values that is assignable to the array's type. For instance:
Basically, the rules for assigning an array element is the same as assigning a variable: wider (e.g. Integer -> Object, int -> double) is allowed, narrower (e.g. Object -> Integer, double -> int) only with a cast, and completely unrelated (e.g. Integer -> String, int -> boolean) not at all.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Debra Simeroth
Ranch Hand

Joined: Jun 11, 2009
Posts: 33
Thank you everyone, I will try this. I am sure that you will hear from me again on this. This is an online class, so without the benefit of a lecture or someone to ask questions of it can get a little confusing. There are so many nuances to Java that sometimes associating them correctly is a problem. Thanks for being here.... I really don't know anyone who is a programmer that I can ask these clarifying questions of and get such a quick response! You guys are really lifesavers for me in this class.

I will have other Java programming classes in my pursuit of my bachelors and really need to get this stuff down. Thanks again!
Fred Hamilton
Ranch Hand

Joined: May 13, 2009
Posts: 679
Debra Simeroth wrote:I have a set of arrays related to inventory. One int array each to store product number and item count, one double array each for cost and total value of items, and one string array holding the item name. I need to sort the items alphabetically according to the string, without interfering with the other information. I am not sure how to approach this. Should I convert each item and its associated data in to a string representation and then sort, or should I try to use a sort or comparator method. I am a beginner, taking a class in Java and am not sure which method is best. We have not covered this yet, and references in the textbook are incomplete up to this point. Thanks in advance for your help.


I agree with the posts of others who support making this more object oriented. But if it turns out that, for the purpose of the asignment, you do need to use a separate array for each data type, then each array would be the same size, right? And presumably related items would have the same index for each array, right? So you would only need to actually make comparisons on one array, item name, which is already string, and whatever shuffle you would make in this array, the same shuffles would be made in the other arrays. So I am not sure why you are talking about converting data to a string representation.
Debra Simeroth
Ranch Hand

Joined: Jun 11, 2009
Posts: 33
I'm Back! I could take the easy way out and just try to make the code that I have work, however I don't think that would serve me well. I went back to the drawing board and as suggested, went with a more OO approach. So far, I just have my class and the array in which to store them, however the array is not populating with the assigned data. I can't figure out what the problem is...


and the item class


It compiles and prints in the way I want it but all the values are null and 0.
Your suggestions are appreciated.

[edit]Add new lines because some lines longer than screen width. CR[/edit]
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18523
    
  40

It compiles and prints in the way I want it but all the values are null and 0.
Your suggestions are appreciated.


It's your constructor...



I am assuming that you want to assign the parameter to the instance variable. However, since your parameter and the iinstance variable has the same name, you are simply assigning the param to itself.... you probably want this...



Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Debra Simeroth
Ranch Hand

Joined: Jun 11, 2009
Posts: 33
WOO HOO! Worked! Now back to the original sort problem.... I will bend my brain a while and get back to you if I can't figure it out... We are using Java How to Program by Deitel and Deitel, (we just finished chapter 10) so far there are no sort functions covered in the text and we are supposed to sort by product name. Any tips on which way to go? An enhanced for loop?
Fred Hamilton
Ranch Hand

Joined: May 13, 2009
Posts: 679
Debra Simeroth wrote:WOO HOO! Worked! Now back to the original sort problem.... I will bend my brain a while and get back to you if I can't figure it out... We are using Java How to Program by Deitel and Deitel, (we just finished chapter 10) so far there are no sort functions covered in the text and we are supposed to sort by product name. Any tips on which way to go? An enhanced for loop?


I'm not well acquainted with advanced techniques for sorting, but any basic sort I've ever done involves a nested loop, a loop within a loop so to speak. Call that a hint. Good luck with the exercise.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19653
    
  18

Debra Simeroth wrote:WOO HOO! Worked! Now back to the original sort problem.... I will bend my brain a while and get back to you if I can't figure it out... We are using Java How to Program by Deitel and Deitel, (we just finished chapter 10) so far there are no sort functions covered in the text and we are supposed to sort by product name. Any tips on which way to go? An enhanced for loop?

Now that you have one single array with Item objects, there are two ways:

1) make Item implement Comparable<Item>:
You can then use Arrays.sort(itemObjects);

2) Use a custom Comparator<Item>. The comparison code will basically be similar to my above code. You can then use Arrays.sort(itemObjects, comparator);
Fred Hamilton
Ranch Hand

Joined: May 13, 2009
Posts: 679
Rob Prime wrote:
Debra Simeroth wrote:WOO HOO! Worked! Now back to the original sort problem.... I will bend my brain a while and get back to you if I can't figure it out... We are using Java How to Program by Deitel and Deitel, (we just finished chapter 10) so far there are no sort functions covered in the text and we are supposed to sort by product name. Any tips on which way to go? An enhanced for loop?

Now that you have one single array with Item objects, there are two ways:

1) make Item implement Comparable<Item>:
You can then use Arrays.sort(itemObjects);

2) Use a custom Comparator<Item>. The comparison code will basically be similar to my above code. You can then use Arrays.sort(itemObjects, comparator);


mmm, nice, I hadn't thought about using a built in sort function, I just thought this was an exercise in writing a sort. I guess not.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19653
    
  18

Well, if it is, then my code would surely result in a big fat F
Debra Simeroth
Ranch Hand

Joined: Jun 11, 2009
Posts: 33
Rob Prime wrote:Well, if it is, then my code would surely result in a big fat F


Well, I could end up with a D but considering my efforts, I should have at least a B+ for effort and TIME! I am happy with what I have achieved this far and will review your comments about sorting since that is still an issue, however due to the late hour and babysitting my dementia ridden grandma this weekend, my brain cells are running on empty. I CAN'T seem to calculate a total inventory value. It was easy to do with multiple arrays like I started with, but now I'm loosing it. Any advice is appreciated...



Any help you can offer is appreciated.... I hope that with just a few tweaks I can meet the assignment criteria... and to sleep one night without dreaming about how to make this work.... nitey nite!

[edit]New lines added, as before. CR[/edit]
Debra Simeroth
Ranch Hand

Joined: Jun 11, 2009
Posts: 33
Never mind... some of Grandma's dementia had temporarily rubbed off. I got it!
Debra Simeroth
Ranch Hand

Joined: Jun 11, 2009
Posts: 33
This is due today.... HELP! I have completed the code as recommended, but am having trouble getting it to execute. It compiles, but throws a Class Cast Exception. I can't see if its is sorting because the exception is at that point in the code. Here is what I have.




I would also like some feedback on the code itself, if anyone wants to critique it. this class is moving so quickly I am overloaded in what I am learning. We are finishing up Week 6 and my brain is having a "stack overflow". So any discussion about the code is appreciated.



[edit]Newlines because code too wide for screen. CR[/edit]
Christophe Verré
Sheriff

Joined: Nov 24, 2005
Posts: 14687
    
  16

I didn't look at the whole code, but one thing caught my eyes : public interface Comparable
You don't have to make this interface. It's an interface from the API : java.lang.Comparable.


[My Blog]
All roads lead to JavaRanch
Debra Simeroth
Ranch Hand

Joined: Jun 11, 2009
Posts: 33
Christophe Verré wrote:I didn't look at the whole code, but one thing caught my eyes : public interface Comparable
You don't have to make this interface. It's an interface from the API : java.lang.Comparable.




THANKS! THAT DID IT!
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38005
    
  22
Since the java.lang.Comparable interface and your Comparable interface have different method signatures, the Arrays#sort method would be unable to find the compareTo() method until you deleted your own interface.

By the way: it should be public class Item implements Comparable<Item> then you can use public int compareTo(Item i) as your method heading.
D. Ogranos
Ranch Hand

Joined: Feb 02, 2009
Posts: 214


The Item class represents a single item. It would still be good to put any methods related to items there. In this case where you want to have a method work with an array of Items, you could use a static method in the Item class:



You then call this in your main program with


deepika bhatia
Greenhorn

Joined: Jun 26, 2009
Posts: 10
Class Cast Exception is thrown when "attempting to cast a reference variable to a type that fails the IS-A test".
in this code you are comparing the values but you need to implement Comparable<Item> to pass the IS-A test

Use :
public class Item implements Comparable<Item>

while defining class item
Debra Simeroth
Ranch Hand

Joined: Jun 11, 2009
Posts: 33
D. Ogranos wrote:

The Item class represents a single item. It would still be good to put any methods related to items there. In this case where you want to have a method work with an array of Items, you could use a static method in the Item class:



You then call this in your main program with




Thanks for this one... I tried and tried to put this into my Item class but COULD NOT call it from the main method. Why is it that I could not call this with a regular method call? What do I need to study here? I reviewed methods and their calls but spent about 4 hours spinning my wheels. Its a real bummer only having an internet teacher, but I am so glad that this forum is here!
David Newton
Author
Rancher

Joined: Sep 29, 2008
Posts: 12617

Without knowing what code didn't work I'd assume that you were trying to call a non-static method from a static context or without an instantiated object.
D. Ogranos
Ranch Hand

Joined: Feb 02, 2009
Posts: 214
Static methods can only be called with their name if they are in the same class. If the method is defined in another class, you have to put that classes' name in front of the method name. So:

- define a class A with a static method myMethod()
- write a class B (this could be the class containing your main method)
- to call myMethod() in class B, you write A.myMethod()

The same way is also used to access other static members of a class (constants etc)
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Sorting arrays
 
Similar Threads
Iterating a Two Dimensional Array
Errors while compiling
new to Cattle Drive
how to easily sort the same TreeSet few times?
Sorting collection of objects