I'm a bit stumped by this as I am still pretty new to Java.  Here is my issue:  I need to return an object by using a string to pass it to another object. Ie, I want to pass a string to the function (getObject in this case) and then compare it to an ArrayList of unit objects by using their getCode function.  What I have so far:  private Unit getUnitObject(String unit1Code) {   for (int i = 0; i &lt; units.size(); i++) {     Unit currUnit = units.get(i);     String unitCode = currUnit.getUnitCode();      if (unit1Code == unitCode) {       Unit selectedUnit = currUnit;       return selectedUnit;     }    } }   It gives me an error - "this method must return a result of type unit" I tried moving the return out of the for loop and still had no success? Can I do it this way?
93
I've been using the == operator in my program to compare all my strings so far. However, I ran into a bug, changed one of them into .equals() instead, and it fixed the bug.  Is == bad? When should it and should it not be used? What's the difference?
92805
I have a class A and another class that inherits from it, B. I am overriding a function that accepts an object of type A as a parameter, so I have to accept an A. However, I later call functions that only B has, so I want to return false and not proceed if the object passed is not of type B.  What is the best way to find out which type the object passed to my function is?
827
If I have an object implementing the Map interface in Java and I wish to iterate over every pair contained within it,  what is the most efficient way of going through the map?  Will the ordering of elements depend on the specific map implementation that I have for the interface?
91805
Short prestory. Typical problem: you have a lot of small string and you want to concatenate them all in one big string. The code like for(Integer i = 0; i &lt; smallStringsSize; i++){     bigString += smallStrings[i]; }  will solve this problem, but it has to produce a lot of unnecessary string objects that consume your heap. That is why Java has classes like StringBuilder and StringBuffer that allow you to solve this problem wihtout consuming too many memory. Thus, I decided to try to do my own StringBuilder in apex. String class has two methods that looked suitable for it:   and  . Here is the code that i used to test these methods against &quot;+=&quot; concatenantion (ready to execute in anonymous): List&lt;String&gt; chars = new List&lt;String&gt;(); List&lt;Integer&gt; charsCode = new List&lt;Integer&gt;(); Integer size = 10000; String chartToAdd = 'Ω'; for(Integer i = 0; i &lt; size; i++){     chars.add(chartToAdd);     charsCode.add(String.valueOf(chartToAdd).charAt(0)); } String joinS = '', forS = '', fromS = ''; Integer initialHeapSize = Limits.getHeapSize(); Integer initialCPUtime = Limits.getCpuTime(); System.debug('initialHeapSize ' + initialHeapSize); System.debug('initialCPUtime ' + initialCPUtime); joinS = String.join(chars, ''); Integer joinHeapSize = Limits.getHeapSize() - initialHeapSize; Integer joinCPUtime = Limits.getCpuTime() - initialCPUtime; System.debug('-------- String.join ---------'); System.debug('joinHeapSize ' + joinHeapSize); System.debug('joinCPUtime ' + joinCPUtime); for(Integer i = 0; i &lt; size; i++){     forS += chars[i]; } Integer forHeapSize = Limits.getHeapSize() - joinHeapSize - initialHeapSize; Integer forCPUtime = Limits.getCpuTime() - joinCPUtime - initialCPUtime; System.debug('-------- for each += ---------'); System.debug('forHeapSize ' + forHeapSize); System.debug('forCPUtime ' + forCPUtime); fromS = String.fromCharArray(charsCode); Integer fromHeapSize = Limits.getHeapSize() - forHeapSize - joinHeapSize - initialHeapSize; Integer fromCPUtime = Limits.getCpuTime() - forCPUtime - joinCPUtime - initialCPUtime; System.debug('-------- String.fromCharArray ---------'); System.debug('fromHeapSize ' + fromHeapSize); System.debug('fromCPUtime ' + fromCPUtime); System.debug(''); System.debug('-------- strings ----------'); System.debug('joins ' + joins); System.debug('fors ' + fors); System.debug('fromS ' + fromS);  The result of this code execution:  initialHeapSize 161166 initialCPUtime 242 -------- String.join --------- joinHeapSize 10016 joinCPUtime 17 -------- for each += --------- forHeapSize 10024 forCPUtime 48 -------- String.fromCharArray --------- fromHeapSize 10016 fromCPUtime 5  As you can see, the heap size for each approach is so close to 10 kilobytes, what is a size of the string of 10 000 characters (size) if each character takes only one byte. In case of creating 10 000 additional string objects, the heap size would be a bit more than 50 megabytes (10 000 * (1 + 10 000)/2). Taking into consideration the above,  Does not the '+=' concatenation create any additional string objects that devour your heap? Did not I miss anything? I am so amazed.  As you see, I use Omega 'Ω' as a chartToAdd. It has  the high-surrogate code point equals to 937, that needs at least 2 bytes to be encoded. How can 10 000 Omegas consume only 10 000 bytes of the heap size?  What weightful reasons Salesforce has that they do not to add the character data type? Any ideas?
17519
I have a string containing the , and I need to convert it to a Java Date object.  String date = "1081157732"; DateFormat df = new SimpleDateFormat(""); // This line try {   Date expiry = df.parse(date);  } catch (ParseException ex) {   ex.getStackTrace(); }   The marked line is where I'm having trouble. I can't work out what the argument to SimpleDateFormat() should be, or even if I should be using SimpleDateFormat().
64500
Currently, I'm trying to get a method in Python to return a list of zero, one, or two strings to plug into a string formatter, and then pass them to the string method. My code looks something like this:  class PairEvaluator(HandEvaluator):   def returnArbitrary(self):     return ('ace', 'king')  pe = PairEvaluator() cards = pe.returnArbitrary() print('Two pair, {0}s and {1}s'.format(cards))   When I try to run this code, the compiler gives an IndexError: tuple index out of range. How should I structure my return value to pass it as an argument to .format()?
5691
Is there a better way of getting this result? This function fails if num has more digits than digits, and I feel like it should be in the library somewhere (like Integer.toString(x,"%3d") or something)  static String intToString(int num, int digits) {     StringBuffer s = new StringBuffer(digits);     int zeroes = digits - (int) (Math.log(num) / Math.log(10)) - 1;      for (int i = 0; i &lt; zeroes; i++) {         s.append(0);     }     return s.append(num).toString(); }
40009
I have the following code that shows either a bug or a misunderstanding on my part.  I sent the same list, but modified over an ObjectOutputStream.  Once as [0] and other as [1].  But when I read it, I get [0] twice.  I think this is caused by the fact that I am sending over the same object and ObjectOutputStream must be caching them somehow.  Is this work as it should, or should I file a bug?   import java.io.*; import java.net.*; import java.util.*;  public class OOS {      public static void main(String[] args) throws Exception {         Thread t1 = new Thread(new Runnable() {             public void run() {                 try {                     ServerSocket ss = new ServerSocket(12344);                     Socket s= ss.accept();                      ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream());                     List same = new ArrayList();                     same.add(0);                     oos.writeObject(same);                     same.clear();                     same.add(1);                     oos.writeObject(same);                  } catch(Exception e) {                     e.printStackTrace();                 }             }         });         t1.start();          Socket s = new Socket("localhost", 12344);         ObjectInputStream ois = new ObjectInputStream(s.getInputStream());          // outputs [0] as expected         System.out.println(ois.readObject());          // outputs [0], but expected [1]         System.out.println(ois.readObject());         System.exit(0);     } }
62286
I need to make some reflective method calls in Java. Those calls will include methods that have arguments that are primitive types (int, double, etc.). The way to specify such types when looking up the method reflectively is int.class, double.class, etc.  The challenge is that I am accepting input from an outside source that will specify the types dynamically. Therefore, I need to come up with these Class references dynamically as well. Imagine a delimited file a list of method names with lists of parameter types:  doSomething int double doSomethingElse java.lang.String boolean   If the input was something like java.lang.String, I know I could use Class.forName("java.lang.String") to that Class instance back. Is there any way to use that method, or another, to get the primitive type Classes back?  Edit: Thanks to all the respondents. It seems clear that there is no built-in way to cleanly do what I want, so I will settle for reusing the ClassUtils class from the Spring framework. It seems to contain a replacement for Class.forName() that will work with my requirements.
80627
I have a string variable that represents the name of a custom class. Example:   string s = "Customer";   I will need to create an arraylist of customers. So, the syntax needed is:  List&lt;Customer&gt; cust = new ..    How do I convert the string s to be able to create this arraylist on runtime?
118759
Question  I'm writing some code that needs to be able to get the values of the parameters from the method that called into the class. I know how to get all the way to the ParameterInfo[] array, but I don't know how to then get the values. Is this even possible?  If it is, I think it has something to do with using the MethodBody property from the MethodInfo object, which allows you to inspect the IL stream, including properties, but I don't know how to do it, and I haven't found applicable code on Google.  Code  // Finds calling method from class that called into this one public class SomeClass {     public static void FindMethod()     {         for (int i = 1; i &lt; frameCount; i++)         {             var frame = new StackFrame(i);             var methodInfo = frame.GetMethod();             if (methodInfo.DeclaringType != this.GetType())             {                 string methodName = frame.GetMethod().Name;                 var paramInfos = methodInfo.GetParameters();                  // Now what?? How do I get the values from the paramInfos                  break;             }             else if (i == frameCount - 1)             {                 throw new TransportException("Couldn't find method name");             }         }     } }
3650
This could be the dumbest question ever asked but I think it is quite confusing for a Java newbie.    Can somebody clarify what is meant by immutable?  Why is a String immutable? What are the advantages/disadvantages of the immutable objects? Why should a mutable object such as StringBuilder be preferred over String and vice-verse?   A nice example (in Java) will be really appreciated.
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 )     {        }  }
37382
I'm a C++ guy learning Java. I'm reading Effective Java and something confused me. It says never to write code like this:  String s = new String("silly");   Because it creates unnecessary String objects. But instead it should be written like this:  String s = "No longer silly";   Ok fine so far...However, given this class:  public final class CaseInsensitiveString {     private String s;     public CaseInsensitiveString(String s) {         if (s == null) {             throw new NullPointerException();         }         this.s = s;     }     :     : }  CaseInsensitiveString cis = new CaseInsensitiveString("Polish"); String s = "polish";    Why is the first statement ok? Shouldn't it be   CaseInsensitiveString cis = "Polish"; How do I make CaseInsensitiveString behave like String so the above statement is OK (with and without extending String)? What is it about String that makes it OK to just be able to pass it a literal like that? From my understanding there is no "copy constructor" concept in Java?
24638
I read  and thought that would easily be solved (not that it isn't solvable without) if one could write:   @Override public String toString() {     return super.super.toString(); }   I'm not sure if it is useful in many cases, but I wonder why it isn't and if something like this exists in other languages.  What do you guys think?  EDIT: To clarify: yes I know, that's impossible in Java and I don't really miss it. This is nothing I expected to work and was surprised getting a compiler error. I just had the idea and like to discuss it.
84091
ok, ive a class and i pass an object as property.  the object that i pass is a List&lt;X&gt;  in my class im trying to access the Object index by reflection BUT I CAN'T!!!   Example:  this class works i just wrote down the part i want to show you and i need help.  class MyClass {     private object _recordSet;     public object RecordSet     {         get { return _recordSet; }         set { _recordSet = value; }     }      public string Draw()     {         system.reflection.Assembly asem = system.reflection.Assembly.getAssembly(_dataSource.GetType());          object instance;          instance = asem.CreateInstance(_dataSource.GetType().UnderlyingSystemType.FullName);          //to access de Count of my List         int recordcount = int.Parse(_dataSource.GetType().GetProperty("Count").GetValue(_dataSource,null));          //i need to do a          for(int cont = 0; cont &lt; recordCount; cont++)         {             _dataSource[cont].Name; // &lt;-- THIS PART IS NOT WORKING!!! because i cant access the Index Directly.... WHAT TO DO!! ???         }     } }
3046
Assuming I have an ArrayList  ArrayList&lt;MyClass&gt; myList;   And I want to call toArray, is there a performance reason to use  MyClass[] arr = myList.toArray(new MyClass[myList.size()]);   over  MyClass[] arr = myList.toArray(new MyClass[0]);   ?  I prefer the second style, since it's less verbose, and I assumed that the compiler will make sure the empty array doesn't really get created, but I've been wondering if that's true.  Of course, in 99% of the cases it doesn't make a difference one way or the other, but I'd like to keep a consistent style between my normal code and my optimized inner loops...