Search code examples
javastringsocketsarraylistinputstream

Adding each new value of a String 'temp' value to ArrayList without overwriting previous 'temp'


My input is coming from a socket using DataInputSteam and because I can have several different String values all being assigned to same clientDayOfWeek string, I cannot figure out how to save all the string values coming in into the same ArrayList without replacing the last value. I'd also like no duplicates if possible.

       Socket socket = null;
       DataInputStream dataInputStream = null;
       dataInputStream = new DataInputStream(
                              socket.getInputStream());

       String clientDayOfWeek = dataInputStream.readUTF();
       ArrayList<String> ar = new ArrayList<String>();
       String temp = clientDayOfWeek;
       ar.add(temp);
       System.out.print("Items in list: "+ ar);

Solution

  • Thanks Prasaanth, that's what I was doing wrong.

    I needed my ArrayList<String> ar = new ArrayList<String>(); to be global and simplified the rest as follows inside my method.

    dataInputStream = new DataInputStream(
                            socket.getInputStream());
       ar.add(dataInputStream.readUTF());
       System.out.print("ar: "+ar);