I was doing the AoC day six challenge when I noticed a bug in my program. In the code below, when using List&lt;string&gt;.Clear() and the end of the loop I had 486 copies of the last List&lt;String&gt;'s values. I found a fix (hack?) but I want to know why .Clear() isn't working on my List&lt;String&gt;. Full program can be found  int result = 0; List&lt;List&lt;string&gt;&gt; groups = new List&lt;List&lt;string&gt;&gt;(); List&lt;string&gt; buffer = new List&lt;string&gt;(); buffer.Clear();  foreach (string s in lineList) {      if (!string.IsNullOrEmpty(s))     {         buffer.Add(s);     }     else     {         groups.Add(buffer);          //// old way         //// was getting 487 copies of the last group         // buffer.Clear          // new way, works but I don't understand why         // byref vs byval issue?         buffer = new List&lt;string&gt;();      }     }
80428
I have a class like this:  public class myClass {   public List&lt;myOtherClass&gt; anewlist = new List&lt;myOtherClass&gt;;    public void addToList(myOtherClass tmp)   {     anewList.Add(tmp);   }  }   So I call "addToList" a hundred times, each adding a unique item to the list.  I've tested my items to show that before I run the "addToList" method, they are unique.  I even put a line in to test "tmp" to make sure it was what I was expecting.  However, when I do this (lets say myClass object is called tmpClass):  int i = tmpClass.anewList.Count(); for (int j = 0; j&lt;i; j++) {    //write out each member of the list based on index j... }   I get the same exact item, and it's the last one that was written into my list.  It's as if when I add, I'm overwriting the entire list with the last item I've added.    Help?  This makes no sense. I've also tried List.Insert, where I'm always inserting at the end or at index 0.  Still no dice.  Yes, I'm doubly source my indexing is correct and when I do my test I'm indexing through each of the elements.  :)  UPDATE: Okay, I tried this and still had the same problem:  foreach(myOtherClass tmpC in tmpClass.anewList) {         Console.WriteLine(tmpC.theStringInMyClass.ToString()); }   and still for each of the 100 items, I got the same string output... I'm sure I'm doing something completely stupid, but I don't know what yet. I'm still 100% sure that the right string is getting passed in to begin with.  -Adeena    Okay, I tried this and still had the same problem:  foreach(myOtherClass tmpC in tmpClass.anewList) {     Console.WriteLine(tmpC.theStringInMyClass.ToString()); }   and still for each of the 100 items, I got the same string output...  I'm sure I'm doing something completely stupid, but I don't know what yet. I'm still 100% sure that the right string is getting passed in to begin with.  -Adeena
78162
I collect a few corner cases and  and would always like to hear more. The page only really covers C# language bits and bobs, but I also find core .NET things interesting too. For example, here's one which isn't on the page, but which I find incredible:  string x = new string(new char[0]); string y = new string(new char[0]); Console.WriteLine(object.ReferenceEquals(x, y));   I'd expect that to print False - after all, "new" (with a reference type) always creates a new object, doesn't it? The specs for both C# and the CLI indicate that it should.  Well, not in this particular case. It prints True, and has done on every version of the framework I've tested it with. (I haven't tried it on Mono, admittedly...)  Just to be clear, this is only an example of the kind of thing I'm looking for - I wasn't particularly looking for discussion/explanation of this oddity. (It's not the same as normal string interning; in particular, string interning doesn't normally happen when a constructor is called.) I was really asking for similar odd behaviour.  Any other gems lurking out there?
560
It seems that a List object cannot be stored in a List variable in C#, and can't even be explicitly cast that way.  List&lt;string&gt; sl = new List&lt;string&gt;(); List&lt;object&gt; ol; ol = sl;   results in Cannot implicitly convert type System.Collections.Generic.List&lt;string&gt; to System.Collections.Generic.List&lt;object&gt;  And then...  List&lt;string&gt; sl = new List&lt;string&gt;(); List&lt;object&gt; ol; ol = (List&lt;object&gt;)sl;   results in Cannot convert type System.Collections.Generic.List&lt;string&gt; to System.Collections.Generic.List&lt;object&gt;  Of course, you can do it by pulling everything out of the string list and putting it back in one at a time, but it is a rather convoluted solution.
4327
Is there a way in Java's for-each loop  for(String s : stringArray) {   doSomethingWith(s); }   to find out how often the loop has already been processed?  Aside from using the old and well-known for(int i=0; i &lt; boundary; i++) - loop, is the construct  int i = 0; for(String s : stringArray) {   doSomethingWith(s);   i++; }   the only way to have such a counter available in a for-each loop?
31644
I'm looking for a clear, concise and accurate answer.    Ideally as the actual answer, although links to good explanations welcome.  This also applies to VB.Net, but the keywords are different - ByRef and ByVal.
46378
Can someone explained, as detailed as possible, the differences between the following types?  List List&lt;Object&gt; List&lt;?&gt;   Let me make this more specific. When would I want to use  // 1  public void CanYouGiveMeAnAnswer(List l) { }  // 2 public void CanYouGiveMeAnAnswer(List&lt;Object&gt; l) { }  // 3 public void CanYouGiveMeAnAnswer(List&lt;?&gt; l) { }
7172
What would be the best way to look in a string[] to see if it contains a element. This was my first shot at it. But perhaps there is something that I am overlooking. The array size will be no larger than 200 elements.  bool isStringInArray(string[] strArray, string key) {     for (int i = 0; i &lt;= strArray.Length - 1; i++)         if (strArray[i] == key)             return true;     return false; }
113159
I'm not sure why I'm getting this error, but shouldn't this code compile, since I'm already checking to see if queue is getting initialized?   public static void Main(String[] args) {     Byte maxSize;     Queue queue;      if(args.Length != 0)     {         if(Byte.TryParse(args[0], out maxSize))             queue = new Queue(){MaxSize = maxSize};         else             Environment.Exit(0);     }     else     {         Environment.Exit(0);     }      for(Byte j = 0; j &lt; queue.MaxSize; j++)         queue.Insert(j);     for(Byte j = 0; j &lt; queue.MaxSize; j++)         Console.WriteLine(queue.Remove()); }   So if queue is not initialized, then the for loops aren't reachable right? Since the program already terminates with Environment.Exit(0)?  Hope ya'll can give me some pointers :)  Thanks.
122018
I am trying to add a list into an another nested list before adding values of a list to nested list it is getting the correct value but after adding i am getting (already output) in debug log when i checked.    public List&lt;String&gt; fieldName {get;set;}  public List&lt;List&lt;String&gt;&gt; fileValuesXML; // To get the field values of xml  for(Dom.XMLNode child : SalesforceObjecet.getChildElements()) {                        objecetName = child.getText();             system.debug('Object Name in XML field  ' + objecetName );              for(Dom.XMLNode subchild : child.getChildElements())              {                 system.debug('Sub child ' + subchild.getText() );                 for(Dom.XMLNode subchildfield : subchild.getChildElements())                 {                     system.debug('Sub child Field ' + subchildfield );                     fName  = subchildfield.getText();                     fieldName.add(fName);                     //fileValuesXML.add(fieldName);                     //system.debug('Filed Name in XML field  ' + fieldName);                 }                  system.debug('Filed Name before affing to filevalueXML  ' + fieldName);                                     fileValuesXML.add(fieldName);                 fieldName.clear();                 system.debug('Filed Name after affing to filevalueXML  ' + fileValuesXML);             }    }    I am getting values in debug log as:     Filed Name before affing to filevalueXML  (AccountSource, field3)   Filed Name after affing to filevalueXML  ((), (already output),   (already output))
9629
I use a lot of lists and arrays but I have yet to come across a scenario in which the array list couldn't be used just as easily as, if not easier than, the linked list.  I was hoping someone could give me some examples of when the linked list is notably better.
9051
Check out the below program.   try {     for (String data : Files.readAllLines(Paths.get("D:/sample.txt"))){         String[] de = data.split(";");         System.out.println("Length = " + de.length);     } } catch (IOException e) {     e.printStackTrace(); }   Sample.txt:   1;2;3;4 A;B;; a;b;c;   Output:   Length = 4 Length = 2 Length = 3   Why second and third output is giving 2 and 3 instead of 4. In sample.txt file, condition  for 2nd and 3rd line is should give newline(\n or enter) immediately after giving delimiter for the third field. Can anyone help me how to get length as 4 for 2nd and 3rd line without changing the condition of the sample.txt file and how to print the values of de[2] (throws  ArrayIndexOutOfBoundsException)?
43660
I have a list of structs and I want to change one element. For example :  MyList.Add(new MyStruct("john"); MyList.Add(new MyStruct("peter");   Now I want to change one element:  MyList[1].Name = "bob"   However, whenever I try and do this I get the following error:     Cannot modify the return value of   System.Collections.Generic.List.this[int]‘ because it is not   a variable   If I use a list of classes, the problem doesn't occur.  I guess the answer has to do with structs being a value type.  So, if I have a list of structs should I treat them as read-only? If I need to change elements in a list then I should use classes and not structs?
106050
Hi I'm pretty new to Stack Overflow so I hope that I'm doing this correctly and that someone out there has the answer I need.  I'm currently coding a program in Java with Eclipse IDE an my question is this:  I need a snippet of code that does the following  It's supposed to get a .TXT file containing text and from that .TXT file  count the number of rows and print it,  count the number of words and print it,  count the number of characters and print it. And finally make a list of the top 10 words used and print that.  Allt the printing is done to system outprintln  I'm pretty new to Java and am having some difficulties.  Anyone out there who can provide me with these lines of code or that knows where i can find them? I want to study the code provided that's how I learn best=)  Thanks to all   Didnt find the edit button sorry...  I Added this to my question:  Hehe it´s an assignment but not a homework assignment ok i see well i could provide what i've done so far, i think im pretty close but it´s not working for me. Is there anything i have missed?  // Class    Tip   import java.io.*; import java.util.*;  class Tip {     public static void main(String [] args) throws Exception     {          String root = System.getProperty("user.dir");            InputStream is = new FileInputStream( root + "\\tip.txt" );         Scanner scan = new Scanner( is );          String tempString = "";         int lines = 0;         int words = 0;         Vector&lt;Integer&gt; wordLength = new Vector&lt;Integer&gt;();         int avarageWordLength = 0;          while(scan.hasNextLine() == true)         {                 tempString = scan.nextLine();                 lines++;         }          is.close();          is = new FileInputStream( root );         scan = new Scanner( is );          while(scan.hasNext() == true)         {                 tempString = scan.next();                 wordLength.add(tempString.length());                 words++;         }          for(Integer i : wordLength)         {                 avarageWordLength += i;         }         avarageWordLength /= wordLength.size();           System.out.println("Lines : " + lines);         System.out.println("Words : " + words);         System.out.println("Words Avarage Length : " + avarageWordLength);          is.close();          } }
80540
I'm trying to do some treatement after creating an item but the treatement is done twice because in my code after creating the item, I'm updating it , so the event reciever get fired twice: first when I add the element and the second when I updated it. Here's the code :  if (Mode == OperationMode.New) {     item = ListeActions.AddItem();     item["Client"] = new SPFieldLookupValue(myClient.ID, myClient["Name"] as string).ToString();     //the Event Reciever ItemAdded is fired here } if (Mode == OperationMode.Edit) {     item = ListeActions.GetItemById(ActionItemID); } TextField ACObject = (TextField)Page.GetControlById("ACObjectID"); UserField ACAssignedTo = (UserField)Page.GetControlById("ACAssignedToID"); NoteField ACDetails = (NoteField)Page.GetControlById("ACDetailsID");  item["Object"] = ACObject.Value; item["AssignedTo"] = ACAssignedTo.Value; item["Details"] = ACDetails.Value;  item.Update();  //if we're in the case of adding new item then the event //reciever ItemAdded is fired here for the second time //while ItemUpdated is not fired   So how can I stop the second fire of itemAdded resulting on the item.Update() yet keep the first fire since I need to keep applying my treatement?  PS: in the case of updating an existing ListeActions.item the itemUpdated is fired twice too !!  BTW : This Code isn't written in the itemadded method nor in the itemupdated method, actually it's the code in a user control for a webpart development.
70164
Lets say I have this array,  int[] numbers = {1, 3, 4, 9, 2};   How can I delete an element by "name"? , lets say number 4?  Even ArrayList didn't help to delete?  string strNumbers = " 1, 3, 4, 9, 2"; ArrayList numbers = new ArrayList(strNumbers.Split(new char[] { ',' })); numbers.RemoveAt(numbers.IndexOf(4)); foreach (var n in numbers) {     Response.Write(n); }
19431
What, if any, is the performance difference between the following two loops?  for (Object o: objectArrayList) {     o.DoSomething(); }   and   for (int i=0; i&lt;objectArrayList.size(); i++) {     objectArrayList.get(i).DoSomething(); }
3385
In the two following snippets, is the first one safe or must you do the second one?  By safe I mean is each thread guaranteed to call the method on the Foo from the same loop iteration in which the thread was created?  Or must you copy the reference to a new variable "local" to each iteration of the loop?  var threads = new List&lt;Thread&gt;(); foreach (Foo f in ListOfFoo) {           Thread thread = new Thread(() =&gt; f.DoSomething());     threads.Add(thread);     thread.Start(); }   -  var threads = new List&lt;Thread&gt;(); foreach (Foo f in ListOfFoo) {           Foo f2 = f;     Thread thread = new Thread(() =&gt; f2.DoSomething());     threads.Add(thread);     thread.Start(); }   Update: As pointed out in Jon Skeet's answer, this doesn't have anything specifically to do with threading.