• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

ArrayList with Iterator

 
Dave DiRito
Ranch Hand
Posts: 77
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This method should take a name that the user provides and insert it into a sorted ArrayList in the correct location. I have a syntax problem that I cannot solve. Here's the code:

Thanks,
Dave
 
Rob Spoor
Sheriff
Pie
Posts: 20512
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is no method called add that takes an Iterator object. It can only accept an integer for the index.
 
Dave DiRito
Ranch Hand
Posts: 77
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks, Rob. I was wondering about that.

So how can I tell where the iterator is at? How do I get the index at that particular point?
 
Dave DiRito
Ranch Hand
Posts: 77
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok, figured that part out, but now I have another, similar problem. I'm trying to get it to compare the name to be inserted to the word that's at the index of where the iterator is at that point in the loop.

Here's my method now with the compile error that I get:


AddName.java:36: cannot find symbol
symbol : method get(java.lang.String)
location: class java.util.ArrayList<java.lang.String>
}else if(name.compareToIgnoreCase(list.get(itr.next())) >= 0 ){
^
1 error
 
Dave DiRito
Ranch Hand
Posts: 77
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok, fixed that. Now it compiles, but does not insert the new word in the proper order, so I have a logic error now. Here's the code now:
 
Campbell Ritchie
Sheriff
Posts: 48652
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am surprised that runs at all; you usually get an Exception if you try to add or remove (other than using the Iterator#remove() method) while there is an Iterator in scope.
 
Dave DiRito
Ranch Hand
Posts: 77
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Don't know why it runs, Campbell. Anyway, because it didn't do what I wanted, I changed the code to the following. This compiles and inserts the word in the proper spot, except if the word comes after the last word in the list. This might work with a LinkedList, but not an ArrayList. Any suggestions?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic