why does my arraylist print out [ben][ben, ben] when it should print out ben ben could anyone help me please? my code is below thanks loftty ArrayList arr = new ArrayList(); Hashtable hash = new Hashtable(); String st1 = "ben"; String st2 = "alex"; String st3 = "ben"; String st4 = "cust"; hash.put("a", st1); hash.put("b", st2); hash.put("c", st3); hash.put("d", st4); Enumeration e = hash.elements(); while (e.hasMoreElements()) { String se = (String)e.nextElement();
Your program is printing correct result. Since you are testing for se == st1 it will be true for two times. Once when first "ben" is encountred and at that time you added "ben" to array list and printed [ben]. Again for st3, se == st1 will be true because you are using String literals and not String object created by new operator. and, second time it is printing [ben,ben]. If you want to see your result then please try creating String objects as:
String st1 = new String ("ben");
String st2 = new String ("alex");
String st3 = new String ( "ben" );
String st4 = new String ( "cust" );
I know that you will have some more question. Please read about String instance pooling in Java and then you should be fine.
Hey Kishori, I searched for the Java String instance pooling in Google and nothing remotely close appeared. Do you have a good resource to read about it 'cause it seems fairly interesting. Where did you learn that?