Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

ArrayList Problems  RSS feed

 
Joe Pettit
Ranch Hand
Posts: 33
C++ Chrome Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all - this is my first post here, so apologies if I'm not adhering to any particular standard! I've just completed a Java course at my local college and I'm trying to use what I've learned to create a basic academic organizer type program. I'm trying to use an ArrayList for one portion of the program but I keep getting an index out of bounds exception and I can't seem to figure out why. Here is the relevant code:







Basically what I'm trying to do here, is pass the object anAssignment from the addAssignment class to the configBuilder class (where the method makeAssignment is located) in the form of an arraylist. The makeAssignment method then adds this information to a file.

I think I put in everything that is relevant - let me know if I missed anything. Anyway - it seems that the last bit of code, the makeAssignment method is throwing the error. Again, any help would be much appreciated! Thank you!
 
Campbell Ritchie
Marshal
Posts: 55677
161
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

You only get an out of bounds exception from an array list when you attempt access to an element which doesn’t exist. If you go through the documentation, which will appear when you click the name of the class spelt correctly: ArrayList you see there are about 7 methods which might throw such an exception. You are adding at 0, which is all right, as long as you don’t mind your entire List being in reverse order and then you are using a traditional for loop for access to all those elements.
You ought not to use a for loop to iterate the whole of a List. You should use an iterator, preferably hidden behind a for‑each loop (called enhanced for).
If it is necessary to use a for loop to iterate something, you must be very careful to use the conventional form, which is certain not to cause problems with Exceptions. Count how many times your loop with the get(index) call will iterate if you have a 5‑element List.

Other points: Your lines are too long; break them in convenient places.
Your class naming is not right: all classes start with CapitalLetters and Assignment would be a better name for a class than AnAssignment.
Your fields should all have private access and should be publically accessible via getXXX() methods. If that is how you wish to display the contents of an Assignment object, give it a toString() method which returns such a String. You can probably simply write myAssignment.toString().
Why are you using a plain simple FileWriter rather than a BufferedWriter or a Formatter?
 
Joe Pettit
Ranch Hand
Posts: 33
C++ Chrome Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:Welcome to the Ranch

You only get an out of bounds exception from an array list when you attempt access to an element which doesn’t exist. If you go through the documentation, which will appear when you click the name of the class spelt correctly: ArrayList you see there are about 7 methods which might throw such an exception. You are adding at 0, which is all right, as long as you don’t mind your entire List being in reverse order and then you are using a traditional for loop for access to all those elements.
You ought not to use a for loop to iterate the whole of a List. You should use an iterator, preferably hidden behind a for‑each loop (called enhanced for).
If it is necessary to use a for loop to iterate something, you must be very careful to use the conventional form, which is certain not to cause problems with Exceptions. Count how many times your loop with the get(index) call will iterate if you have a 5‑element List.

Other points: Your lines are too long; break them in convenient places.
Your class naming is not right: all classes start with CapitalLetters and Assignment would be a better name for a class than AnAssignment.
Your fields should all have private access and should be publically accessible via getXXX() methods. If that is how you wish to display the contents of an Assignment object, give it a toString() method which returns such a String. You can probably simply write myAssignment.toString().
Why are you using a plain simple FileWriter rather than a BufferedWriter or a Formatter?


1. Will do - thanks!
2. Didn't realize there was a specific convention, I'll be sure to modify that to conform to standards - thanks!
3. Never thought of that - guess a simple string return would work fine, I'm always one to think of the most complicated solution first, hah! I'll give that a shot.
3. I don't know - to be honest, I don't know all that much about the different writing methods - I'll have to look into that.

And with regards to the original problem - you think the for loop is causing all of this? I've read about the enhanced for loop but I guess I kind of shrugged it off and assumed I wouldn't need it! I'll try modifying the method to use that and see if that fixes the problem.

Thanks for your help!!
 
Mike Simmons
Ranch Hand
Posts: 3090
14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Joe Pettit wrote:And with regards to the original problem - you think the for loop is causing all of this? I've read about the enhanced for loop but I guess I kind of shrugged it off and assumed I wouldn't need it! I'll try modifying the method to use that and see if that fixes the problem.

An enhanced for loop will fix the problem, but I think it's worthwhile to understand where the problem really came from, too. Note that your IndexOutOfBoundsException should have a stack trace associated with it, a list of classes, methods and line numbers in your program telling you where the program was when the problem occurred. It's worthwhile to learn how to read this. If you look carefully, I'm pretty sure one line near the top of the stack trace will point you to a line number inside the for loop - this will confirm that yes, it's that for loop that is generating the index which it's complaining about.

And look closely at the other questions Campbell asked you about the loop. Ask yourself: what is the lowest index the loop will generate? What is the lowest index an ArrayList can have? And what is the highest index the loop can generate? And what is the highest index the ArrayList can have?
 
Joe Pettit
Ranch Hand
Posts: 33
C++ Chrome Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Would you guys mind giving me an example of the enhanced for loop? I understand the syntax, but it seems like I need to do something to my arraylist class to make this work - is that right?
 
Campbell Ritchie
Marshal
Posts: 55677
161
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There should be an example in the Java Tutorials link I gave you. Or here, in the class called Shuffle. They might be for arrays rather than Lists, but the syntax is very similar.

And you have parameterised the List, so use the parameter and don’t mess about with class casts. Because you used <Assignment> your List can only contain Assignments.
 
Campbell Ritchie
Marshal
Posts: 55677
161
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, you do not have to do anything special to the List to get a for‑each loop to work.
 
Joe Pettit
Ranch Hand
Posts: 33
C++ Chrome Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:There should be an example in the Java Tutorials link I gave you. Or here, in the class called Shuffle. They might be for arrays rather than Lists, but the syntax is very similar.

And you have parameterised the List, so use the parameter and don’t mess about with class casts. Because you used <Assignment> your List can only contain Assignments.


I'm still a bit confused - sorry!

I understand that:



The arraylist name goes there, but what would go in the first part of the loop? I see typically it would be an int for an int array, or a String for a string array - what would it be for an object array?
 
Campbell Ritchie
Marshal
Posts: 55677
161
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is what it shows in the Java Tutorials link I showed you yesterday, with indentation altered to match what you are using:
for (int item : numbers)
{
    System.out.println("Count is: " + item);
}
There is a more formal description in the Java Language Specification, but that is by no means easy to read. Simply for (<type> <local identifier> : <collection or array name)…

And have you counted how many times your for loop would iterate a 5‑element list?>
 
Campbell Ritchie
Marshal
Posts: 55677
161
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You haven’t got an Object[]. You have a List of Assignments. You wrote specifically List<Assignment> or similar, so you can be confident that your List only contains Assignments. It is a local loop variable, so you can call it a in the loop.
 
R. Jain
Ranch Hand
Posts: 375
1
Java Python Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Joe Pettit wrote:Hi all - this is my first post here, so apologies if I'm not adhering to any particular standard! I've just completed a Java course at my local college and I'm trying to use what I've learned to create a basic academic organizer type program. I'm trying to use an ArrayList for one portion of the program but I keep getting an index out of bounds exception and I can't seem to figure out why. Here is the relevant code:





This is not the correct way to define an ArrayList... You should have parameterized type in both sides....
And also any List is a dynamically increasing list... so you don't need to give size as you give in case of traditional Array....

So, remove that (5) from above....

Joe Pettit wrote:




[removed]

And yes, what everyone is saying, you should use enhanced for loop, whenever you want to iterate over a List...
And for that, Campbell has already given a good example and syntax...
 
shaileshkumar mistry
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
inhanced loop in your case :----
 
Campbell Ritchie
Marshal
Posts: 55677
161
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Both of you, please go to the “Beginning Java” forum and read this:
We're all here to learn, so when responding to others, please focus on helping them discover their own solutions, instead of simply providing answers.
If Joe Pettit is to learn about that Exception, or about for‑each loops, he will have to work it out for himself. If somebody simply gives him an answer, he will learn nothing. Don’t be annoyed with me, but I have pulled rank and removed the straight answers from your posts.
 
R. Jain
Ranch Hand
Posts: 375
1
Java Python Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:Both of you, please go to the “Beginning Java” forum and read this:
We're all here to learn, so when responding to others, please focus on helping them discover their own solutions, instead of simply providing answers.
If Joe Pettit is to learn about that Exception, or about for‑each loops, he will have to work it out for himself. If somebody simply gives him an answer, he will learn nothing. Don’t be annoyed with me, but I have pulled rank and removed the straight answers from your posts.


Sorry for that Campbell.. Will remember it from now on...
 
Campbell Ritchie
Marshal
Posts: 55677
161
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
R. Jain wrote:
Joe Pettit wrote: . . .


This is not the correct way to define an ArrayList... You should have parameterized type in both sides....
And also any List is a dynamically increasing list... so you don't need to give size as you give in case of traditional Array....

So, remove that (5) from above.... . . .
No, that is the correct way to give the initialisation the same actual type parameter as the declaration. Look here under the section called “the diamond”. New feature in Java7.
There is actually a better way to declare that List:I agree the 5 is unnecessary, but it does no harm to specify a size for a List if you are sure that size is correct. If it is a large size, you ought to specify it. Populating this list:… will be much faster because you have specified a size.

It would be far better to give the Assignment class a proper toString() method and use a BufferedWriterI would probably have used a java.util.Formatter object myself.
 
Campbell Ritchie
Marshal
Posts: 55677
161
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Apologies accepted
 
R. Jain
Ranch Hand
Posts: 375
1
Java Python Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:
No, that is the correct way to give the initialisation the same actual type parameter as the declaration. Look here under the section called “the diamond”. New feature in Java7.
There is actually a better way to declare that List:


Oh... Didn't knew that he was using Java 7... Yes in Java 7 it will work for sure... What a nice feature it is....
 
Joe Pettit
Ranch Hand
Posts: 33
C++ Chrome Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I did end up getting the arraylist to work correctly, but through the process I determined that the arraylist wasn't the best thing to use for what I was trying to do. I ended up using a toString method in the assignmentWriter class and used this string to write to the file. Thanks for the help everybody!
 
Campbell Ritchie
Marshal
Posts: 55677
161
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well done
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!