#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2008
    Posts
    2
    Rep Power
    0

    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: ");
    	}
    
    }
    Person class file
    Code:
    public class Person{
    	int age;
    	String firstName;
    	String surname;
    	String favColour;
    
    	void setAge(int age){
    		this.age = age;
    	}
    
    	int getAge(){
    		return age;
    	}
    
    	void setSurname(String surname){
    		this.surname = surname;
    	}
    
    	String getSurname(){
    		return surname;
    	}
    
    	void setFirstName(String firstName){
    		this.firstName = firstName;
    	}
    
    	String getFirstName(){
    		return firstName;
    	}
    
    	void setColour(String favColour){
    		this.favColour = favColour;
    	}
    
    	String getFavColour(){
    		return favColour;
    	}
    
    
    }
  2. #2
  3. Feelin' Groovy
    Devshed Supreme Being (6500+ posts)

    Join Date
    Aug 2001
    Location
    WDSMIA
    Posts
    10,135
    Rep Power
    5053
    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.

    ~

    Comments on this post

    • johnire agrees : thanks
    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)));}}
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2008
    Posts
    2
    Rep Power
    0
    I love you!

    I just added s = new Person(); after I used it and now it works like a charm. Thanks again!

    Comments on this post

    • Yawmark agrees : You're welcome. :)
  6. #4
  7. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    2
    Rep 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
  8. #5
  9. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2007
    Location
    Portugal
    Posts
    38
    Rep Power
    9
    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.

IMN logo majestic logo threadwatch logo seochat tools logo