Homework - ArrayList = Next element overwriting previous element?
Discuss ArrayList = Next element overwriting previous element? in the Java Help forum on Dev Shed. ArrayList = Next element overwriting previous element? Java Help forum discussing all Java platforms - J2ME, J2SE and J2EE - as well as relevant standards, APIs and frameworks such as Swing, Servlets, JSPs, Applets, Struts, Spring, Hibernate, ANT, EJB, and other Java-related topics.
Posts: 2
Time spent in forums: 36 m 45 sec
Reputation Power: 0
Homework - ArrayList = Next element overwriting previous element?
Hi there - the next element of my ArrayList seems to be overwriting the previous element. I'm sure it's something simple, but I can't see. Any help is greatly appreciated. I add an element to the arraylist, and it works fine - but when i add another it overwrites it and i have two identical elements.
Thanks again,
John.
personMain.java
Code:
import java.util.Iterator;
import java.util.ListIterator;
import java.util.ArrayList;
public class personMain{
public static void main(String[] args){
// variables
int switchVar; // for switch statement
ArrayList<Person> people = new ArrayList<Person>(); // create new LinkedList of type Person
Person s = new Person(); // declare new object of type Person
Iterator<Person> itr = people.iterator();
String firstName;
String surname;
String colour;
String personToSearchFor;
int age;
int userToRemove = 0;
int userToEdit = 0;
menu(); // display menu
switchVar = Keyboard.readInt();
while(switchVar != 6){ // loop switch statement until user wishes to exit
switch(switchVar){
case 1:
// add person
System.out.println("Add a person.");
System.out.print("First name: ");
firstName = Keyboard.readString();
s.setFirstName(firstName);
System.out.print("Surname: ");
surname = Keyboard.readString();
s.setSurname(surname);
System.out.print("Age: ");
age = Keyboard.readInt();
s.setAge(age);
System.out.print("Favourite color: ");
colour = Keyboard.readString();
s.setColour(colour);
people.add(people.size(), s);
break;
case 2:
// edit person
System.out.print("Select a user ID to edit: ");
userToEdit = Keyboard.readInt();
System.out.print("First name: ");
firstName = Keyboard.readString();
people.get(userToEdit).setFirstName(firstName);
System.out.print("Surname: ");
surname = Keyboard.readString();
people.get(userToEdit).setSurname(surname);
System.out.print("Age: ");
age = Keyboard.readInt();
people.get(userToEdit).setAge(age);
System.out.print("Favourite color: ");
colour = Keyboard.readString();
people.get(userToEdit).setColour(colour);
break;
case 3:
// remove person
System.out.print("Select a user ID to remove: ");
userToRemove = Keyboard.readInt();
people.remove(userToRemove);
break;
case 4:
// search for a person
System.out.print("Enter user's surname: ");
personToSearchFor = Keyboard.readString();
break;
// print out contents of the array list
case 5:
System.out.print("\nAddress Book:\n");
for(int i = 0; i < people.size(); i++){
System.out.println("------------------------------------");
System.out.println("First Name: " + people.get(i).getFirstName());
System.out.println("Surname: " + people.get(i).getSurname());
System.out.println("Age: " + people.get(i).getAge());
System.out.println("Favourite colour: " + people.get(i).getFavColour());
System.out.println("------------------------------------\n");
}
break;
// exit application
default:
System.out.println("Exiting application..\n");
}
menu(); // display menu
switchVar = Keyboard.readInt();
}
}
//=================================================
// Menu
//=================================================
public static void menu(){
System.out.println("\nPerson Management System");
System.out.println("------------------------\n");
System.out.println("1. Add person.");
System.out.println("2. Edit person.");
System.out.println("3. Remove person.");
System.out.println("4. Search for a person.");
System.out.println("5. Print all users.");
System.out.println("6. Exit.\n");
System.out.print("Enter choice: ");
}
}
Posts: 10,135
Time spent in forums: 3 Months 1 Week 4 Days 1 h 22 m 45 sec
Reputation Power: 5052
When you "add a new person", you're actually just modifying the existing Person object because you're reusing the same reference. If you want to add a new Person, you'll want to actually create a new Person object.
~
__________________ Yawmark
class Sig{public static void main(String...args){\u0066or(int
\u0020$:"vÌÈÊ\"¤¾Àʲ¬Æ\"v¤Î¤\"²¤¨¸¬Æ".to\u0043h\u0061rArray()
)System./*goto/*$/%\u0126//^\u002A\u002Fout.print((char)(($>>
+(~'"'&'#'))+('<'>>('\\'/'.')/\u002Array.const(~1)\*\u002F)));}}
Posts: 2
Time spent in forums: 55 m 4 sec
Reputation Power: 0
Similar problem with arraylist overwrite
Hi all
I seem to have a similar problem - an element of my arraylist is overwritten. I tried to use this thread as guidance to my problem, but I have not managed to solve it.
In my program (which is actually a FBDK function block algorithm implemented in Java), I want to store the data of an input variable (PART) into an element of an out variable array (PART_array). This process will happen multiple times (with the occurence of an event) and must thus store the variable in several array elements.
The problem is that the elements of PART_array are overwritten by the last entry. For instance, for the first event occurence, PART_array[] = ["1"," "," "," "," "," "]. Then, with the second occurence, instead of PART_array[] = ["1","2"," "," "," "," "], I find PART_array[] = ["2","2"," "," "," "," "] - thus showing the overwrite. I have realised that overwrite already occurs with the storage to PART_ARRAY ArrayList. I thought that by reinitializing (p = new Part()) the problem would be solved...obviously not.
Any help in solving this problem will be GREATLY appreciated! The code is as follows:
Code:
package fb.rt;
import java.util.ArrayList;
import fb.datatype.*;
import fb.rt.*;
import fb.rt.events.*;
public class STORE_TO_ARRAY extends fb.rt.FBInstance {
/** Normal Execution Request */
public final EventInput REQ = new EventInput(this);
/** Execution Confirmation */
public final EventOutput CNF = new EventOutput();
/** EVENT NEXT */
public final EventOutput NEXT = new EventOutput();
/** VAR NumOfTasks:INT */
public INT NumOfTasks = new INT();
/** VAR current_task:INT */
public INT current_task = new INT();
/** VAR PART:WSTRING */
public WSTRING PART = new WSTRING();
/** VAR next_task:INT */
public final INT next_task = new INT();
/** VAR PART_array:WSTRING */
public final ARRAY PART_array = new ARRAY(new WSTRING(), 6);
public ArrayList<Part> PART_ARRAY = new ArrayList<Part>();
Part p = new Part();
//public WSTRING[] part = new WSTRING[6];
/** The default constructor. */
public STORE_TO_ARRAY(){
super();
}
/** The index (2) of state REQ. */
public static final int index_REQ = 2;
/** The actions to take upon entering state REQ. */
private void state_REQ(){
eccState = index_REQ;
alg_REQ();
serviceEvent(null);}
public void serviceEvent(EventServer e){
switch(eccState){
case index_START:
if ((e == REQ)) state_REQ();
}
}
/** ALGORITHM REQ IN Java*/
public void alg_REQ(){
int ct = 0;
ct = current_task.value;
System.out.println("Store_to_Array triggered with current task = " + ct);
System.out.println("NumOfTasks.value = " + NumOfTasks.value);
if(ct <= NumOfTasks.value){
//write received input data to output variable array elements
p.setPart(PART);
PART_ARRAY.add(ct-1,p);
Part p = new Part();
PART = new WSTRING();
int nt = ct + 1;
next_task.value = (short)nt;
if(ct == NumOfTasks.value){
for(int i = 0;i<= ct-1;i++){
PART_array.value[i] = PART_ARRAY.get(i).getPart();
System.out.println("PART_arraylist["+i+"] = " + PART_ARRAY.get(i).getPart().toString());
System.out.println("PART[] = " + PART_array.value[i].toString());
}
CNF.serviceEvent(this);
}
else{
NEXT.serviceEvent(this);
System.out.println("NEXT triggered");
}
}
}
}
The class file for Part is as follows:
Code:
package fb.rt;
import fb.datatype.WSTRING;
public class Part {
WSTRING part;
void setPart(WSTRING part){
this.part = part;
}
WSTRING getPart(){
return part;
}
}
Many thanks in advance!
Regards
Karel
Last edited by KarelKruger : November 23rd, 2012 at 02:37 AM.
Reason: Addition of info
Posts: 38
Time spent in forums: 4 Days 6 h 34 m 46 sec
Reputation Power: 8
KarelKruger
Your code seems to have some sort of problem here:
Code:
public void alg_REQ(){
int ct = 0;
ct = current_task.value;
System.out.println("Store_to_Array triggered with current task = " + ct);
System.out.println("NumOfTasks.value = " + NumOfTasks.value);
if(ct <= NumOfTasks.value)
{
//write received input data to output variable array elements
p.setPart(PART);
PART_ARRAY.add(ct-1,p);
Part p = new Part();
PART = new WSTRING();
int nt = ct + 1;
next_task.value = (short)nt;
if(ct == NumOfTasks.value){
for(int i = 0;i<= ct-1;i++){
PART_array.value[i] = PART_ARRAY.get(i).getPart();
System.out.println("PART_arraylist["+i+"] = " + PART_ARRAY.get(i).getPart().toString());
System.out.println("PART[] = " + PART_array.value[i].toString());
}
CNF.serviceEvent(this);
}
else{
NEXT.serviceEvent(this);
System.out.println("NEXT triggered");
}
}
That code will only run once, cause you aren't inside of a cicle, and the for cicle where you do the print it actually does what u want because it will only write value to the first position of the array.
And after you write the first value for the first position it will go into the for cicle.