I'm new at Java and I came across a problem I couldn't find a solution to, so maybe somebody can help me out. When I write this code: ArrayList&lt;String&gt; Liste = new ArrayList&lt;&gt;(); String Name;  Liste.add(&quot;Harry&quot;); Name = Liste.get(0); Name = &quot;Dieter&quot;;  System.out.print(Liste.get(0)); System.out.print(Name);  The output is, as expected: Harry Dieter  However, if I change the type to a custom object: ArrayList&lt;Names_Class&gt; Liste = new ArrayList&lt;&gt;(); Names_Class Name;  Liste.add(new Names_Class()); Liste.get(0).First_Name = &quot;Harry&quot;; Name = Liste.get(0); Name.First_Name = &quot;Dieter&quot;;  System.out.print(Liste.get(0)); System.out.print(Name);  The output becomes: Dieter Dieter  So it seems Java only copies a references or something. Could somebody explain what happens here, and how I can get a complete copy of a single item out of an ArrayList?
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?
16225
Why does it (apparently) make a difference whether I pass null as an argument directly, or pass an Object that I assigned the value null?  Object testVal = null; test.foo(testVal);    // dispatched to foo(Object) // test.foo(null);    // compilation problem -&gt; "The method foo(String) is ambiguous"     public void foo(String arg) { // More-specific     System.out.println("foo(String)"); }  public void foo(Object arg) { // Generic     System.out.println("foo(Object)"); }   In other words, why is the (commented-out) second call to foo(...) not dispatched to foo(Object)?  Update: I use Java 1.6. I could compile Hemal's code without problems, but mine still doesn't compile. The only difference I see is that Hemal's methods are static while mine are not. But I really don't see why this should make a difference...?  Update 2: Solved. I had another method foo(Runnable) in my class, so the dispatcher couldn't unambiguously select the single most specific method. (See my comment in Hemal's second answer.) Thanks everyone for your help.
17166
I have a list of integers, List&lt;Integer&gt; and I'd like to convert all the integer objects into Strings, thus finishing up with a new List&lt;String&gt;.  Naturally, I could create a new List&lt;String&gt; and loop through the list calling String.valueOf() for each integer, but I was wondering if there was a better (read: more automatic) way of doing it?
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?
109364
I have a method which takes params object[] such as:  void Foo(params object[] items) {     Console.WriteLine(items[0]); }   When I pass two object arrays to this method, it works fine:  Foo(new object[]{ (object)"1", (object)"2" }, new object[]{ (object)"3", (object)"4" } ); // Output: System.Object[]   But when I pass a single object[], it does not take my object[] as the first param, instead it takes its all elements like I wanted to pass them one by one:  Foo(new object[]{ (object)"1", (object)"2" }); // Output: 1, expected: System.Object[]   How do I pass a single object[] as a first argument to a params array?
18114
I have a method with an out parameter that tries to do a type conversion. Basically:  public void GetParameterValue(out object destination) {     object paramVal = "I want to return this. could be any type, not just string.";      destination = null; // default out param to null     destination = Convert.ChangeType(paramVal, destination.GetType()); }   The problem is that usually someone would call this like:  string output; GetParameterValue(output);   This will fail because of:  destination.GetType()   destination is null, so we can't call .GetType() on it. We also can not call:  typeof(destination)   because destination is a variable name not a type name.  So is there any way to get the type of an object that is set to null? I would think there would have to be a way to know what type a storage location is without it being assigned anything.    Just to give a bit more info, I am trying to make a utility method that will grab the output parameters of an Oracle stored procedure. The issue is that DbParameter.Value is of type object.  What would be ideal would be for the developers to do something like:  string val = GetParameterValue("parameterName");   The notable thing is that there is no casting of types. In practice, you don't know the lparam of the "equals", so I went with:  string val; GetParameterValue("parameterName", out val);   And figured within the method, I would know the destination type of the output variable. I guess that was a bad assumption. As an alternative, I also wrote the method:  public T GetParameterValue&lt;T&gt;(string paramName)   So the developers can do:  string val = GetParameterValue&lt;string&gt;("parameterName");   I find the explicit "string" declaration to be repetitive, especially since in practice, the destination if probably an object property and the oracle data type could change (think ORM):  MyObj.SomeProp = GetParameterValue&lt;MyObj.SomeProp.GetType()&gt;("parameterName");   But again, if MyObj.SomeProp is null, that .GetType() call fails. The VM has to know the type of MyObj.SomeProp, even when its null, right? or else how would it catch cast exceptions?    To partially solve my own problem, I can do:  MyObj.SomeProp = GetParameterValue&lt;typeof(MyObj).GetField("SomeProp").GetType()&gt;("parameterName");   The whole idea was to not have to explicitly use the Type in more than one place, so that if the data type changes, it only has to be changed in the destination object (MyObj.SomeProp) and in the DB. There has to be a better way...
99253
I like how Java has a Map where you can define the types of each entry in the map, for example &lt;String, Integer&gt;.   What I'm looking for is a type of collection where each element in the collection is a pair of values.  Each value in the pair can have its own type (like the String and Integer example above), which is defined at declaration time.    The collection will maintain its given order and will not treat one of the values as a unique key (as in a map).    Essentially I want to be able to define an ARRAY of type &lt;String,Integer&gt; or any other 2 types.    I realize that I can make a class with nothing but the 2 variables in it, but that seems overly verbose.    I also realize that I could use a 2D array, but because of the different types I need to use, I'd have to make them arrays of OBJECT, and then I'd have to cast all the time.    I only need to store pairs in the collection, so I only need two values per entry.  Does something like this exist without going the class route?  Thanks!
23825
I got an anonymous type inside a List anBook:  var anBook=new []{  new {Code=10, Book ="Harry Potter"}, new {Code=11, Book="James Bond"} };   Is to possible to convert it to a List with the following definition of clearBook:  public class ClearBook {   int Code;   string Book;  }   by using direct conversion, i.e., without looping through anBook?
282
Conditions: do not modify the original lists; JDK only, no external libraries. Bonus points for a one-liner or a JDK 1.3 version. Is there a simpler way than: List&lt;String&gt; newList = new ArrayList&lt;String&gt;(); newList.addAll(listOne); newList.addAll(listTwo);
85933
I was writing a toString() for a class in Java the other day by manually writing out each element of the class to a String and it occurred to me that using reflection it might be possible to create a generic toString() method that could work on ALL classes. I.E. it would figure out the field names and values and send them out to a String.  Getting the field names is fairly simple, here is what a co-worker came up with:  public static List initFieldArray(String className) throws ClassNotFoundException {      Class c = Class.forName(className);     Field field[] = c.getFields();     List&lt;String&gt; classFields = new ArrayList(field.length);      for (int i = 0; i &lt; field.length; i++) {         String cf = field[i].toString();         classFields.add(cf.substring(cf.lastIndexOf(".") + 1));     }      return classFields; }   Using a factory I could reduce the performance overhead by storing the fields once, the first time the toString() is called. However finding the values could be a lot more expensive.  Due to the performance of reflection this may be more hypothetical then practical. But I am interested in the idea of reflection and how I can use it to improve my everyday programming.
28627
String fieldSetName = 'Account_FieldSet'; String ObjectName = 'Account';   I wanted get list of all fields from this fieldset.  I know if fieldset name is hardcoded in the apex then following syntax works -   SObjectType.Account.FieldSets.Account_FieldSet.getFields();   But here main issue is Object name and fieldset name will come at runtime.
93303
If I have the following code: MyType&lt;int&gt; anInstance = new MyType&lt;int&gt;(); Type type = anInstance.GetType();  How can I find out which type argument(s) &quot;anInstance&quot; was instantiated with, by looking at the type variable? Is it possible?
18599
I want to return two objects from a Java method and was wondering what could be a good way of doing so?  The possible ways I can think of are: return a HashMap (since the two Objects are related) or return an ArrayList of Object objects.  To be more precise, the two objects I want to return are (a) List of objects and (b) comma separated names of the same.  I want to return these two Objects from one method because I dont want to iterate through the list of objects to get the comma separated names (which I can do in the same loop in this method).  Somehow, returning a HashMap does not look a very elegant way of doing so.
3879
So I was playing around a little more with attributes in .NET, and realized that every call to Type.GetCustomAttributes() creates a new instance of my attribute. Why is that? I would think that the attribute instance would basically be a singleton-per-MemberInfo, with 1 instance bound to the Type, PropertyInfo, etc...  Here is my test code:  using System;  namespace AttribTest { [AttributeUsage(AttributeTargets.Class)] class MyAttribAttribute : Attribute {     public string Value { get; set; }      public MyAttribAttribute()         : base()     {         Console.WriteLine("Created MyAttrib instance");     } }  [MyAttrib(Value = "SetOnClass")] class MyClass { }  class Program {     static void Main(string[] args)     {         Console.WriteLine("Getting attributes for MyClass.");         object[] a = typeof(MyClass).GetCustomAttributes(false);         ((MyAttribAttribute)a[0]).Value = "a1";          Console.WriteLine("Getting attributes for MyClass.");         a = typeof(MyClass).GetCustomAttributes(false);         Console.WriteLine(((MyAttribAttribute)a[0]).Value);          Console.ReadKey();     } } }   Now if I were to implement attributes, I would expect the output to be:  Created MyAttrib instance Getting attributes for MyClass. Getting attributes for MyClass. a1   Where the "class loader" (sorry, I have more of a Java background, not 100% sure how .net loads its types) would compile MyClass, and create an instance of MyAttribAttribute, and store them together somewhere. (probably the Perm Gen in the heap if this were Java) The 2 calls to GetCustomAttributes() would then just return the same earlier created instance.  But the actual output is:  Getting attributes for MyClass. Created MyAttrib instance Getting attributes for MyClass. Created MyAttrib instance SetOnClass   So... why? It seems like creating a new instance of all these objects for every call is a bit excessive, and not good for performance/memory management.  Is there any way to always get the same instance over and over?  Anyone have any ideas why it was designed this way?  The reason I care at all is because I made a custom attribute that internally holds some validation information, so in the Attribute I basically have a "private bool Validated" that I set to true. The validation stuff takes a while, so I don't want to run it every time. Now the problem is that since it creates a new instance of the attribute each time I get the attributes, Validated is always "false".
16158
Consider this example (typical in OOP books):    I have an Animal class, where each Animal can have many friends. And subclasses like Dog, Duck, Mouse etc which add specific behavior like bark(), quack() etc.  Here's the Animal class:  public class Animal {     private Map&lt;String,Animal&gt; friends = new HashMap&lt;&gt;();      public void addFriend(String name, Animal animal){         friends.put(name,animal);     }      public Animal callFriend(String name){         return friends.get(name);     } }   And here's some code snippet with lots of typecasting:  Mouse jerry = new Mouse(); jerry.addFriend("spike", new Dog()); jerry.addFriend("quacker", new Duck());  ((Dog) jerry.callFriend("spike")).bark(); ((Duck) jerry.callFriend("quacker")).quack();   Is there any way I can use generics for the return type to get rid of the typecasting, so that I can say      jerry.callFriend("spike").bark(); jerry.callFriend("quacker").quack();   Here's some initial code with return type conveyed to the method as a parameter that's never used.   public&lt;T extends Animal&gt; T callFriend(String name, T unusedTypeObj){     return (T)friends.get(name);         }   Is there a way to figure out the return type at runtime without the extra parameter using instanceof? Or at least by passing a class of the type instead of a dummy instance. I understand generics are for compile time type-checking, but is there a workaround for this?
4455
I have an array that is initialized like:  Element[] array = {new Element(1), new Element(2), new Element(3)};   I would like to convert this array into an object of the  class.  ArrayList&lt;Element&gt; arraylist = ???;
27673
I've been lately trying to learn more and generally test Java's serialization for both work and personal projects and I must say that the more I know about it, the less I like it. This may be caused by misinformation though so that's why I'm asking these two things from you all:  1: On byte level, how does serialization know how to match serialized values with some class?  One of my problems right here is that I made a small test with ArrayList containing values "one", "two", "three". After serialization the byte array took 78 bytes which seems awfully lot for such low amount of information(19+3+3+4 bytes). Granted there's bound to be some overhead but this leads to my second question:  2: Can serialization be considered a good method for persisting objects at all? Now obviously if I'd use some homemade XML format the persistence data would be something like this  &lt;object&gt;     &lt;class="java.util.ArrayList"&gt;     &lt;!-- Object array inside Arraylist is called elementData --&gt;     &lt;field name="elementData"&gt;         &lt;value&gt;One&lt;/value&gt;         &lt;value&gt;Two&lt;/value&gt;         &lt;value&gt;Three&lt;/value&gt;     &lt;/field&gt; &lt;/object&gt;   which, like XML in general, is a bit bloated and takes 138 bytes(without whitespaces, that is). The same in JSON could be   {     "java.util.ArrayList": {         "elementData": [             "one",             "two",             "three"         ]     } }   which is 75 bytes so already slightly  smaller than Java's serialization. With these text-based formats it's of course obvious that there has to be a way to represent your basic data as text, numbers or any combination of both.  So to recap, how does serialization work on byte/bit level, when it should be used and when it shouldn't be used and what are real benefits of serialization besides that it comes standard in Java?