Need Help with Linked List problem PLEASE

hi im having a slight problem trying to understand why my linked list has stopped working

heres some code snipits

System.out.println(names); // this prints [markmistry ]     this is my LinkedList
System.out.println(newname); // this prints markmistry    this is a String variable
locationIndex1 = names.indexOf(newname); locationIndex1 is an int
System.out.println(locationIndex1); // this prints -1   why?

It’s not entirely clear what’s going on because you’ve not provided the exact code you’re using, but I’ve got a guess.

In a LinkedList, indexOf returns -1 if it does not find what you were looking for.
http://java.sun.com/j2se/1.5.0/docs/api/java/util/LinkedList.html#indexOf(java.lang.Object)

So you’re getting -1 because “markmistry” isn’t found in your list. Even though your list prints out “markmistry,” the problem is with string comparison.

i.e.

String a = “markmistry”;
String b = “markmistry”;

if (a == b)
{
System.out.println(“Equal”);
}
else
{
System.out.println(“Not Equal”);
}

The above would not print out Equal, it would print Not Equal, because using == is a memory address comparison, not a value comparison. What you would want to do is this:

if (a.equals(b))
{
System.out.println(“Equal”);
}
else
{
System.out.println(“Not Equal”);
}

And that would print Equal.

The indexOf method… wow I was going to say indexOf uses == but then I checked the docs myself… it actually uses .equals. Okay.

Looking further into it, it looks like your names array contains the string "markmistry " but you’re looking for “markmistry” . Make sure there is no space in there.

i noticed the space at the end of the string in the array or list whateveryou call it so i added a space to the string it still didnt work heres the entire class hope i dont get told off for posting this but i am really stuck basically i am trying to send private messages to only the person that indexof finds.
bigger snippet


    private static class Handler extends Thread {

        private String name;
        private Socket socket;
        private BufferedReader in;
        private PrintWriter out;

        public Handler(Socket socket) {

            this.socket = socket;
        }

        public void run() {

            try {

                in = new BufferedReader(new InputStreamReader(
                    socket.getInputStream()));

                out = new PrintWriter(socket.getOutputStream(), true);

                while (true) {

					out.println("SUBMITNAME");
					name  = in.readLine();
									
				

                    if (name == null) {
                        return;
                    }

                    synchronized (names) {

                        if (!names.contains(name)) {

                            names.add(name);
							// indexOf will work here but no where else ??
							
							ClientArea.append(name+ "\n");	
							break;
                        }

                    }

                }


                writers.add(out);

                while (true) {


                    String input = in.readLine();
					messageArea.setCaretPosition(messageArea.getDocument().getLength());
					messageArea.append(name + " : " + input+"\n");
					System.out.println(input);
                    if (input == null) {
                        return;
                    }
					
                    if (input.startsWith("PRIVATE")){
					
						StringTokenizer st = new StringTokenizer(input,"PRIVATE");
				
						newname = st.nextToken();
						newmess = st.nextToken();
						newname2 = st.nextToken();
						
						messageArea.setCaretPosition(messageArea.getDocument().getLength());
						messageArea.append("Private message intended for "+newname+ " message = "+ newmess+" private from "+newname2+"\n");
// this below doesnt work
						
						synchronized (names) {
						
							System.out.println(names);
							System.out.println(newname);
							locationIndex1 = names.indexOf(newname);
							System.out.println(locationIndex1);
						
							if (names.contains(newname)) {

								System.out.println("true name was found");
								
								try{
				
									locationIndex1 = names.indexOf(newname);
									
									((PrintWriter)writers.get(locationIndex1)).println("PRIVATE"+":" +newname2+":" +newmess);
									//System.out.println("Private message intended for "+newname+ " message = "+  newmess+" private from "+newname2);
								}
								
								catch (Exception e){
				
									System.out.println(e);
								}
							}
						}

					}
					
					else{
					
						for ( i = writers.iterator(); i.hasNext();){
      
							if (exitee!=""){

								((PrintWriter)i.next()).println("MESSAGE " +":" +  exitee + ":" + "logging out"+"\n"+"MESSAGE " +":" + name + ":" 									+ input);
								//System.out.println(exitee + ": " + "logging out");
					
							}
							
							else{
							
								((PrintWriter)i.next()).println("MESSAGE " +":" + name + ":" + input);
								//System.out.println("MESSAGE " + name + ": " + input);
							}
						}
						
						exitee ="";
					}
                }



            }


better idea i am going to remove private facility its only for a game chat anyway not needed really.
ill figure it out when i get like a few months free time ;D

If you return to this, I’d suggest actually looping through your entire names list and doing comparisons one at a time, printing out both the names and the comparison result. Maybe something else altogether is happening, and the names are not being properly added or something like that, which you’ll only know by inspecting the whole array when you want to do the comparison. I’d also make sure that your threading is not causing some problems, for instance, make sure you’re not storing separate name lists for each thread or something like that.

Is that just a typo that you have a space on the end of markmistry when you print the actual list out?

[markmistry ] <- Notice the space after the string and before the ]

// Json

no mate the space is there in the array when i call it but if i add a blank space at the end of the string it still doesnt work and it prints the same result.
the threading issue has crossed my mind several times when i check for "name " or “name” directly instead of the variable reference it still doesnt work…lol its a right head scratcher

for testing i log on as 1 person and tried to send private to myself only 1 name in array i printed it i checked the client code to see if im adding a blank char at end of the name i send when logging on to the gameserver everythings fine…the thing is…it used to work fine…ive recently updated my jre and im starting to think it may be that but no worries i removed the private …for now i got bigger problems like

1 min i can log on to game via my sql with a name and password thats not there the next min i cant ??? wtf???

Part of the problem is solved now on to the next part.
I managed to track down the culprit

			kickass.newuser = kickass.newuser.replace('/',' ');  

I use the “/” as a delimiter and i replaced it with ’ ’ but i had forgot to trim the whitespace from the end

			String mynewstring = kickass.newuser.trim();
			kickass.newuser = mynewstring;

all is to sort out my print writer


try{
      locationIndex1 = names.indexOf(newname);

// is ithis correct below as im sure it used to work
      ((PrintWriter)writers.get(locationIndex1)).println("PRIVATE"+": " +newname2+": " +newmess); 
}
catch (Exception e){
      System.out.println(e);
}
[\code]

First of all

kickass.newuser = kickass.newuser.replace('/',' ');

could probably be replaced with

kickass.newuser = kickass.newuser.replace('/',' ').trim();

or even

kickass.newuser = kickass.newuser.replace("/","");

which would replace the “/” with an empty string.

Second I’m not really sure how your lists writers and names are created and if these are the only places you do add on them, but relying on the list indexes to be the same in names and writers might not be the best. You might be better off having a map for the writers.


    final PrintWriter out = new PrintWriter(socket.getOutputStream(), true);

    final Map<String, PrintWriter> writers = new HashMap<String, PrintWriter>();

    writers.put(newname, out);

    // Later on when you want to get that one just do a get on the name as a key
    final PrintWriter thisUsersPrintWriter = writers.get(newname);

Something like that, I don’t know the full story but maybe you need to change the structure a little bit.

// Json

Thanks i will take a look at that but the (’/’,’’) wont work i tried it compiler complains blank character literal i will try the trim at the end :O) nice to learn new ways of doing something…cheers

Thats why you should use normal quotes and not single quotes in your replace, just like I typed it in the example :smiley:

// Json