Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 3 of 3

Thread: new arrayList element overwrites all previous

  1. #1
    Junior Member
    Join Date
    Apr 2010
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Post new arrayList element overwrites all previous

    Hi, i have a program that has a Database class that is used to create an ArrayList that stores patients. I have a Patient class which defines what a Patient is and i have a server class which creates a simple server and allows a user to connect to using telnet or similar program. patients can be added to the database but when i add the second one, it adds it ok to the next position in the array but it also overwrites the previous stored ones to make identical. I know i need to create a new object for the patient but i have tried to do this already both by adding it as a field and declaring it in the begining and by removing that declaration and declaring it in the relevant if statement and niether seem to fix the problem. how much of my code would i need to post? all the relevent pieces or all my code... this is for an assignment and i read on another post when i was looking for a solution similar before posting and read that turnitin scans the site so i wouldnt want to flag my work as somebody elses cos they find it posted on a forum :(

    I think this is the relevent code if it isnt enough i will upload it all

     
    import java.net.*;
    import java.util.StringTokenizer;
    import java.io.*;
     
    public class Server {
    	public static void main(String args[]) {
    		new SimpleServer(6001) ;
    	}        
     
    } // class Server1
     
    class SimpleServer {
    	//	ArrayList<Patient> patients = new ArrayList<Patient>();
    	Database db;
    	public ServerSocket sock;
    	public Socket conn;
    	public BufferedReader in;
    	public BufferedWriter out;
    	public String str;
     
    	SimpleServer(int port) {
    		super();
                                                      try {
    			in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    		              } catch (Exception e) {
    			System.out.println("Error : " + e);
    			System.out.println("Can't get input stream for socket");
    			System.exit(1);
    		              }	
     
                                                      try {
    			out = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()));
    		             } catch (Exception e) {
    			System.out.println("Error : " + e);
    			System.out.println("Can't get output stream for socket");
    			System.exit(1);
    		             }
     
    		try {
                                                       do {
     
                                                                try {
    				// wait for client to send data
    				str = in.readLine();
    				if (str.endsWith("ADD")){
    					Patient pat = new Patient();
    					StringTokenizer  st = new StringTokenizer(str, ":");
    					pat.setID(st.nextToken());
    					pat.setfName(st.nextToken());
    					pat.setlName(st.nextToken());
    					pat.setCondition(st.nextToken());
    					pat.setHealth(st.nextToken());
    					System.out.print(Patient.getID());
    					db.patients.add(pat);
    					System.out.println("Output: " + db.patients.get(0));
    					out.write("#~                Patient Information.                    ");
    					out.write("#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
    					out.write("#~ Patient ID:        " + Patient.getID() +"                                 ");
    					out.write("#~ Patient Name:      " + Patient.getfName() + Patient.getlName() + "                            ");
    					out.write("#~ Patient Condition: " + Patient.getCondition() +"                                 ");
    					out.write("#~ Patient Health:    " + Patient.getHealth() + "                                ");
    					out.write("#~                                                        ");
    					out.write("#~         Patient has been added to system!              "); 
    					out.write("#~                                                        ");
    					out.write("#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
    					out.write("##########################################################\n\nInput :>");
    					System.out.println(db.patients.size());
    				}
    				out.newLine();
    				out.flush();
    			} catch(IOException e) {
    				System.out.println("Error : " + e);
    				System.exit(1);
    			}catch(NullPointerException e){
    				System.out.println("Terminal has tried to exit without typing EXIT" + e);
    			}
    			System.out.println("Client sent string " + str.trim());
    		}  while ( !str.startsWith("exit") );
     
    		System.out.println("Closing server now");
    		System.exit(0);
     
    	}  // SimpleServer constructor

    This is my database class :-

     
     
    import java.util.ArrayList;
    import java.io.Serializable;
     
    public class Database implements Serializable{
     
    	/**
    	 * A class to define the database, used to enable records to stored 
    	 *  as Patient Objects . 
    	 * @author u0669469
    	 */
    	private static final long serialVersionUID = 8397775991766188997L;
    	//List of Patients.
    	ArrayList<Patient> patients = new ArrayList<Patient>();
    	/**
    	 * Add the Patient to the array list.
    	 * @param newPatient
    	 */
    	public void addPatient(Patient newPatient) {
    		patients.add(newPatient);
    	}
     
    	public Patient retrievePatient(String name) {
    		System.out.println("Patient " + patients);
    		return null;
    	}
     
    	public void removePatient(int remove) {
    		patients.remove(remove);
    	}
     
    	public void removeList() {
    		patients.clear();
    	}
     
    	public int numberOfPatients(int patientNumber)
    	{
    		return patients.size();
    	}
    }

    And this is my Patient Class:-

    import java.io.Serializable;
    public class Patient implements Serializable {
     
    	/**
    	 * A class to define what a patient is, used to enable records to be kept to a consistant
    	 * format. 
    	 * @author u0669469
    	 */
    	private static final long serialVersionUID = 8949306406483963579L;
    	public static String  patientID;
    	public static String  fName;
    	public static String  lName;
    	public static String  condition;
    	public static String  health;
     
     
    public Patient() {
     
    	}
    	public static String getCondition() {
    		return condition;
    	}
     
    	public void setCondition(String condition) {
    		Patient.condition = condition;
    	}
     
    	public static String getHealth() {
    		return health;
    	}
     
    	public void setHealth(String health) {
    		Patient.health = health;
    	}
     
    	public static String getID() {
    		return patientID;
    	}
     
    	public void setID(String iD) {
    		patientID = iD;
    	}
     
    	public static String getfName() {
    		return fName;
    	}
     
    	public void setfName(String fName) {
    		Patient.fName = fName;
    	}
     
    	public static String getlName() {
    		return lName;
    	}
     
    	public void setlName(String lName) {
    		Patient.lName = lName;
    	}
     
     
    }

    I have tried creating a new Patient in many places and non of them seem to work. I would appreciate any thoughts on what the problem might be? am i not referencing a new Patient object properly or is my arrayList not set up properly?

    My code compiles ok and there are no errors present when i try to compile so im guessing its something obvious that im forgetting?
    Last edited by twinkletoes; April 1st, 2010 at 03:42 PM.


  2. #2
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,372
    Thanks
    183
    Thanked 836 Times in 779 Posts
    Blog Entries
    5

    Default Re: new arrayList element overwrites all previous

    You are 'overwriting' because your Patient class has all static variables, so every time you set one it appears they all change (when in fact there is only one of each). These should be instance variables to get the behavior you want. See Understanding Instance and Class Members for more information. Also, when you print them out make sure you retrieve the last entered Patient in the Database, not the first, otherwise you will always be printing out the first entered Patient (and thus appear you are 'overwriting').

  3. #3
    Junior Member
    Join Date
    Apr 2010
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Smile Re: new arrayList element overwrites all previous

    Thank you very much i changed the methods to static in eclipse as it flagged them as errors... but this is obviously due to my confusion when writing the output. I have written arraylists before and couldnt understand why this wouldnt work but thank you again youve saved my hair from ending up on the floor in clumps

    ill look at the way the Patients are printed out and thank you also for pointing this out

Similar Threads

  1. How to use an ArrayList and what is its advantage over array?
    By JavaPF in forum Java SE API Tutorials
    Replies: 4
    Last Post: December 21st, 2011, 04:44 AM
  2. Add white spices before the String element
    By bookface in forum Java Theory & Questions
    Replies: 1
    Last Post: March 23rd, 2010, 09:50 PM
  3. [SOLVED] theory behind testing each element of an array.
    By etidd in forum Java Theory & Questions
    Replies: 2
    Last Post: February 5th, 2010, 09:04 AM
  4. How to extract a particular element details which has more references ???
    By j_kathiresan in forum Algorithms & Recursion
    Replies: 1
    Last Post: December 31st, 2009, 01:11 AM
  5. [SOLVED] Extracting an How to ArrayList from an ArrayList and convert to int??
    By igniteflow in forum Collections and Generics
    Replies: 2
    Last Post: August 16th, 2009, 02:11 PM