• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 210
  • Last Modified:

having a nightmare with sorting objects in an array !!!!

I'm trying to sort an array of objects, but I keep running into the same problems over and over again.

Array declaration:  
    MyBag stuff = new MyDB(10);

Here is the beginning of the MyDB class so that the "stuff" declaration might make a little more sense:
     public class MyDB implements MyBag
     {
          private Object[] theData;
          private int numItems;

          public MyDB(int size)
          {
               numItems = 0;
               theData = new Object[size];
          }


From within the driver, I am calling the sorting via:
    ((MyDB)stuff).sortTheData();

**********************
Now here's where it gets a little tricky .... Let's take a look at the "stuff" object!   ---->
     theData[0] = CD
          artist = "Tori Amos"
          director = null
          minutes = 57
          seconds = 7.0
          title = "Little Earthqueakes"
     theData[1] = DVD
          artist = null
          director = "Rob Reiner"
          minutes = 98
          seconds = 0.0
          title = "Princess Bride, The"
     theData[2] = VideoTape
          artist = null
          director = "Merian Cooper"
          minutes = 103
          seconds = 0.0
          title = "King Kong"
     theData[3] = AudioTape
          artist = "X"
          director = null
          minutes = 37
          seconds = 45.0
          title = "Los Angeles"
     theData[4] = VideoTape
          artist = null
          director = "John Guillermin"
          minutes = 134
          seconds = 0.0
          title = "King Kong"
     theData[5] = null
     theData[6] = null
     theData[7] = null
     theData[8] = null
     theData[9] = null
 ****************************    

The next thing I should probably point out is the class hierarchy:
                                                     
  -   Recording implements Comparable
            Audio extends Recording
                      AudioTape extends Audio
                      CD extends Audio
            Video extends Recording
                      VideoTape extends Video
                       DVD extends Video

  -  MyDB implements MyBag
  -  Driver

*******************************

The objects need to be sorted based on title, but in the chance of a duplicate (theData[2] & theData[4] for instance - both being "King Kong"), either director or artist is compared.     Artist is specific to Audio and director is specific to Video.

********************************

Back to the actual dilemma ----->
     when "((MyDB)stuff).sortTheData();" is triggered from the driver, it calls the following in the MyDB class:
             
       public void sortTheData()
       {
             for (int i = numItems; i<theData.length; i++)
             {
                   theData[i] = new Object();
             }
             Arrays.sort(theData);
       }

I'm not sure if the Arrays.sort(theData) quite right, but I'm pretty sure that will suffice as long as I nail down the compareTo(Object o) method in the Recording class ....................   THIS IS WHERE I'M BEAT !!!!!!!    Everything I've tried either gives me a NullPointerException or a ClassCastException!


COULD SOMEBODY PLEASE HELP !!!!!!!!!


Regards,
Travis
0
trs28
Asked:
trs28
  • 8
  • 8
1 Solution
 
CEHJCommented:
Why have you not declared

private Recording[] theData;

given your hierarchy?
0
 
trs28Author Commented:
Well, this is how I have it working ... hopefully this helps provide enlightenment! :)
Hell, I'm excited I got an answer already!   I love experts-exchange!

Following "MyBag stuff = new MyDB(10);" in the driver is a call to a static method  -->   initData(stuff);

Here is that method:   (right now, I just have dummy data in, but eventually these will contain inputted values)

public static void initData(MyBag stuff)
      {
            Recording currItem =
                  new CD("Little Earthquakes", 57, 7);
            ((Audio)currItem).setArtist("Tori Amos");
            stuff.addElement(currItem);
            
                 currItem =
                  new DVD("Princess Bride, The", 98, 0);
            ((Video)currItem).setDirector("Rob Reiner");
            stuff.addElement(currItem);

            currItem =
                  new VideoTape("King Kong", 103, 0);
            ((Video)currItem).setDirector("Merian Cooper");
            stuff.addElement(currItem);

            currItem =
                  new AudioTape("Los Angeles", 37, 45);
            ((Audio)currItem).setArtist("X");
            stuff.addElement(currItem);

            currItem =
                  new VideoTape("King Kong", 134, 0);
            ((Video)currItem).setDirector("John Guillermin");
            stuff.addElement(currItem);
      }
0
 
CEHJCommented:
Once having done that, you can override your Comparable methods:


public class Audio extends Recording {
      ...
      public int compareTo(Object o) {
            int result = super.compareTo(o);
            if (result == 0) {
                  return artist.compareTo(((Audio)o).artist);
            }
      }
}

public class Video extends Recording {
      ...
      public int compareTo(Object o) {
            int result = super.compareTo(o);
            if (result == 0) {
                  return director.compareTo(((Video)o).director);
            }
      }
}

0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
CEHJCommented:
Sorry, each of those methods should finish with

else {
    return result;
}
0
 
trs28Author Commented:
Still errors on me ... here is the Stack Trace:

Exception in thread "main" java.lang.ClassCastException: DVD
      at Audio.compareTo(Audio.java:49)
      at java.util.Arrays.mergeSort(Unknown Source)
      at java.util.Arrays.mergeSort(Unknown Source)
      at java.util.Arrays.sort(Unknown Source)
      at MyDB.sortTheData(MyDB.java:32)
      at Assig4a.main(Assig4a.java:68)

I see that you've overridden the compareTo(Object o) method in the Audio and Video subclasses, but how do I structure it in the Recording class???   It's not like it'll just let me omit it given that it's the class that's actually implementing the Comparable interface.
0
 
CEHJCommented:
Like this:

public class Recording implements Comparable {
      ...
      public int compareTo(Object o) {
            return title.compareTo(((Recording)o).title);
      }
}

0
 
trs28Author Commented:
ahhh!    now it's all starting to come together!   ....but... still have a little problem .....

Exception in thread "main" java.lang.ClassCastException: java.lang.Object
      at Recording.compareTo(Recording.java:12)
      at Video.compareTo(Video.java:45)
      at java.util.Arrays.mergeSort(Unknown Source)
      at java.util.Arrays.mergeSort(Unknown Source)
      at java.util.Arrays.sort(Unknown Source)
      at MyDB.sortTheData(MyDB.java:32)
      at Assig4a.main(Assig4a.java:68)


does that make any sense?  it doesn't seem to like your return title.compareTo(((Recording)o).title);

is there any other data that would be helpful for you to have in helping me with this little speedbump?
0
 
CEHJCommented:
Incidentally, sorting is not meant to work with disparate objects, and if you try to, you'll get ClassCastException. You can only compare an Audio with a Video *as Recording*.
0
 
CEHJCommented:
Given your Comparable implementations, which enforce the rules you want, you can see it doesn't make sense to compare a directory and an artist anyway, ClassCastException apart
0
 
trs28Author Commented:
Well exactly, the only time there is a need to compare anything other than the title names is when there is a duplicate, as in the case of the two "King Kong" entries.   At that point, then there is a need to compare the director, but never a director with an artist.  

Being that these are all decendants of Recording, I'm sure there's a way to sort these objects.   Again, the only thing being compared is the title.   Regardless of whether they fall from the Video or Audio classes, I'm just trying to put them in alphabetical order within the array.   Again, should a duplicate title be found, either the artist OR director values are compared between the duplicate objects respectively.

Does that help any?  I know there's a way to sort these damn things ... I just know it!   :)    Regardless, I appreciate all the input you've had (and hopefully will continue to have too) !!!!!  
0
 
CEHJCommented:
The best way to do it if you do have a 'bag' of types is to use a custom Comparator and typecheck
0
 
trs28Author Commented:
now you've gone way above my head - i'm fairly new & normally comfortable with Comparable

might the problem have anything to do with the null values (theData[9] = null, etc) .... I did initialize them to empty Objects:

for (int i = numItems; i<theData.length; i++)
{
     theData[i] = new Object();
}
Arrays.sort(theData);


I doubt it would make a difference if I initialized them to something other than Object ... say Recording ?!?!?

0
 
trs28Author Commented:
i've been tracing through the execution & i see what's happened ... its similar to what i wrote about the null array values ... it blows up when it tries to compare title = "King Kong" & title = null.   how can i stop the comparison after the last object ????

maybe I shouldn't initialize the remaining indexes in the array ?!?!?
0
 
trs28Author Commented:
Just wanted to let you know that I figured it out !!!!!

The key was to not sort via "Arrays.sort(theData);"

The key was to sort via "Arrays,sort(theData, 0, numItems);"

that way, it didn't try to sort any null references !!!    



Regardless CEHJ, I couldn't have done it without all your help!   I can't tell you how much I appreciate everything !!!    I'm tickled that I figured it out myself though!   Maybe I'll be a programmer afterall!   Thank god for debuggers!
0
 
CEHJCommented:
Yes, you need to have the correct type. Recording[] is what you need
0
 
trs28Author Commented:
I see your point ... that's some fine tuning for down the road!   Thanks again!   Take care!
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

  • 8
  • 8
Tackle projects and never again get stuck behind a technical roadblock.
Join Now