EASY problem with arraylist indexoutofboundsexeption
Code:
ArrayList<String> lastname2 = new ArrayList();
//int x = lastname.size() - 1;
int x = lastname.size();
//System.out.print(x);
do
{
lastname2.add(lastname.get(x));
x = x-1;
}while (x != -1);
Collections.sort(lastname, String.CASE_INSENSITIVE_ORDER);
String moreinput = JOptionPane.showInputDialog(null, counter + " people voted.\n\rTheir last names:\n\r " + lastname + "\n\rEnter the last name of whoever you want to look up: ");
int finalindex = lastname2.indexOf(moreinput);
JOptionPane.showMessageDialog(null, "Their information:\n\r" + firstname.get(finalindex) + lastname2.get(finalindex) + "\n\r" + address.get(finalindex) + "\n\r" + city.get(finalindex) + ", " + state.get(finalindex) + "\n\r" + zipcode.get(finalindex));
This part of a voting poll program I'm making is supposed to duplicate the arraylist "lastname" and call the new arraylist "lastname2," then sort lastname arraylist alphabetically, while letting you look up the information of any voter by referencing lastname2. The two lines commented out are some variations I've been experimenting with (the println(x) is just to see if x even gets a value set (spoiler: it doesnt....))
I'm very new to java, so any help solving this would be appreciated.
--
I have a feeling the solution is very simple and I'm just missing something, or if somebody has a suggestion as to a better way to code this instead of a DoWhile loop....
i thought of that also, as you can see with one of the lines commented out... I tried
int x = lastname.size() - 1;
same thing...
also i just tried all 3 of the options you kindly provided, but none worked.
also, i posted that while i was on my phone in a rush, sorry it's in the wrong place.
should i post my whole code or something? it looks like the problem isn't with this area.
well i found the problem... the variables that were added to "lastname" were.... never added. but i don't really know how to add them... the code i have is about 50 lines though, are you allowed to post that long? lol
As mentioned, when copying out of a list you should use a for or a while, not a do/while. Do while's indicate that its guaranteed to perform the first action, whilst your list is currently empty so you cannot retrieve the first item. You can use a try/catch of course.
It may be a lot easier to simply invoke the .clone() method on the primary list though and use that copy. Its shallow clone, but if its just for sorting for whatever reason than that is fine.
If the problem is adding to the collection, post that code.