3

In my code below:

List<Skill__c> skilist = [ select Id,Name from Skill__c where Skill__c.Id IN:sl.keySet()];
Iterator<Skill__c> iter = skilist.iterator();

 List<Job_Opening_Skill__c> Jos=new List<Job_Opening_Skill__c>();

for(Job_Opening_Skill_Set__c jobOpeningSkillSet:trigger.new){

    Job_Opening_Skill__c js=new Job_Opening_Skill__c();

    system.debug('skill list size-------------->>>>>>' + skilist.size());

    while(iter.hasNext()){
        system.debug('skill is----------------->>>>>>' + iter.next().Name );
        **js.Skill__c=iter.next().Id;**
        js.Job_Opening__c=jobOpeningSkillSet.Job_Opening__c;
        Jos.add(js);
    }


}

insert Jos;

The skilist List has only one value. I have only ONE element in it. above is a part of trigger which is invoked after update/insert. When I do an update/insert to the object on which I wrote this trigger I get an error -

System.NoSuchElementException: Iterator has no more elements.

I suspect that it is caused due to - js.Skill__c=iter.next().Id; line since it is moving to the next element but it has only one element( I may be wrong since hasnext() should return false and while loop has no way to reach next(). But I don't know how I can resolve this. Any help?

1 Answer 1

6

As you have mentioned you have only one element, that is why you are facing this problem.

you are using;


system.debug('skill is----------------->>>>>>' + iter.next().Name );
js.Skill__c=iter.next().Id;

And each time you call iter.next() it will take you to the next element.

So to avoid this you can use;


while(iter.hasNext()){
        Skill__c tempSkill = iter.next(); // Get the element and use it inside the loop
        system.debug('skill is----------------->>>>>>' + tempSkill.Name );
        js.Skill__c=tempSkill.Id;
        js.Job_Opening__c=jobOpeningSkillSet.Job_Opening__c;
        Jos.add(js);
    }

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .