This is my first post here, so please be friendly! :)  Let's say I have this code:  public static void reassign (int[] nums) {   int[] A = {10,11,22};   A = nums; }  public static void main(String[] args) {   int[] nums = {0,2};    reassign(nums);   System.out.println(nums[1]); }   Why is my answer 2, and not 11? Does it have something to do with the relative sizes of the arrays?
121
I always thought Java uses pass-by-reference. However, I've seen a couple of blog posts (for example, ) that claim that it isn't (the blog post says that Java uses pass-by-value). I don't think I understand the distinction they're making. What is the explanation?
84232
Alright, I think we all agree that what happens with the following code is undefined, depending on what is passed,  void deleteForMe(int* pointer) {      delete[] pointer; }   The pointer could be all sorts of different things, and so performing an unconditional delete[] on it is undefined. However, let's assume that we are indeed passing an array pointer,  int main() {      int* arr = new int[5];      deleteForMe(arr);      return 0; }   My question is, in this case where the pointer is an array, who is it that knows this? I mean, from the language/compiler's point of view, it has no idea whether or not arr is an array pointer versus a pointer to a single int. Heck, it doesn't even know whether arr was dynamically created. Yet, if I do the following instead,  int main() {      int* num = new int(1);      deleteForMe(num);      return 0; }   The OS is smart enough to only delete one int and not go on some type of 'killing spree' by deleting the rest of the memory beyond that point (contrast that with strlen and a non-\0-terminated string -- it will keep going until it hits 0).  So whose job is it to remember these things? Does the OS keep some type of record in the background? (I mean, I realise that I started this post by saying that what happens is undefined, but the fact is, the 'killing spree' scenario doesn't happen, so therefore in the practical world someone is remembering.)
26165
I have a class that contains a dynamically allocated array, say  class A {     int* myArray;     A()     {         myArray = 0;     }     A(int size)     {         myArray = new int[size];     }     ~A()     {         // Note that as per MikeB's helpful style critique, no need to check against 0.         delete [] myArray;     } }   But now I want to create a dynamically allocated array of these classes. Here's my current code:  A* arrayOfAs = new A[5]; for (int i = 0; i &lt; 5; ++i) {     arrayOfAs[i] = A(3); }   But this blows up terribly. Because the new A object created (with the A(3) call) gets destructed when the for loop iteration finishes, and this means that the internal myArray of that A instance gets delete []-ed.  So I think my syntax must be terribly wrong? I guess there are a few fixes that seem like overkill, which I'm hoping to avoid:   Creating a copy constructor for A. Using vector&lt;int&gt; and vector&lt;A&gt; so I don't have to worry about all this. Instead of having arrayOfAs be an array of A objects, have it be an array of A* pointers.   I would think this is just some beginners thing where there's a syntax that actually works when attempting to dynamically allocate an array of things that have internal dynamic allocation.  (Also, style critiques appreciated, since it's been a while since I did C++.)  Update for future viewers: All of the answers below are really helpful. Martin's is accepted because of the example code and the useful "rule of 4," but I really suggest reading them all. Some are good, succinct statements of what's wrong, and some point out correctly how and why vectors are a good way to go.
70083
I'm trying to find out how much memory my objects take to see how many of them are ending up on the  (which is anything over 85,000 bytes). Is it as simple as adding 4 for an int, 8 for a long, 4 (or 8 if you're on 64 bit) for any reference types etc for each object, or are there overheads for methods, properties, etc.?
119176
In some text it is given that we can't assign constant values to a reference variable. When I executed such a program I could do it. Is there any condition we can't assign a constant value to a reference variable?
22625
MyClass[] array; List&lt;MyClass&gt; list;   What are the scenarios when one is preferable over the other? And why?
13274
Does anybody have useful example of this assignment inside a C# method? I have been asked for it once during job interview, and I am still interested in answer myself.
77422
I have a call to a method in a class as follows:  String key1 = "test1"; String key2 = "test2";  long[] datalr = new long[] {}; datalr = TestClass.callerSub(key1,key2);   The test class is as follows:  public class TestClass {  Public TestClass { }  public long[] callerSub(string key1, String key2){  long[] datalr = new long[] {0,0};  datalr[0] = 2; datalr[1] = 3;  return datalr;  } }   I'm getting the following error in the first class:  Error: Compile Error: Method does not exist or incorrect signature: TestClass.callerSub(String, String) at line 54 column 12       which is the following line:  datalr = TestClass.callerSub(key1,key2);   The datalr data in the callerSub method is just an example above,  Any idea why?  Thanks
14488
I saw this in , in reference to shortcomings of the Java spec:  There are more shortcomings and this is a subtle topic. Check  out: public class methodOverloading{      public static void hello(Integer x){           System.out.println(&quot;Integer&quot;);      }       public static void hello(long x){           System.out.println(&quot;long&quot;);      }       public static void main(String[] args){          int i = 5;          hello(i);      } }  Here &quot;long&quot; would be printed (haven't checked it myself), because the compiler chooses widening over auto-boxing. Be careful when using auto-boxing or don't use it at all!  Are we sure that this is actually an example of widening instead of autoboxing, or is it something else entirely? On my initial scanning, I would agree with the statement that the output would be &quot;long&quot; on the basis of i being declared as a primitive and not an object.  However, if you changed hello(long x)  to hello(Long x)  the output would print &quot;Integer&quot; What's really going on here?  I know nothing about the compilers/bytecode interpreters for java...
115971
In the context of C++ (not that it matters):  class Foo{     private:         int x[100];     public:         Foo(); }   What I've learnt tells me that if you create an instance of Foo like so:  Foo bar = new Foo();   Then the array x is allocated on the heap, but if you created an instance of Foo like so:  Foo bar;   Then it's created on the stack.  I can't find resources online to confirm this.
94519
Is it possible in c# to initialize an array in, for example, subindex 1?  I'm working with Office interop, and every property is an object array that starts in 1 (I assume it was originally programed in VB.NET), and you cannot modify it, you have to set the entire array for it to accept the changes.  As a workaround I am cloning the original array, modifying that one, and setting it as a whole when I'm done.  But, I was wondering if it was possible to create a new non-zero based array
832
.NET offers a generic list container whose performance is almost identical (see Performance of Arrays vs. Lists question). However they are quite different in initialization.   Arrays are very easy to initialize with a default value, and by definition they already have certain size:  string[] Ar = new string[10];   Which allows one to safely assign random items, say:  Ar[5]="hello";   with list things are more tricky. I can see two ways of doing the same initialization, neither of which is what you would call elegant:  List&lt;string&gt; L = new List&lt;string&gt;(10); for (int i=0;i&lt;10;i++) L.Add(null);   or  string[] Ar = new string[10]; List&lt;string&gt; L = new List&lt;string&gt;(Ar);   What would be a cleaner way?  EDIT: The answers so far refer to capacity, which is something else than pre-populating a list. For example, on a list just created with a capacity of 10, one cannot do L[2]="somevalue"  EDIT 2: People wonder why I want to use lists this way, as it is not the way they are intended to be used. I can see two reasons:   One could quite convincingly argue that lists are the "next generation" arrays, adding flexibility with almost no penalty. Therefore one should use them by default. I'm pointing out they might not be as easy to initialize. What I'm currently writing is a base class offering default functionality as part of a bigger framework. In the default functionality I offer, the size of the List is known in advanced and therefore I could have used an array. However, I want to offer any base class the chance to dynamically extend it and therefore I opt for a list.
44787
If you are creating a 1d array, you can implement it as a List, or else use the 'array' module in the standard library.  I have always used Lists for 1d arrays.  What is the reason or circumstance where I would want to use the array module instead?  Is it for performance and memory optimization, or am I missing something obvious?
95446
What are the differences between multidimensional arrays double[,] and array-of-arrays double[][] in C#?  If there is a difference, what is the best use for each one?
99159
I didn't understand the permutation and of course, I got this question wrong.     Compute the inverse of the following permutation:   $$ \begin{pmatrix}  1&amp;2&amp;3&amp;4&amp;5&amp;6\\ 2&amp;5&amp;4&amp;1&amp;6&amp;3 \end{pmatrix} $$   Could you please help me with this question and provide an explanation?  Furthermore, is it possible to compute the direct permutation, not the inverse one? If yes, how?  Thank you in advance!
83735
private void activateRecords(long[] stuff) {     ...     api.activateRecords(Arrays.asList(specIdsToActivate));   }   Shouldn't this call to Arrays.asList return a list of Longs?  Instead it is returning a List&lt;long[]&gt;  public static &lt;T&gt; List&lt;T&gt; asList(T... a)   The method signature is consistent with the results, the varargs throws the entire array into the list.  It's the same as new ArrayList(); list.add(myArray)  And yes, I know it's meant to be used like this: Arrays.asList(T t1, T t2, T t3)  I guess what I'm getting at, is instead of the varargs form, why can't I just have my old asList method (at least I think this is how it used to work) that would take the contents and put them individually into a list?  Any other clean way of doing this?
8697
While looking at online code samples, I have sometimes come across an assignment of a String constant to a String object via the use of the new operator.  For example:  String s; ... s = new String("Hello World");   This, of course, compared to  s = "Hello World";   I'm not familiar with this syntax and have no idea what the purpose or effect would be.  Since String constants typically get stored in the constant pool and then in whatever representation the JVM has for dealing with String constants, would anything even be allocated on the heap?