Java Help
 
Forums: » Register « |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support | 
User Name:
Password:
Remember me

The Shed is going Social! Join us on FaceBook and Twitter and chime in on the conversation.

Go Back   Dev Shed ForumsProgramming LanguagesJava Help

Reply
Add This Thread To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 
Thread Tools Search this Thread Rate Thread Display Modes
 
Unread Dev Shed Forums Sponsor:
  #1  
Old May 1st, 2008, 07:35 AM
johnire johnire is offline
Registered User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: May 2008
Posts: 2 johnire User rank is Private First Class (20 - 50 Reputation Level)johnire User rank is Private First Class (20 - 50 Reputation Level) 
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: ");
	}

}


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;
	}


}

Reply With Quote
  #2  
Old May 1st, 2008, 07:41 AM
Yawmark's Avatar
Yawmark Yawmark is offline
Feelin' Groovy
Dev Shed God 11th Plane (10000 - 10499 posts)
 
Join Date: Aug 2001
Location: WDSMIA
Posts: 10,135 Yawmark User rank is General 61st Grade (Above 100000 Reputation Level)Yawmark User rank is General 61st Grade (Above 100000 Reputation Level)Yawmark User rank is General 61st Grade (Above 100000 Reputation Level)Yawmark User rank is General 61st Grade (Above 100000 Reputation Level)Yawmark User rank is General 61st Grade (Above 100000 Reputation Level)Yawmark User rank is General 61st Grade (Above 100000 Reputation Level)Yawmark User rank is General 61st Grade (Above 100000 Reputation Level)Yawmark User rank is General 61st Grade (Above 100000 Reputation Level)Yawmark User rank is General 61st Grade (Above 100000 Reputation Level)Yawmark User rank is General 61st Grade (Above 100000 Reputation Level)Yawmark User rank is General 61st Grade (Above 100000 Reputation Level)Yawmark User rank is General 61st Grade (Above 100000 Reputation Level)Yawmark User rank is General 61st Grade (Above 100000 Reputation Level)Yawmark User rank is General 61st Grade (Above 100000 Reputation Level)Yawmark User rank is General 61st Grade (Above 100000 Reputation Level)Yawmark User rank is General 61st Grade (Above 100000 Reputation Level) 
Time spent in forums: 3 Months 1 Week 4 Days 1 h 22 m 45 sec
Reputation Power: 5052
Send a message via ICQ to Yawmark Send a message via MSN to Yawmark
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)));}}

Reply With Quote
  #3  
Old May 1st, 2008, 07:47 AM
johnire johnire is offline
Registered User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: May 2008
Posts: 2 johnire User rank is Private First Class (20 - 50 Reputation Level)johnire User rank is Private First Class (20 - 50 Reputation Level) 
Time spent in forums: 36 m 45 sec
Reputation 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.

Reply With Quote
  #4  
Old November 22nd, 2012, 03:59 PM
KarelKruger KarelKruger is offline
Registered User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Nov 2012
Posts: 2 KarelKruger User rank is Just a Lowly Private (1 - 20 Reputation Level) 
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

Reply With Quote
  #5  
Old November 29th, 2012, 05:56 AM
Revoh Revoh is offline
Contributing User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Mar 2007
Location: Portugal
Posts: 38 Revoh User rank is Corporal (100 - 500 Reputation Level)Revoh User rank is Corporal (100 - 500 Reputation Level)Revoh User rank is Corporal (100 - 500 Reputation Level)Revoh User rank is Corporal (100 - 500 Reputation Level) 
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.

Reply With Quote
Reply

Viewing: Dev Shed ForumsProgramming LanguagesJava Help > Homework - ArrayList = Next element overwriting previous element?

Developer Shed Advertisers and Affiliates



Thread Tools  Search this Thread 
Search this Thread:

Advanced Search
Display Modes  Rate This Thread 
Rate This Thread:


Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
View Your Warnings | New Posts | Latest News | Latest Threads | Shoutbox
Forum Jump

Forums: » Register « |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support | 
  
 


Powered by: vBulletin Version 3.0.5
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.

© 2003-2013 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap