Iterator Question

Hello,
I have a question about iterators.
I have a list that is extracted from a file of names. it is then traversed using iterators, but the problem is the file has spaces in between the first and last name, and in some cases inside the last names themselves.
using println for display means i get the first and last name on 2 different lines. using print means i get all the names on one line.
is there a way to break it up so i can get the names on one line each?
thanks

By default the scanner uses white space to seperate tokens.
You need to modify the scanner so that it reads one token per line.
Something like
scanner.useDelimiter("\\n");
or maybe
String lineSeperator = System.getProperty("line.seperator");
scanner.useDelimiter(lineSeperator );
would probably do it.
Sorry, I don't have java 1.5 installed on my machine so I can't test it, but I hope you get the idea.

Similar Messages

  • Help with a simple iterator question

    the question is how to reset an iterator so it points to the beginng of a collection. Here is a piece of code. Thanks in advance:
    import java.io.*;
    import java.util.*;
    public class IteratorTest {
    public static void main(String[] args) {
    List list = new ArrayList();
    for (int i=0; i<10; i++) {
    list.add(new Integer(i));
    Iterator it = list.iterator();
    while (it.hasNext()) {
    System.out.println(it.next());
    // want to reset iterator here without
    // it = list.iterator();
    while (it.hasNext()) {
    System.out.println(it.next());

    Instead of using an Iterator, use a ListIterator.
    ListIterator it = list.listIterator();
    // walk forwards
    while (it.hasNext()) {
      it.next();
    // walk backwards
    while (it.hasPrevious()) {
      it.previous();
    // walk forwards again
    while (it.hasNext()) {
      it.next();
    }

  • Foreach loop iteration question

    Here's what I want to do. I have a list of items that I need to insert a comma between. For the last item there should be no comma afterward, so I need to flag this loop iteration as special.
    <c:set var="numRsns" value="${fn.length(networksForm.regionalSportsNetworkStations)}"/>
    <c:forEach var="rsn" items="${networksForm.regionalSportsNetworkStations}" varStatus="rsncounter">
         <c:if test="??? < numRsns" >
                               <b><c:out value="${rsn.description}" escapeXml="false" /></b>
                     </c:if>
         <b><c:out value="${rsn.description}," escapeXml="false" /></b>
    </c:forEach>How can I find out what the current iteration of the loop is? I am fairly new to JSP and JSTL so all help is appreciated.
    Thanks!

    Another useful feature of the loop status variable - it has boolean properties "first" and "last" to indicate if it is the first or last row
    <b>
    <c:forEach var="rsn" items="${networksForm.regionalSportsNetworkStations}" varStatus="rsncounter">
      <c:out value="${rsn.description}" escapeXml="false" />
      <c:if test="${rsncounter.last}>,</c:if>
    </c:forEach>
    </b>{code}
    Also because everything in your loop is bolded, why not just put bold tags around the whole thing, rather than mark up each individual element?                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Why iterator

    Why do I need an Iterator (vector.iterator() or arraylist.iterator()) to iterate a collection object though I have all required methods to access the collection object.

    aksarben wrote:
    My point was that you can use for loops without iterators.Okay. I was more aiming at the OP and other newbies who might be reading. There used to be a lot of "for loop vs. iterator" questions here, as if it were either/or, when the real either or is get() vs. iterator. I assume the confusion came from the fact the one of the standard idioms for using an iterator used a while loop, while get() typically used a for loop.
    The following are all equivalent:
    // "old" idiom that newbies were most familiar with
    List list = ...;
    Iterator it = list.iterator();
    while (it.hasNext()) {
      X x = (X)it.next();
      // do stuff
    // "old" idiom that most experienced developers I've worked with used
    List list = ...;
    for (Iterator it = list.iterator(); it.hasNext();) {
      X x = (X)it.next();
      // do stuff
    // "new" idiom which is just syntactic sugar for the above
    List<X> list = ...;
    for (X x : list) {
      // do stuff
    }And the wrong ways to iterate, which are equivalent to each other, but not equivalent to the above are:
    List<X> list = ...;
    // wrong idiom which newbies are familiar with
    for (int i = 0; i < list.length(); i++) {
      X x = list.get(i);
      // do stuff
    // wrong idiom which is equivalent to the above, but not common
    int i = 0;
    while (i < list.length()) {
      X x = list.get(i);
      // do stuff
    }

  • Lose MouseEvent after creating new class. Why?

    I have a main class that generates three clickable textfields (lessons).  Clicking a specific lesson starts the appropriate lesson.  However, once the lesson starts, I am unable to detect any mouseevents.  I do not use any mouseevents in any of the lessons so I am baffled about what happened to my mouse eventlisteners.  Even though I can see the nextLesson button, nothing happens when clicked.  If I click it before starting my lesson, my trace indicates that I have clicked it.  Any ideas?  Do I need my lessons to somehow self-terminate when done and if so, how would I go about this.  I currently use the browsers back arrow to terminate the complete session.  Seems kludgey.

    Site: itonlytakes1.org
    Currently I only have one lesson published: Discover the first ten number labels.  A minor annoyance is after you click on the lesson text, you have to click on the window again BEFORE the lesson will detect a numeric keypress (don't understand this either).  After executing the forty experiments (around two minutes), a summary of the time it took to recognize (subitize) the dashes and the quantity of errors will display.  I have been unable to create buttons or execute any code that will let you exit this screen and return to the main program screen, hence the advice to use the browser's back arrow.  SO, I decided to create a higher level script that contains all the lessons instead of using HTML, but I have not published it because I can't get the mouseevent to occur after starting Labeling.  I'll attach my prototype main program, Discovery, and the first lesson, Labeling (which is currently executed when you click on "Discover the first ten number labels".)  Be kind as I only started using AS3 and O.O.P. in January.  Thirty years ago I programmed in Fortran IV, and I haven't even written a shell script for 15 years.
    *********** don't know why .as files aren't attachable **********
    *********Discovery.as********************************
    package subquan{
        import flash.display.Sprite;
        import flash.text.*;
        //import flash.ui.Keyboard;
        import flash.events.*;
        //import flash.utils.setInterval;
        //import flash.utils.clearInterval;
        //import flash.utils.getTimer;
        public class Discovery extends Sprite {
            var lesson:*;
            public function Discovery() {
                var labeling:TextField = new TextField;
                labeling.text = "Discover number labels";
                labeling.x = 20;
                labeling.y = 50;
                addChild(labeling);
                labeling.addEventListener(MouseEvent.CLICK, runLabeling);
                var container:TextField = new TextField;
                container.text = "Discover number labels";
                container.x = 20;
                container.y = 100;
                addChild(container);
                container.addEventListener(MouseEvent.CLICK, runContainer);
                var dimension:TextField = new TextField;
                dimension.text = "Discover number labels";
                dimension.x = 20;
                dimension.y = 150;
                addChild(dimension);
                dimension.addEventListener(MouseEvent.CLICK, runDimension);
                private function runLabeling(evt:MouseEvent):void {
                lesson = new Labeling();
                addChild(lesson);
                private function runContainer(evt:MouseEvent):void {
                trace("Containers clicked");
                private function runDimension(evt:MouseEvent):void {
                trace("Dimension clicked");
    ********************  Labeling.as ***************************************
    package subquan{
        import flash.display.Sprite;
        import flash.display.Shape;
        import flash.text.*;
        import flash.ui.Keyboard;
        import flash.events.*;
        import flash.utils.setInterval;
        import flash.utils.clearInterval;
        import flash.utils.getTimer;
        public class Labeling extends Sprite {
            public static  const UP:Boolean=true;
            public static  const DOWN:Boolean=false;
            public static  const OFF:Boolean=false;
            public static  const ON:Boolean=true;
            public var number:*;// Main Container for all
            public var questions:*;// Remaining questions container
            public var rightEdge:uint;// Set in .fla file through window->property and select top pointer in side menu.
            public var lowerEdge:uint;
            // Decimal point locates number on the stage. (Not always visible)
            public var decimalPointX:uint;
            public var decimalPointY:uint;
            public var dim:String;
            public var base:uint;// Maximum pairs (base, number) = (2, 127), (3, 2186), (4, 16383), ..., Math.pow(base, 7) - 1
            public var num:int;// Maximum number is seven(7) digits regardless of base.
            public var scale:uint;
            // Variables for smooth scaling
            public var smoothStep:Number;// Change in scale for each step
            public var normalization:Number;// Current level of normalization.  Usually at 0, stop, or 1
            private var normalizationStop:Number;// Intermediate stop between full and normalized.
            private var smoothIntervalID:int;// Used to clear smoothing interval
            private var atAStop:Boolean=true;// smooth scaling is completed
            // Shared text field shows message whether subquan is to scale or not.
            private var answered:Boolean=false;// Indicates whether correct answer received
            private var answerSoFar:String;
            private var answerSign:Boolean;
            private var subquanAnswer:String;
            private var subquanAnswerSign:Boolean;
            private var waitAfterAnswer:uint;
            private var grade:Boolean;
            private var range:uint;
            private var hintID:int;
            private var sleepID:int;
            private var sounds:*;// Instance name for DigiSounds
            // Normalization text
            private var ToScale:String = "Subquan to scale";
            private var NotToScale:String = "Subquan NOT to scale";
            private var Normalized:String="Subquan normalized";
            private var lesson:*;// LessonText object
            private var answerArray:Array;
            private var samples:uint;// Number of samples of each digit
            private var numberTimes:Array=new Array();//Array keeping tracking of times per digit
            private var checkTime:Number;//Used for computed the time to answer
            private var errors:Array=new Array();//Tracks the number of errors.  Used to compute average time to answer
            private var newLesson:Boolean;//Tracks the start of a new lesson
            private var iterations:uint;//Total number of answers required = base * samples
            public function Labeling() {
                newLesson = true;
                base = 10;
                samples = 4;
                iterations = base * samples;
                for (var i:uint=0; i<base; i++) {
                    numberTimes[i] = 0;
                    errors[i] = 0;
                var numbers:*=new Numbers();
                answerArray = numbers.getNumbers(samples, base);
                rightEdge=550;// Set in .fla file through window->property and select top pointer in side menu.
                lowerEdge=400;
                decimalPointX=rightEdge - 100;
                decimalPointY=lowerEdge - 50;
                range=1;// Power of 10.  Do not exceed 7!
                waitAfterAnswer = 3000;
                smoothStep = 1/24;// Change in scale for each step
                sounds=new DigiSounds  ;// Initialize array of number words and notes
                lesson = new LessonText(lowerEdge, rightEdge);// Initialize feedback texts
                addChild(lesson);
                lesson.intro.text = "DISCOVERY 1:\n\nYou can recognize, in less than one second, any\nlabel (or symbolic name) of the first ten digits\n\nDo not count\nEnter 0, 1, 2, 3, 4, 5, 6, 7, 8, or 9\nas fast as you can\n\nEnter any number to begin.";
                lesson.remainingLabel.text = "Remaining experiments";
                addEventListener(KeyboardEvent.KEY_DOWN,keyDownFunc);
            private function newNumber():void {
                if (number) {
                    stage.removeChild(number);
                if (answerArray.length>0) {
                    num = answerArray.pop();
                    setNormalization(1);
                    // TEMPLATE: Quantity(num:Number, newBase:Number, normalization:Number=1, scale:Number=1, dim:String="null")
                    number=new Quantity(num,base,normalization,1, "null", OFF);
                    stage.addChild(number);
                    checkTime=getTimer();// Set time when number was displayed
                    number.x=decimalPointX;
                    number.y=decimalPointY;
                    subquanAnswer=String(number.getSubquanNumber());
                    subquanAnswerSign=number.getSubquanSign();
                    sounds.playNumber(subquanAnswerSign,number.getSubquanNumber());
                    lesson.answer.text="";
                    answerSoFar="";
                    answerSign=true;
                    lesson.grade.text="";
                    grade=false;
                    lesson.hint.text="";
                    clearInterval(hintID);
                    hintID=setInterval(giveHint,5000);
                    answered=false;
                } else {
                    lesson.grade.text="";
                    lesson.answer.text = "";
                    lesson.scaleText.text = "";
                    lesson.remainingLabel.text = "";
                    var doneText:String="";
                    var avgTimes:Number=0;
                    var totalErrors:uint=0;
                    for (var i:uint=0; i<base; i++) {
                        doneText = doneText + "\nfor " + i + " was " + Math.floor(numberTimes[i]/samples) + " with " + errors[i] + " errors";
                        avgTimes += numberTimes[i];
                        totalErrors+= errors[i];
                    var average:Number = Math.floor(avgTimes/base/samples);
                    var penalty:Number = Math.floor(totalErrors*Math.min(average, 2000)/base/samples);
                    var score:Number = average + penalty;
                    var comment:String = "";
                    doneText = doneText + "\nFor all including penalty was " + score + " msecs";
                    doneText = doneText + "\nTotal errors " + totalErrors + ", penalty: " + penalty + " msecs";
                    if (totalErrors == 0 && score < 1000) {
                        comment = "Excellent";
                    } else {
                        if (totalErrors/base/samples <= 0.05 && score < 1000) {
                            comment = "Well Done";
                        } else {
                            comment = "Practice reduces time and errors";
                    lesson.intro.text = comment + "\n\nAverage Times (in 1/1000th of a second)" + doneText;
            private function randomDim():String {
                var dimArray:Array=new Array;
                dimArray=["null","x","y","z"];
                return dimArray[Math.floor(Math.random() * 4)];
            private function wakeUp():void {
                clearInterval(sleepID);
                newNumber();
            private function giveHint():void {
                lesson.hint.text="Try " + subquanAnswer;
            public function setNormalization(n:Number):void {
                normalization = n;
                normalizationStop = n;
                atAStop=true;
                switch (n) {
                    case 0 :
                        lesson.scaleText.text=ToScale;
                        break;
                    case 1 :
                        lesson.scaleText.text=Normalized;
                        break;
                    default :
                        lesson.scaleText.text=NotToScale;
            public function smoothScale(target:Number):void {
                if (normalization > target) {
                    if (normalization - smoothStep <= target) {// At target, stop scaling
                        normalization=target;
                        atAStop=true;
                        clearInterval(smoothIntervalID);
                    } else {
                        normalization-= smoothStep;
                } else {
                    if (normalization + smoothStep >= target) {
                        normalization=target;
                        atAStop=true;
                        clearInterval(smoothIntervalID);
                    } else {
                        normalization+= smoothStep;
                number.scaleDigits(normalization);
            // IMPORTANT: Don't forget to press Ctrl + Enter to run n code and then on that preview screen,
            //      go to the menu and select Control then Disable Keyboard Shortcuts.
            private function keyDownFunc(event:KeyboardEvent):void {
                var key:uint=event.keyCode;
                var mathKey:String=null;
                switch (key) {
                    case 8 ://backspace key
                    case 46 ://delete key
                        trace("I am here");
                        //code to exit goes here
                        break;
                    case 13 :// Enter/retrun key.  Clear entry to start over.  SEE IMPORTANT NOTE
                        answerSoFar="";
                        answerSign=true;
                        lesson.clearAnswer;
                        lesson.clearGrade;
                        break;
                    case 37 :// Left arrow - change normalization stop
                        if (normalization - smoothStep <= 0) {// Set normalizationStop to fullscale
                            setNormalization(0);
                        } else {
                            setNormalization(normalization - smoothStep);
                        number.scaleDigits(normalizationStop);
                        break;
                    case 38 :// Up arrow
                        if (normalization == 1) {
                            atAStop=false;
                            lesson.scaleText.text=NotToScale;
                            clearInterval(smoothIntervalID);
                            smoothIntervalID=setInterval(smoothScale,10,normalizationStop);
                        if (normalization == normalizationStop) {
                            atAStop=false;
                            lesson.scaleText.text=ToScale;
                            clearInterval(smoothIntervalID);
                            smoothIntervalID=setInterval(smoothScale,10,0);
                        break;
                    case 39 :// Right arrow - change normalization stop
                        if (normalization + smoothStep >= 1) {// Set normalizationStop to normalized
                            setNormalization(1);
                        } else {
                            setNormalization(normalization + smoothStep);
                        number.scaleDigits(normalizationStop);
                        break;
                    case 40 :// Down arrow
                        if (normalization == 0) {
                            atAStop=false;
                            lesson.scaleText.text=NotToScale;
                            clearInterval(smoothIntervalID);
                            smoothIntervalID=setInterval(smoothScale,10,normalizationStop);
                        if (normalization == normalizationStop) {
                            atAStop=false;
                            clearInterval(smoothIntervalID);
                            smoothIntervalID=setInterval(smoothScale,10,1);
                            lesson.scaleText.text=Normalized;
                        break;
                    case 109 :// '-' on keypad pressed
                    case 189 :// '-' key pressed
                        if (! answerSign ) {
                            answerSoFar="";
                            answerSign=true;
                            lesson.answer.text="";
                        } else {
                            answerSoFar="-";
                            answerSign=false;
                            lesson.answer.text=answerSoFar;
                        lesson.clearGrade();
                        break;
                    default :
                        if (48 <= key && key < 58) {
                            mathKey=String(key - 48);
                        if (96 <= key && key < 106) {
                            mathKey=String(key - 96);
                        if (mathKey) {
                            if (newLesson) {
                                newLesson = false;
                                lesson.intro.text="";
                                newNumber();
                            } else {
                                if (! answered) {
                                    if (answerSoFar.length < subquanAnswer.length) {// Don't already have correct or incorrect answer
                                        answerSoFar+= mathKey;
                                        lesson.answer.text=answerSoFar;
                                    } else {// Have answer but want to change numbers
                                        answerSign=true;
                                        answerSoFar=mathKey;
                                        lesson.answer.text=answerSoFar;
                                        lesson.grade.text="";
                                    if (answerSoFar.length == subquanAnswer.length) {
                                        if (answerSoFar == subquanAnswer && answerSign == subquanAnswerSign) {// Correct Answer
                                            numberTimes[num]+= getTimer() - checkTime;
                                            lesson.hint.text="";
                                            sounds.playAnswer();
                                            answered=true;// Prevent accidental overwrite of sleepID from rapid key presses
                                            clearInterval(hintID);
                                            clearInterval(sleepID);
                                            sleepID=setInterval(wakeUp,2000);
                                            lesson.grade.text=" CORRECT";
                                            lesson.grade.setTextFormat(lesson.correctAnswerFormat);
                                            if (questions) {
                                                stage.removeChild(questions);
                                            // TEMPLATE: Quantity(num:Number, newBase:Number, normalization:Number=1, scale:Number=1, dim:String="null")
                                            iterations -= 1;
                                            if (iterations) {
                                                questions=new Quantity(iterations,10,1,0.25,"x");
                                                stage.addChild(questions);
                                                questions.x = rightEdge - 30;
                                                questions.y = 80;
                                        } else {
                                            errors[num] += 1;
                                            lesson.grade.text=" INCORRECT";
                                            lesson.grade.setTextFormat(lesson.incorrectAnswerFormat);
                                } else {
                                    trace("Lesson1.keyDownFunc: Unnecessary number key entered");
                        } else {
                            trace("Lesson1.keyDownFunc: Unused keycode " + key + " is " + String.fromCharCode(key));

  • Where to buy camera accessories.

    I'm looking for a follow focus, mattbox, SXS cards, etc. for our EX1. Where can I get the best deals on these items?

    Mobutu, this site has been advised many times to you, even in the recent past. If you can't recollect that, shame on you. You seem to have an obstinacy for re-iterating questions that either have been answered in various posts or stirring up topics that have been discussed previously. What are you looking for? An answer that may in three years time possibly be slightly relevant to you if you have the means and inclination to act upon it or do you just want a discussion?

  • Yet another Try Catch question. Iterating through a ForEach loop

    Confused on error handling in a Powershell ForEach loop. I’m looping through a list of registry keys, attempting
     to open each one. If it succeeds, I do a bunch of stuff. If it fails, I want to skip to the next iteration.
    If I was doing It in VBScript I’d do this:
    For Each Thing In colThings
    Open Thing
    If Err.Number <> 0 Then
    “oops”
    Else
    Do stuff
    Do stuff
    Do stuff
    End If
    Next
    This is what I came up with in PowerShell. It seems to work, but just doesn’t seem powershell-ish. There must be a better way to use the catch output than just creating a $return variable and assigning it success or fail?
    ForEach ($subKeyName in $subKeyNames)
    try{$subKey = $baseKey.OpenSubKey("$subKeyName")}
    catch{$return = "error" }
    If($return -eq "error" )
    “Oops”
    Else
    Do stuff
    Do stuff
    Do Stuff

     
    I totally get what you're saying about formatting. I don't' have any habits yet, since I've only been working in Powershell since... well, what time is it now?
    Unfortunately, It Has Been Decreed that we are no longer to use VBScript for any engineering solutions at work, so my 15 years experience in it now needs to be transitioned over asap. I don't have the luxury of crawling before I run. I'm trying not to be
    frustrated, but it's like an English major waking up one day and being told "You must now speak French exclusively. Here's a book."
    The Do Stuff example of my ForEach loop is about 50 lines of code involving matching values in subkeys of this registry key with another and collecting output. I tried wrapping the whole thing in a try section based on some examples, but it seemed odd, that's
    why I'm asking. I'm used to tightly focused error handling at the point where an error may occur.
    In this example I'm only interested in whether or not I can open the subkey (it exists, but I may not have permission). If I can't, there's no point in continuing with this iteration of the loop, I want to skip to the next one. So why include all the "Do
    Stuff" in the the try section? From a readability viewpoint, it doesn't seem helpful.
    Also, there may be more error handling deeper in the code. If I then put that in a try/catch, and then something else inside that, now I have nested try/catches mixed in with nested if/elses, all wrapped in a For loop.
    Again, I can see how it works logically, but for readability not so much, and having all these braces 50 lines apart to match up is giving me eye strain :).
    It sounds like David is agreeing with jrv, that putting the entire ForEach loop code into a try/catch is the conventional way to do it. I guess it makes as much sense as putting it all in an If-else-Endif, and I just need to adjust my paradigm.
    But if not, my specific question was more along the lines of, is there a built in way to tell that the catch section has been executed, rather than me using it to populate an arbitrary variable and then read it? In VBScript, you execute something, and the
    next line, you check the Err.number. I wasn't sure if you could do that with a try/catch.

  • Iterator Interface.A question please.

    I am unable to grasp the meaning of the following below :
    As we all know,Interfaces have abstract methods,(ie methods that
    have no body) and any class that implements the Interface has to
    implement the methods defined in the interface.That is,write the body for those methods.
    So far so good.
    Now coming to Collections called Vector.
    We have the 'Iterator' interface implemented by the vector class.
    The Iterator interface has the methods hasNext(),next().
    and we have the following code in the our class which iterates thru'
    the vector:
    MyClass item;
    while(iter.hasNext())
    item = (MyClass)iter.next();
    // Do something here.....
    Now we are using the methods hasNext() and next() above.
    But as they belong to the Iterator interface,(which means they
    are basically methods with no implementations) then how is iteration
    possible? We havent defined anything in the hasNext() method or the next()
    so how does Java automatically start iteration
    Has any one understood my question?Arent hasNext() and next() supposed
    to be methods with no body???
    If I am saying iter.hasNext(),that means hasNext() has been defined
    somewhere to iterate thru the vector?
    I am just confused regarding this issue as to how is hasNext() and next()
    being implemented as I as the programmer have not implemented them
    in my code
    Please can some one answer my question?
    Regards
    Ajay

    Thanks Will.
    Regarding the question,then why define an Iterator interface when
    the collection class implements the functionality?
    Why not define the methods hasNext() and next() in the Object
    class?
    So by default,all classes extends the Object class ,we
    cud use the hasNext() and next() method?
    No??? Or am I wrong?

  • Reconcile question: Error iterating accounts for resource:

    Guys,
    One question. While trying to reconsile my MS SQL database table it fails and I'm getting the next error message:
    Error iterating accounts for resource :
    java.lang.NullPointerException
    Any Idea what might cause this error. All other resources are reconsiling just fine...
    Thanks.
    Elger

    Unfortunately that didn't help. I deleted the whole account index just to make sure all 'links' where gone but I'm still getting the null pointer exception.
    Any more idea's?

  • Iterator Interface.A question please......respond

    I am unable to grasp the meaning of the following below :
    As we all know,Interfaces have abstract methods,(ie methods that
    have no body) and any class that implements the Interface has to
    implement the methods defined in the interface.That is,write the body for those methods.
    So far so good.
    Now coming to Collections called Vector.
    We have the 'Iterator' interface implemented by the vector class.
    The Iterator interface has the methods hasNext(),next().
    and we have the following code in the our class which iterates thru'
    the vector:
    MyClass item;
    while(iter.hasNext())
    item = (MyClass)iter.next();
    // Do something here.....
    Now we are using the methods hasNext() and next() above.
    But as they belong to the Iterator interface,(which means they
    are basically methods with no implementations) then how is iteration
    possible? We havent defined anything in the hasNext() method or the next()
    so how does Java automatically start iteration
    Has any one understood my question?Arent hasNext() and next() supposed
    to be methods with no body???
    If I am saying iter.hasNext(),that means hasNext() has been defined
    somewhere to iterate thru the vector?
    I am just confused regarding this issue as to how is hasNext() and next()
    being implemented as I as the programmer have not implemented them
    in my code
    Please can some one answer my question?
    Regards
    Ajay

    Thanks for yr reply.
    So you mean to say the the Iterator methods hasNext()
    and next()
    are being implemented by the Vector class.right?Not exactly. The Vector class defines an inner class, and it is this class that implements the Iterator interface, and so these two methods. When you write code like
    Vector myVector = new Vector();
    // code to fill myVector...
    Iterator it = myVector.iterator();the call to the iterator() method tells myVector to give you an instance of this inner class. The Vector class itself doesn't implement next() or hasNext().
    Then why define an interface with these methods at
    all?
    Why not give concrete bodies to these methods and put
    them in
    the Object Class.If you did that, then all classes would inherit them - all classes would be iterators. That wouldn't make sense, though, as clearly not all classes are meant to be used to iterate over collections of objects.
    Iterator is an interface so that a consistent API can be defined for iteration. As iterators are used in lots of different places, it is very helpful to have all of them guaranteed to have next() and hasNext() methods (amongst others). It is also very helpful to be able to call the iterator() method on any Collection class and know that the object that is returned, regardless of its implementation, will be of type Iterator.
    Then we can call them polymorphically.???But that's what you're doing - Vector and ArrayList (for example) have different implementations of Iterator, but code that iterates over them doesn't need to know that. As both return objects that implement the Iterator interface, they are interchangeable; that's polymorphism at work.

  • Iterator Interface. A question?

    I am unable to grasp the meaning of the following below :
    As we all know,Interfaces have abstract methods,(ie methods that
    have no body) and any class that implements the Interface has to
    implement the methods defined in the interface.That is,write the body for those methods.
    So far so good.
    Now coming to Collections called Vector.
    We have the 'Iterator' interface implemented by the vector class.
    The Iterator interface has the methods hasNext(),next().
    and we have the following code in the our class which iterates thru'
    the vector:
    MyClass item;
    while(iter.hasNext())
    item = (MyClass)iter.next();
    // Do something here.....
    We are using the methods hasNext() and next() above.
    But as they belong to the Iterator interface,(which means they
    are basically methods with no implementations) then how is iteration
    possible? We havent defined anything in the hasNext() method or the next()
    so how does Java automatically start iteration
    Has any one understood my question?Arent hasNext() and next() supposed
    to be methods with no body?.
    Arent they supposed to be empty()?
    If they have no body,then how are they being implemented?
    If I am saying iter.hasNext(),that means hasNext() has been defined
    somewhere to iterate thru the vector?
    I am just confused regarding this issue as to how is hasNext() and next()
    being implemented as I as the programmer have not implemented them
    in my code
    Please can some one answer my question?
    Regards
    Ajay

    public Iterator iterator()
    Returns an iterator over the elements in this list in proper sequence.
    This implementation returns a straightforward implementation of the iterator interface, relying on the backing list's size(), get(int), and remove(int) methods.
    Note that the iterator returned by this method will throw an UnsupportedOperationException in response to its remove method unless the list's remove(int) method is overridden.
    This implementation can be made to throw runtime exceptions in the face of concurrent modification, as described in the specification for the (protected) modCount field.
    Specified by:
    iterator in interface List
    Specified by:
    iterator in class AbstractCollection
    Returns:
    an iterator over the elements in this list in proper sequence.
    See Also:
    modCount
    So based on the above JavaDoc for java.util.AbstractList, which Vector sub-classes, the iterator() method returns an implementaion of the iterator interface. This is where the methods are defined.

  • Iterator Refresh Question

    Hello there,
    i have a case where i have a search screen that is based on a table , let's say employees, the results is an ADF Read Only table. I brought the department name from the deparments View object to the employees View object so i can see the name as well as the id in my Results. Now i have a button Create , when i create an employee and enter a department id and then press save , the page results to the search screen where the new record i created appears with the department id but without the department name.
    My primary thought was to set the refresh iterator property but i'm not being able to solve my problem.
    Anyone can help me ?

    In your backing bean, if you have access to the binding container, run something like the following:
    DCIteratorBinding iter = (DCIteratorBinding)bindings.get("MyIteratorName");
    iter.execute();You can gain access to the binding container by doing the following:
    1. Define an instance-level field in the backing bean:
    private BindingContainer bindings;2. Add a getter and setter for the field:
        public BindingContainer getBindings() {
            return bindings;
        public void setBindings(BindingContainer bindings) {
            this.bindings = bindings;
        }3. Add a managed-property to the definition of your backing bean in faces-config.xml:
      <managed-bean>
        <managed-bean-name>myBackingBean</managed-bean-name>
        <managed-bean-class>com.acme.backing.MyBackingBean</managed-bean-class>
        <managed-bean-scope>request</managed-bean-scope>
        <managed-property>
          <property-name>bindings</property-name>
          <value>#{bindings}</value>
        </managed-property>
      </managed-bean>If you don't want to add a managed property to the bean, you can locate the BindingContainer like this:
    FacesContext ctx = FacesContext.getCurrentInstance();
    Application app = ctx.getApplication();
    ValueBinding bind = app.createValueBinding("#{bindings}");
    BindingContainer bindings = (BindingContainer)bind.getValue(ctx);

  • Reposting: Question regarding iteration over synchronized list

    [added proper markup]
    I've got an A-Life program I work on for fun. I thought I understood (sorta) synchronized collections, but this puzzles me. The method body is as follows:
         * Create new animals from existing animals
         * @return The cohort of newborn animals
        public List<IAnimal> regenerate() {
            List<IAnimal> children = new ArrayList<IAnimal>();
            synchronized (animalList) {
                Iterator<IAnimal> it = animalList.iterator();          // must be in synchro block according to JDK notes
                 while (it.hasNext()) {
                     IAnimal a = it.next();
                     if (a.isPregnant() && ((GeneModel.getInstance().getTicks() % getEnvironment().getAnimal().getReproCycle()) == 0)) {
                         IAnimal child = a.reproduce();
                         children.add(child);                    // newborns
    //                     animalList.add(child);                    // the whole population  //THROWS CME!
                 animalList.addAll(children);                                     // does not throw CME
            return children;
        }Animal list is a synchronized list (backed by and ArrayList). Note that I've synchronized on the list, yet adding children individually throws a ConcurrentModificationException (I did overwrite the add() method on the backing list, but I wouldn't think that would be a problem; it might be in that it iterates over itself... but synchronizing that doesn't help, either).
    Anyhow, doing an addAll outside of the synchronization block works fine (also works if I loop through the children and add them at this point).
    Is it my override of the add() method? From what I can see, the synchronized wrapper just adds a mutex to each access method in the backing list. Here's the method override:
          List<IAnimal> backingList =
                new LinkedList<IAnimal>() {
                     * Checks that we're not putting one animal on top of another. If we are, we generate a new animal and
                     * try again.
                     * @param   animal  The animal to be added
                     * @return  true
                    public boolean add(IAnimal animal) {
                        boolean added = false;
    outer:
                        do {
                            // synchronized (this) {                // DIDN'T HELP
                            Iterator<IAnimal> iAnimals = iterator();
                            while (iAnimals.hasNext()) {
                                //FIXME: this algorithm assumes square animals
                                Point existingAnimalLocation = iAnimals.next().getLocation();
                                double distance = existingAnimalLocation.distance(animal.getLocation());
                                if (distance < animal.getSize().getWidth()) {
                                    animal = new Animal();
                                    continue outer;
                            //}  //end unhelpful synchro block
                            super.add(animal);
                            added = true;
                        while (!added);
                        return added;
                    } // end method add
                };

    Jefferino wrote:
    spoon_ wrote:
    By the way that Iterators in Java are designed, you are not allowed to modify a list as you iterate over it.
    Not true: Iterator.remove().
    Edited by: Jefferino on Mar 20, 2008 2:24 AMOh yeah, you can modify it using the iterator's methods; but not using any of the collection's methods, like add().

  • Question regarding iteration over synchronized list

    I've got an A-Life program I work on for fun. I thought I understood (sorta) synchronized collections, but this puzzles me. The method body is as follows:
    * Create new animals from existing animals
    * @return The cohort of newborn animals
    public List<IAnimal> regenerate() {
    List<IAnimal> children = new ArrayList<IAnimal>();
    synchronized (animalList) {
    Iterator<IAnimal> it = animalList.iterator();          // must be in synchro block according to JDK notes
         while (it.hasNext()) {
         IAnimal a = it.next();
         if (a.isPregnant() && ((GeneModel.getInstance().getTicks() % getEnvironment().getAnimal().getReproCycle()) == 0)) {
         IAnimal child = a.reproduce();
         children.add(child);                    // newborns
    //     animalList.add(child);                    // the whole population //THROWS CME!
         animalList.addAll(children); // does not throw CME
    return children;
    Animal list is a synchronized list (backed by and ArrayList). Note that I've synchronized on the list, yet adding children individually throws a ConcurrentModificationException (I did overwrite the add() method on the backing list, but I wouldn't think that would be a problem; it might be in that it iterates over itself... but synchronizing that doesn't help, either).
    Anyhow, doing an addAll outside of the synchronization block works fine (also works if I loop through the children and add them at this point).
    Is it my override of the add() method? From what I can see, the synchronized wrapper just adds a mutex to each access method in the backing list. Here's the method override:
    List<IAnimal> backingList =
    new LinkedList<IAnimal>() {
    * Checks that we're not putting one animal on top of another. If we are, we generate a new animal and
    * try again.
    * @param animal The animal to be added
    * @return true
    public boolean add(IAnimal animal) {
    boolean added = false;
    outer:
    do {
    // synchronized (this) {                // DIDN'T HELP
    Iterator<IAnimal> iAnimals = iterator();
    while (iAnimals.hasNext()) {
    //FIXME: this algorithm assumes square animals
    Point existingAnimalLocation = iAnimals.next().getLocation();
    double distance = existingAnimalLocation.distance(animal.getLocation());
    if (distance < animal.getSize().getWidth()) {
    animal = new Animal();
    continue outer;
    //} //end unhelpful synchro block
    super.add(animal);
    added = true;
    while (!added);
    return added;
    } // end method add
    };

    Your code is not formatted (use code tags for this) but it seems to me that you add elements to the list while you iterate over it, hence a ConcurrentModificationException is thrown. Use a ListIterator if you want to add to the list while iterating.

  • ADF question: re-executing the view iterator which returns different rows

    Hi,
    I am terribly stuck in building one of my demos for
    an ADF seminar.
    I happened to created a view object which queries with
    rows showing up random lists such that:
    select a, b, c
    from sometable
    order by mod(DBMS_RANDOM.Random,50)+50
    and the result shows up fine. I wanted to display
    only one row, so I set up fetch size max to 1.
    in this way, I would get a random selection whenever
    I executed query to this view object.
    I created a data page where the results would show up.
    ok, so far so good. But I happened to notice that
    the randomly selected row would not change once it is
    loaded (pressing reload button on my browser did not
    refreshed the random selection). I knew this behavior,
    that the view object would cache the query once it
    is executed and not updated.
    So, I put an action event to invoke the 'Execute' method
    to this view object iterator. The selection now seems
    to be working randomly, but I also got error messages
    that says:
    You must correct the following error(s) before proceeding:
    JBO-29000: Unexpected exception caught: oracle.jbo.JboException, msg=JBO-33035: Row currency has changed since the user interface was rendered. The expected row key was oracle.jbo.Key[2 ]
    JBO-33035: Row currency has changed since the user interface was rendered. The expected row key was oracle.jbo.Key[2 ]
    I suspect this was because the newly selected row has different Key(primary key) to that of previously selected row, but I want to override this.
    is there any way that I may clear up the selection cache
    to tell ADF that the newly selected row is the current
    key in the row?
    Any suggestions are gladly welcomed.
    Regards,
    Howard Yoo

    repost

Maybe you are looking for