12 Replies - 1653 Views - Last Post: 25 November 2009 - 08:49 AM Rate Topic: -----

#1 nobodycool  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 14
  • Joined: 24-November 09

Creating an array of objects

Post icon  Posted 24 November 2009 - 06:40 PM

Hello there,


I am working on an assignment for school and I am having a hard time understanding the concept of an array of objects. I am required to create an array of Music objects so that I can search through them via a binary search and make changes as stipulated by reading a .txt file.

My problem is, I do not think I understand Object arrays properly. I can not seem to populate the array from the Music class. Do I populate in the instanceOf if block? Does it matter? I have two test populations of the array under the music instance of RockSong block and on trying to System.out.println() the output for accuracy I just get a null result. Any shove in the right direction would be most appreciated. Thank you.



public class Main
{
	private TextFileReader listenFile;
	private ListenFile currentRecord, nextRecord;
	private Music music;

	String listenDate = "";
	String listenName = "";
	String musicType ="";
	String rockGroup = "";
	String musicName = "";
	Calendar date;
	Calendar closeDate;
	Date df;

   public static void main (String args[])
   {
	(new Main()).DisplayFile();
   }

   private void DisplayFile()
	   {
	   int count =0;


	 ObjectInputStream inFile = null;
	 try
	 { inFile = new ObjectInputStream (new FileInputStream("music.dat"));}
	 catch (IOException ioex) { System.out.println ("ERROR Opening"); System.exit(1); }

	 try
	 {
		 while (true)
		 {
			 Music music = (Music)inFile.readObject();
			 Music[] musicArray= new Music[300];
			 

			 if (music instanceof RockSong){

				 musicArray[0].name = music.name;
				 muiscArray[1].timesPlayed = music.timesPlayed;
						 
					  }

			 if (music instanceof ClassicalPiece){
		  

			 }
			 if (music instanceof Musical){
				closeDate = (((Musical)music).close);
				  if (closeDate == null) {
				   ((Musical)music).close=Calendar.getInstance();
				 }

			 }
			  System.out.println(musicArray[count]);

			  count++;

		   }
	 }
	 catch (EOFException eofex) { System.out.println ("\nDONE");}
	 catch (IOException ioex) { System.out.println ("ERROR Reading"); System.exit(1); }
	 catch (ClassNotFoundException cnfex) { System.out.println ("ERROR class"); System.exit(1); }

   }



And here are my classes:

class Music implements Serializable
{
	 String name;
	 int timesPlayed;
	 Calendar lastTime;
}

class RockSong extends Music
{
	 String group;
}

class ClassicalPiece extends Music
{
	 String composer;
	 String type;
}

class Musical extends Music
{
	 Calendar open;
	 Calendar close;
}




Is This A Good Question/Topic? 0
  • +

Replies To: Creating an array of objects

#2 Dogstopper  Icon User is offline

  • The Ninjaducky
  • member icon



Reputation: 2857
  • View blog
  • Posts: 10,961
  • Joined: 15-July 08

Re: Creating an array of objects

Posted 24 November 2009 - 06:56 PM

First off, you reinitialize this array every itereation...
Music[] musicArray= new Music[300];



Notice how it's INSIDE the while loop? It would work much better as an instance variable instead.

You must add a counter variable to the while loop to keep track of the loop index...
Here is what I mean.
// defined Music[] musicArray= new Music[300]; before this method.
		 while (true)
		 {
			 Music music = (Music)inFile.readObject();			 

			 if (music instanceof RockSong){
				 // Inside each of these, add the properties of that induvidual song
				 music.name = music.name;
				 music.timesPlayed = music.timesPlayed;						 
			  }
			 else if (music instanceof ClassicalPiece){
				 // ... Same comment
			 }
			 else if  (music instanceof Musical){
				// ... Same comment.
			 }

			  musicArray[count] = music;
			  count++;
		}


Was This Post Helpful? 0
  • +
  • -

#3 nobodycool  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 14
  • Joined: 24-November 09

Re: Creating an array of objects

Posted 24 November 2009 - 07:23 PM

I would like to start by thanking you for the help! I corrected my silly initialization error and I had some success in beginning to populate the object array. My problem now is that it is actually not differentiating the instanceof's when it populates. It is just going down the line and grabbing each one in the .dat file that I am reading. In fact, when it comes to the 11th record, which I know is a instanceof RockSong record it throws a null pointer exception. I have a feeling it is because I am not grabbing that String to put into the object array. The thing is I am having troubling finding the syntax to put that object into the musicArray. Here is what I revised after your first help.


 private void DisplayFile()
	   {
	   int count =0;
	  Music[] musicArray= new Music[300];

	 ObjectInputStream inFile = null;
	 try
	 { inFile = new ObjectInputStream (new FileInputStream("music.dat"));
	 listenFile = new TextFileReader("listen.txt");}
	 catch (IOException ioex) { System.out.println ("ERROR Opening"); System.exit(1); }

	 try
	 {
		 while (true)
		 {
			 Music music = (Music)inFile.readObject();


			 if (music instanceof RockSong){

					  musicArray[count].name = music.name;
					  musicArray[count].timesPlayed = music.timesPlayed;
					   musicArray[count].lastTime = music.lastTime;

					  }

			 else if (music instanceof ClassicalPiece){
		   
				 
			 }
			 else if (music instanceof Musical){
				closeDate = (((Musical)music).close);
				  if (closeDate == null) {
				   ((Musical)music).close=Calendar.getInstance();
				  }
				 
			 }

			 musicArray[count] = music;

		  //just used this to test the output
			  System.out.println(count+"  "+musicArray[count].name);

			  count++;

		   }
	 }
	 catch (EOFException eofex) { System.out.println ("\nDONE");}
	 catch (IOException ioex) { System.out.println ("ERROR Reading"); System.exit(1); }
	 catch (ClassNotFoundException cnfex) { System.out.println ("ERROR class"); System.exit(1); }

   }



Was This Post Helpful? 0
  • +
  • -

#4 Dogstopper  Icon User is offline

  • The Ninjaducky
  • member icon



Reputation: 2857
  • View blog
  • Posts: 10,961
  • Joined: 15-July 08

Re: Creating an array of objects

Posted 24 November 2009 - 07:35 PM

You may wish to check the integrity of your .dat file to make sure that all your objects are correct for the nullPointerException.

Maybe the cast is messing it up in some way...
Music music = (Music)inFile.readObject();



However, Can you tell us, what exactly is in the .dat file, and how did you save them?
Was This Post Helpful? 0
  • +
  • -

#5 nobodycool  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 14
  • Joined: 24-November 09

Re: Creating an array of objects

Posted 24 November 2009 - 07:46 PM

View PostDogstopper, on 24 Nov, 2009 - 06:35 PM, said:

You may wish to check the integrity of your .dat file to make sure that all your objects are correct for the nullPointerException.

Maybe the cast is messing it up in some way...
Music music = (Music)inFile.readObject();



However, Can you tell us, what exactly is in the .dat file, and how did you save them?



Indeed. The music.dat file contains a binary file of Music objects written by an ObjectOutputStream object. I can read the file with ease by simply calling the objects to a regular array but I need to have them in an object array so that I can manipulate them as per the instructions of a listen.txt file that I read later on. If it would help I can include the .dat file for you to read from with my code.

The problem I am having is being able to put the RockSong group object into the musicArray within the instanceOf block. I tried to throw up some getters and setters within the RockSong class but then I get a caught IOException in the main method. The syntax is eluding me to grab the objects from the extensions of the Music class in order to put them into the musicArray.

This post has been edited by nobodycool: 24 November 2009 - 07:47 PM

Was This Post Helpful? 0
  • +
  • -

#6 Dogstopper  Icon User is offline

  • The Ninjaducky
  • member icon



Reputation: 2857
  • View blog
  • Posts: 10,961
  • Joined: 15-July 08

Re: Creating an array of objects

Posted 24 November 2009 - 08:14 PM

Oh your code is wrong here:
					  musicArray[count].name = music.name;
					  musicArray[count].timesPlayed = music.timesPlayed;
					   musicArray[count].lastTime = music.lastTime;



As of yet, musicArray at that specific count has not been instantiated yet. There is a spot for a Music object to be but there has not been one instanciated yet. The first way to do this would be:
 while (true)
		 {
			 Music music = (Music)inFile.readObject();


			 if (music instanceof RockSong){
					  musicArray[count] = new RockSong();
					  musicArray[count].name = music.name;
					  musicArray[count].timesPlayed = music.timesPlayed;
					  musicArray[count].lastTime = music.lastTime;

			}
			 else if (music instanceof ClassicalPiece){
						   
			 }
			 else if (music instanceof Musical){
				...   
			 }

		  //just used this to test the output
			  System.out.println(count+"  "+musicArray[count].name);

			  count++;

		   }



BUT since music already holds all the information anyway, why not just do this:
musicArray[count] = music;



No need to set any values because the loaded variable music holds them all.
Was This Post Helpful? 0
  • +
  • -

#7 nobodycool  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 14
  • Joined: 24-November 09

Re: Creating an array of objects

Posted 24 November 2009 - 08:52 PM

That worked great and I actually understand why it works that way! I really appreciate that. So all you really have to do is use the musicArray[count} = music statement to populate the array and from there you can access the individual elements in that array. Very handy

One thing I still don't understand is, how do I get the objects from the extended Music classes to the musicArray? This is to say that, I want to put the group name in the music array when it applies to a RockSong object and I want to put the composer in the music array when it applies to a ClassicalPiece object, as per my classes at the top of this post. Is there a special call to populate them into the array or is it because I have not initialized a RockSong object within the main method?
Was This Post Helpful? 0
  • +
  • -

#8 Dogstopper  Icon User is offline

  • The Ninjaducky
  • member icon



Reputation: 2857
  • View blog
  • Posts: 10,961
  • Joined: 15-July 08

Re: Creating an array of objects

Posted 24 November 2009 - 09:18 PM

If we think about it, what exactly does this line do?
Music music = (Music)inFile.readObject();



Does it make it always a Music object, and never a RockObject for instance...I mean...I don't know, but I am posing the question. If not then maybe try looking at this sort of thing instead.
if (music instanceof RockSong){
					  musicArray[count] = new RockSong();
					  RockSong rs = (RockSong) music // So we can use music.group
					  musicArray[count].name = music.name;
					  musicArray[count].timesPlayed = music.timesPlayed;
					  musicArray[count].lastTime = music.lastTime;
					  musicArray[count].group = rs.group;
			}
			 else if (music instanceof ClassicalPiece){
						   
			 }


Was This Post Helpful? 0
  • +
  • -

#9 nobodycool  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 14
  • Joined: 24-November 09

Re: Creating an array of objects

Posted 24 November 2009 - 09:34 PM

Well...I am under the impression that it always creates a Music object but the objects are also extensions of the three other classes that extend from the music class. This could be completely wrong in how it really is but that is how I have it in my head. Is it that, when you use inheritance the extended class is a separate object or just a piece of the main object?

I have tried to implement the changes you suggested but it does not like this line.
musicArray[count].group = rs.group;




It will not take the musicArray[count].group command. Is this because the group variable is not an instance of the Music class but rather an instance of the Music extends RockSong class?
Was This Post Helpful? 0
  • +
  • -

#10 nobodycool  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 14
  • Joined: 24-November 09

Re: Creating an array of objects

Posted 24 November 2009 - 09:50 PM

I am actually beginning to think I may not need to populate these elements into the array. I may be able to add them later as they never change. Hmmmm. I would still like to know how I might be able to do it.

This post has been edited by nobodycool: 24 November 2009 - 09:53 PM

Was This Post Helpful? 0
  • +
  • -

#11 Dogstopper  Icon User is offline

  • The Ninjaducky
  • member icon



Reputation: 2857
  • View blog
  • Posts: 10,961
  • Joined: 15-July 08

Re: Creating an array of objects

Posted 24 November 2009 - 09:55 PM

View Postnobodycool, on 24 Nov, 2009 - 10:34 PM, said:

It will not take the musicArray[count].group command. Is this because the group variable is not an instance of the Music class but rather an instance of the Music extends RockSong class?


Yah unfortunately, it's from the fact that musicArray is of type Music and only accepts methods/variables in the highest level class (in this case, Music). Can you post you current code up to this point, and see if maybe you can figure out as to how you are going to fix this.

Hint* It involves casting...
Was This Post Helpful? 0
  • +
  • -

#12 nobodycool  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 14
  • Joined: 24-November 09

Re: Creating an array of objects

Posted 24 November 2009 - 11:03 PM

Ok...so I have been reading up on casting and I think I understand what it is implying. Subclasses can only be accessed within the main class by upcasting or assigning the object to a reference variable type of the parent object. The thing is I can not find the correct syntax to make the upcasting work properly. This is what I have thus far of that small portion we have been working on. I am not using the correct syntax when trying to get the RockSong subclass variable.

 while (true)
		 {
			 Music music = (Music)inFile.readObject();

			 if (music instanceof RockSong){
				 RockSong rockSong = new RockSong();
				 Music rockMusic = rockSong;
				  musicArray[count] = music;			   
				  musicArray[count]  = ((Music)rockMusic).getGroup();
					  }
			 else if (music instanceof ClassicalPiece){
				musicArray[count] = music;
			 }
			 else if (music instanceof Musical){
				closeDate = (((Musical)music).close);
				  if (closeDate == null) {
				   ((Musical)music).close=Calendar.getInstance();
				  }
				 musicArray[count] = music;
			 }
			 musicArray[count] = music



This populates the Parent objects in the Music class perfectly but as I said I need to also grab the objects from the subclasses and put those in the array for display purposes and comparison purposes.
Was This Post Helpful? 0
  • +
  • -

#13 nobodycool  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 14
  • Joined: 24-November 09

Re: Creating an array of objects

Posted 25 November 2009 - 08:49 AM

SO I have been working on this for a while again today and I figured otu the issue I was having! I really appreciate all the help you gave me Dogstopper, it really helped me to, not just find the answer, but understand why. Now I am off to work on the next aspect of the program. :) If I need any further guidance I will be sure to pop in. Thanks again.

I also thought I would submit the code that finally worked for me just for reference.

 private void DisplayFile()
	   {
	   int count =0;


	 ObjectInputStream inFile = null;
	 try
	 { inFile = new ObjectInputStream (new FileInputStream("music.dat"));
	 listenFile = new TextFileReader("listen.txt");}
	 catch (IOException ioex) { System.out.println ("ERROR Opening"); System.exit(1); }

	 try
	 {

		 while (true)
		 {


			 Music music = (Music)inFile.readObject();
			
			 
			 if (music instanceof RockSong){
			   
				  musicArray[count] = music;
				 System.out.println(count+" "+musicArray[count].name+" "+musicArray[count].timesPlayed+" "+musicArray[count].lastTime.getTime()+" "+((RockSong)musicArray[count]).group);


					  }
			  if (music instanceof ClassicalPiece){

				musicArray[count] = music;
				System.out.println(count+" "+musicArray[count].name+" "+musicArray[count].timesPlayed+" "+musicArray[count].lastTime.getTime()+" "+((ClassicalPiece)musicArray[count]).composer+" "+((ClassicalPiece)musicArray[count]).type);

			 }
			  if (music instanceof Musical){
				closeDate = (((Musical)music).close);
				  if (closeDate == null) {
				   ((Musical)music).close=Calendar.getInstance();
				}

				 musicArray[count] = music;
				 System.out.println(count+" "+musicArray[count].name+" "+musicArray[count].timesPlayed+" "+musicArray[count].lastTime.getTime()+" "+((Musical)musicArray[count]).open.getTime()+((Musical)musicArray[count]).close.getTime());			  
			 }

			  count++;	  

	 }
	 } catch (EOFException eofex) { System.out.println ("\nDONE");}
	 catch (IOException ioex) { System.out.println ("ERROR Reading"); System.exit(1); }
	 catch (ClassNotFoundException cnfex) { System.out.println ("ERROR class"); System.exit(1); }



This post has been edited by nobodycool: 25 November 2009 - 08:50 AM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1