简体   繁体   中英

Difference in passing an object to an arraylist (initializing once and more than once)

This is my main class MainClass and it has an arraylist MyList . I created an object for ExtractClass [not shown] extract and added it to my MyList. There is also another class PressClass [not shown]

public class MainClass {
  public static void main(String[] args) {

    ArrayList<ExtractClass> MyList = new ArrayList<ExtractClass>();

    ExtractClass Extract = new ExtractClass();

    MyList.add(Extract);
    MyList.add(Extract);

    PressClass Press = new PressClass(); 
    Press.pressMethod(MyList);
  }
}

Here is another version of the above program. I have initialized an object Extract and then added to MyList and i repeated it once more.

public class trailclass {
  public static void main(String[] args) {

    ArrayList<ExtractClass> MyList = new ArrayList<ExtractClass>();

    ExtractClass Extract;

    Extract = new ExtractClass();
    MyList.add(Extract);

    Extract = new ExtractClass();
    MyList.add(Extract);

    PressClass Press = new PressClass(); 
    Press.pressMethod(MyList);
  }
}

I got the same output for both programs. What is the difference between both? Does any of the above two codes breaks the rules of java? As a developer, which piece of code does one prefer?

It depends on what you try to achieve... In the first snippet you are adding the same ExtractClass instance twice to the list and in the second code snippet you are adding 2 different ExtractClass instances to the list. As I am not aware to the internals of your ExtractClass I can determine which of the codes is "right".

Simple answer is that you are creating two objects, one of which you don't need. The garbage collector wont destroy it however because it is in the ArrayList MyList so a reference to it is still reachable. In the first example the same object is being added to an ArrayList twice. In the second example, an object is made and added to to the ArrayList. After that, a new object is created and it too is added tot he ArrayList. The objects may have the same values (However you made your constructor) but the references are different.

If you want more explanation please ask.

The presented 2 solutions are not the same. The first adds the same object twice to the list while the second adds 2 different instances to the list.

Btw initializing a local variable in the same line is more compact and you should prefer that if it is a simple object creation:

ExtractClass Extract = new ExtractClass();

Also note that if you don't use the local variable, you can simply leave that out and add directly to the list:

MyList.add(new ExtractClass());

Also by convention you should start your variable names with lowercased letters and start your types (eg class name) with uppercased letter.

What is the difference between both?

Firt one creates one single object and add it twice to the list

In the second you create two different(1) objects and add each one once to the list, this is what actualy you will in most cases intend to do.

Does any of the above two codes breaks the rules of java?

Technically not. List allows the same object to appear more than one time in it. Semantically, it depends whether it is your intetion to have the same object more than one time in the list or not.

As a developer, which piece of code does one prefer?

In general you mean the have the second version.

(1) different depends on your implementation of hashCode and equals . The defaults from the base class Object just dows a reference check. So the different instances will not be equal and thus different. You can see the impact of this when you use the List#contains method. Depending on your implementation of the former methods and on which instance you pass to it you may get different results.

As per your current Implementation Both programs would work because you are adding object new ExtractClass() with default implemnentation in the list. First program adds same object twice while the second adds 2 different instances to the list.

If you have scenario where ExtarctClass constructor accepts some parameter lets say File destDir you will be left with second Option because you may have to provide different destDir for different objects

with said above your second program would look like below

public class trailclass {
  public static void main(String[] args) {

    ArrayList<ExtractClass> MyList = new ArrayList<ExtractClass>();

    ExtractClass Extract;

    Extract = new ExtractClass(new File("c:\temp"));
    MyList.add(Extract);

    Extract = new ExtractClass(new File("c:\temp"));
    MyList.add(Extract);

    PressClass Press = new PressClass(); 
    Press.pressMethod(MyList);
  }
}

This can further be written as below

public class trailclass {
  public static void main(String[] args) {
    ArrayList<ExtractClass> MyList = new ArrayList<ExtractClass>();
    MyList.add(new ExtractClass(new File("c:\temp")));
    MyList.add(new ExtractClass(new File("c:\temp")));

    PressClass Press = new PressClass(); 
    Press.pressMethod(MyList);
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM