My code currently filling up a HashSet with an object of Class Coin.  private HashSet&lt;Coin&gt; walletcoin; public Wallet(int WalletSize) {     walletcoin = new HashSet&lt;Coin&gt;();     for(int i = 0; i &lt; WalletSize; i++){         walletcoin.add(new Coin());     } }   This seems to be working fine.  Class Coin:  public class Coin {     public Coin(){     }     }   The second method is currently trying to remove a Coin object from the HashSet.  public int removeCoin() {     Coin toremove = new Coin();        if(walletcoin.contains(toremove))        {                if(walletcoin.remove(toremove))            {                return 1;            }         }        return 7; }   I have created a new object of Class coin, to try to search against the HashSet. Currently after testing the program skips straight to the final return statement and does not go through the if statements.  How would I be able to modify my code in order for the if statements to correctly work, and remove one of the type Coin elements from the HashSet.
7577
What issues / pitfalls must be considered when overriding equals and hashCode?
122845
As most stories here begin, I was writing some code for a project that I was working on, and stumbled across an oddity when writing some unit tests. I was testing a method that has a Set&lt;sObject&gt; parameter, and I was attempting to pass this method a Set&lt;Account&gt;.  As Account inherits from sObject, I thought this would work fine. However, when running my test, I got the error     Method does not exist or incorrect signature: [TestClass].someMethod(Set&lt;Account&gt;)   Yes, the method that I was testing expects an argument of Set&lt;sObject&gt;, but an Account can be up-cast to an sObject, and Salesforce handles that implicitly, right?  Since Salesforce was throwing a fit when I tried to rely on implicit casting, the next thing I tried was explicitly up-casting. When I tried to explicitly up-cast my set, I was greeted with a different error     Line: someNumber, Column: otherNumber   Incompatible types since an instance of Set&lt;Account&gt; is never an instance of Set&lt;SObject&gt;   This can be reproduced with the following snippet  Set&lt;sObject&gt; testSet1; Set&lt;Account&gt; testSet2 = new Set&lt;Account&gt;();  testSet1 = (Set&lt;sObject&gt;)testSet2;   I haven't found anything in the documentation to suggest that up-casts for sets aren't allowed. Given that we can up-cast Lists and Maps, I feel this is rather unexpected.  Furthermore, knowing that an Apex set is really a Java HashSet in the back-end (look at the bottom of ), I tried to look for documentation to see if this is somehow dictated by Java, but I came up empty there as well.  I've been able to move on with my project, but this leaves me wondering...  Is there some documentation (Salesforce or Java) that explains this behavior? Failing that, can someone cobble together a feasible explanation for why Sets can't be up-cast?
113807
Why does the following code not work?  I want to instantiate prefabs in a list and then use  it as a GameObject like that :  public GameObject prefab;  void Start() {   ArrayList players = new ArrayList();    for(int i=0; i&lt;5; i++)   {         players.Add( (GameObject)Instantiate(prefab));   }    players[2].transform.position = new Vector3(1, 1, 1);  }   there is an error message
90357
I am trying to tidy up some really bad legacy code from an old developer and I'm trying to get rid of these nested for loops. The code below shows what I'm currently working with. I've fixed this before with nested SOQL queries but nothing like this. How would this need to look to remove these for loops (except Trigger.New)? Would I use Maps? How would I do that?  map&lt;Id,SObject&gt; mapProperyIdBudDetail = util.GetObjFields(setPropertyId, 'Property'); map&lt;Id,SObject&gt; mapSpaceIdBudDetail = util.GetObjFields( PropertyMap.keyset(), 'Space');  for ( Lease__c l: Trigger.New ) {      if(mapProperyIdBudDetail.get(PropertyMap.get(l.space__c))!=null) {          lProperties = new List&lt;SObject&gt;{mapProperyIdBudDetail.get(PropertyMap.get(l.space__c))};              for ( SObject p: lProperties ) {                  for ( String fm: FieldMap.keyset() ) {                      if ( p.get(FieldMap.get(fm)) != Null) {                         l.put(fm,p.get(FieldMap.get(fm)));                     }                  }             }     } }
37105
I am using java language,I have a method that is supposed to return an object if it is found. If it is not found, should I:  return null throw an exception other  Which is the best practise or idiom?
23661
Context Around this Code: I am making a schedulable class run each Sunday to track a couple of metrics important to the team.   Question: I am looking to consolidate DML operations and a big part of this is understanding pass by reference vs pass by value.  I want to pass the salesOps user object to the method SDREfficiencyLastWeek. I made the return type void, because I figured that I will be passing this by reference and I can make all the updates in the method without having to anything.   Why I am confused:    I read the above article and am thrown off by the following statement:  "Non-primitive data type arguments, such as sObjects, are also passed into methods by value. "   If the object is indeed passed by reference, then the query for the salesOps user in my code should be sufficient enough to edit all fields on that object without actually having to state each field in the query.  global class SDREfficientMetricsSchedulable implements Schedulable  {     global void execute(SchedulableContext sc)      {         User salesOps = [SELECT ID FROM USER WHERE id = '0056A000002Z3p9QAC'];         List&lt;String&gt; queries = new List&lt;String&gt;();          String contactsWorked_lastWeek  = 'select count(id) results from contact where LastActivityDate = last_week';         queries.add(contactsWorked_lastWeek);          String demosSet_lastWeek            = 'select count(id) results from form__c where CreatedDate = last_week';         queries.add(demosSet_lastWeek);          String demosCompleted_lastWeek  = 'select count(id) results from opportunity where (stagename = \'Unqualified Demo Completed\'  OR stagename = \'Qualified Demo Completed\' )  and RecordTypeId = \'0126A000000yudDQAQ\' and CloseDate = last_week';         queries.add(demosCompleted_lastWeek);          String qualifiedDemos_lastWeek  = 'select count(id) results  from opportunity where RecordTypeId = \'0126A0000004Ao6QAE\' and isclosed = false and  SDR_Owner__c != null and CreatedDate = last_week';         queries.add(qualifiedDemos_lastWeek);          String closedWon_lastWeek       = 'select count(id) results  from opportunity where RecordTypeId = \'0126A0000004Ao6QAE\' and iswon = true and  SDR_Owner__c != null and CloseDate = last_week';         queries.add(qualifiedDemos_lastWeek);            SDREfficiencyLastWeek(queries, salesOps);          update salesOps;     }       public void SDREfficiencyLastWeek(List&lt;String&gt; queries, User salesOps )     {        }  }
36762
Given the following class  public class Foo {     public int FooId { get; set; }     public string FooName { get; set; }      public override bool Equals(object obj)     {         Foo fooItem = obj as Foo;          if (fooItem == null)          {            return false;         }          return fooItem.FooId == this.FooId;     }      public override int GetHashCode()     {         // Which is preferred?          return base.GetHashCode();          //return this.FooId.GetHashCode();     } }   I have overridden the Equals method because Foo represent a row for the Foos table.  Which is the preferred method for overriding the GetHashCode?  Why is it important to override GetHashCode?
13663
Assume you have some objects which have several fields they can be compared by:  public class Person {      private String firstName;     private String lastName;     private String age;      /* Constructors */      /* Methods */  }   So in this example, when you ask if:  a.compareTo(b) &gt; 0   you might be asking if a's last name comes before b's, or if a is older than b, etc...  What is the cleanest way to enable multiple comparison between these kinds of objects without adding unnecessary clutter or overhead?   java.lang.Comparable interface allows comparison by one field only Adding numerous compare methods (i.e. compareByFirstName(), compareByAge(), etc...) is cluttered in my opinion.   So what is the best way to go about this?
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); }
90809
Does anyone know if there is a good equivalent to Java's Set collection in C#? I know that you can somewhat mimic a set using a Dictionary or a HashTable by populating but ignoring the values, but that's not a very elegant way.
96218
I came across this code and wanted others to provide their point of view... is it good or bad ? ;)  Class ReportClass {  public string ReportName {get; set;} }   Then it was used as follows in code:  displayReport(ReportClass.ReportName = cmbReportName.SelectedValue.ToString())   That is about the simplest form example I can give you. Quetion is... why can't I find examples ? What would this be called? Is this just asking for trouble?  EDIT: I'm referring to the inplace assignment. Which I wasn't aware of until today
94174
When I am writing code in Python, I often need to remove items from a list or other sequence type based on some criteria. I haven't found a solution that is elegant and efficient, as removing items from a list you are currently iterating through is bad.  For example, you can't do this:  for name in names:     if name[-5:] == 'Smith':         names.remove(name)   I usually end up doing something like this:  toremove = [] for name in names:     if name[-5:] == 'Smith':         toremove.append(name) for name in toremove:     names.remove(name) del toremove   This is innefficient, fairly ugly and possibly buggy (how does it handle multiple 'John Smith' entries?). Does anyone have a more elegant solution, or at least a more efficient one?   How about one that works with dictionaries?
98914
The MSDN documentation on  describes 3 contradicting rules for how the method should work.     If two objects of the same type represent the same value, the hash function must return the same constant value for either object. For the best performance, a hash function must generate a random distribution for all input. The hash function must return exactly the same value regardless of any changes that are made to the object.   Rules 1 &amp; 3 are contradictory to me.  Does Object.GetHashCode() return a unique number based on the value of an object, or the reference to the object. If I override the method I can choose what to use, but I'd like to know what is used internally if anyone knows.
18175
Say I am iterating over a Map in Java... I am unclear about what I can to that Map while in the process of iterating over it. I guess I am mostly confused by this warning in the Javadoc for the Iterator interface remove method:     [...] The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other than by calling this method.   I know for sure that I can invoke the remove method without any issues. But while iterating over the Map collection, can I:   Change the value associated with a key with the Map class put method (put with an existing key)? Add a new entry with the Map class put method (put with a new key)? Remove an entry with the Map class remove method?   My guess is that I can probably safely do #1 (put to an existing key) but not safely do #2 or #3.  Thanks in advance for any clarification on this.
56415
I have four foreach loops that iterate through the collections and based on a condition do something.   Here is the code that I am writing now:  boolean breakFlag = false; String valueFromObj2 = null; String valueFromObj4 = null; for(Object1 object1: objects){   for(Object2 object2: object1){     // I get some value from object2     valueFromObj2 = object2.getSomeValue();     for(Object3 object3 : object2){       for(Object4 object4: object3){        // Finally I get some value from Object4.        valueFromObj4 = object4.getSomeValue();        // Compare with valueFromObj2 to decide either to break all the foreach loop        breakFlag = compareTwoVariable(valueFromObj2, valueFromObj4 );        if(breakFlag){break;}       } // fourth loop ends here       if(breakFlag){break;}     } // third loop ends here     if(breakFlag){break;}   } // second loop ends here   if(breakFlag){break;} } // first loop ends here   The main object (objects in the code) comes from a third-party provider SDK, so I cannot change anything on that portion. I want to ask the Stack&nbsp;Overflow community if there is a better approach to break all the four foreach loops. Or if there is any other way to refactor this code to make it more readable and maintainable.
17160
If i have a complex object, what is the best practice pattern to write code to compare 2 instances to see if they are the same
8608
It's clear that a search performance of the generic HashSet&lt;T&gt; class is higher than of the generic List&lt;T&gt; class. Just compare the hash-based key with the linear approach in the List&lt;T&gt; class.  However calculating a hash key may itself take some CPU cycles, so for a small amount of items the linear search can be a real alternative to the HashSet&lt;T&gt;.  My question: where is the break-even?  To simplify the scenario (and to be fair) let's assume that the List&lt;T&gt; class uses the element's Equals() method to identify an item.