• Post Reply Bookmark Topic Watch Topic
  • New Topic

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

Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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;

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' ?
Posts: 59461
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

They gave me pumpkin ice cream. It was not pumpkin pie ice cream. Wiping my tongue on this tiny ad:
Why should you try IntelliJ IDEA ?
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!