aspose file tools*
The moose likes Beginning Java and the fly likes How to insert object reference into array where index = null? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "How to insert object reference into array where index = null?" Watch "How to insert object reference into array where index = null?" New topic
Author

How to insert object reference into array where index = null?

drew taylor
Greenhorn

Joined: Feb 20, 2006
Posts: 21
Hi,

Any help or suggestions will be very much appreciated

I'm trying to insert an object reference into an array where the next value in the array is null. So far I have the following code although I'm not sure if this is the correct way to do this:


// Takes a teacher object reference an inserts into array where
// next value is null.
public void insertTeacher(Teacher teacher) {

count = teacherList.length;

if (teacherList.length == 0) // Insert at index 0 if array is empty
teacherList[0] = teacher;
else
{

for (int i = 0; i < count; i++)
{
if (i < count)
insert where teacherList[i] = null ???



Am I going in the right direction with this? Can someone provide me with example code for 'insert where teacherList = null' ?
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39409
    
  28
What is teacherList? Is it a List or an array?
You seem to be treating it as a List not an array (although some Lists do contain arrays).
You know that arrays only have the methods from the Object class, and the length attribute. When you set up an array it contains 0s (if a primitive array) or nulls throughout.
When you set up a List it doesn't (officially) contain anything; it has all the methods in the List interface and you use size() to find how many elements it contains. You can only find a null if you have put a null in somewhere.

Read the Java Tutorial about arrays, ditto about the collections framework, particularly where it says "list implementations," the API description and ths methods for List and similarly for what is probably the most popular List implementation ArrayList.

You can go through the List using its size() method to find how many elements it has, then you could use your for loop to find whether any of the elements is null, and there is a method in List which can replace the null with your new object.

But if you haven't put nulls in your List there won't be any nulls detectable. You will simply have to use the usual method to get another member in. It's in List and it will tell you where it puts the new element.

Tell us what you work out.

CR
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: How to insert object reference into array where index = null?