7

I am working on a project, and I was taught to instantiate variables in constructors. I'm having some trouble doing this with an ArrayList thought. Can you suggest some best practices, do I need to define the ArrayList with the instance variables or can I do it in the constructor. Thanks for your suggestions! I have an example of what I'm talking about below:

//imports
import java.util.*;
import java.lang.*;

public class ArrayListConstructorDemo
{
//instance variables/attributes

String string;
List<String> list;// for example does this line need to say List<String> list = new ArrayList<String>();

//constructors
public ArrayListConstructorDemo()
{
    String string = "null";
    List<String> list = new ArrayList<String>();//is there anyway I can do this here instead of 6 lines up?
}//end default constructor
public ArrayListConstructorDemo(String string,List<String> list)
{
    this.string = string;
    this.list = list;
}//end generic constructor

//observers/getters/accessors
 public String getString(){return string;}//end method getString()
 public List<String> getList(){return list;}//end method getList()

//transformers/setters/mutators
     public void setTable(String string){this.string = string;}
     public void setValues(String list)
     {

    //  for(String s : test) 
    //  {
            list.add(this.list);
    //  }
     }
public String toString()
{
    return "this is a generic toString method for the class ArrayListConstructorDemo";
}//end toString

public static void main(String[] args)  
{
    ArrayListConstructorDemo alcd = new ArrayListConstructorDemo();
    System.out.println(alcd.list.size());

//test Lists in general
    List<String> bleh = new ArrayList<String>();
    bleh.add("b1");
    System.out.println(bleh.get(0));
}//end method main()
}//end class ArrayListConstructorDemo
4
  • 1
    Don't confuse declaration and initialization. Also careful that you don't shadow the variable. (Those are all keywords.) Commented Mar 29, 2014 at 19:56
  • Why are you re-declaring the variables in constructor? Commented Mar 29, 2014 at 19:56
  • Sotiros I just did that for brevities sake. You're totally right and in practice I don't! Rohit I was taught that in a default constructor anything that needs to have a value to be accessed later should be instantiated in the default constructor instead of adding default values before that, this prevents you from having issues later on with random values floating around. Commented Mar 29, 2014 at 20:02
  • Rohit is referring to a concept called shadowing. If you have a field declared with the name list and then declare a new variable called list within the constructor, when referring to list within the constructor, you'll be referring to the local variable rather than the field. Commented Mar 29, 2014 at 20:03

6 Answers 6

5

Change

List<String> list = new ArrayList<String>();

to

list = new ArrayList<String>();
Sign up to request clarification or add additional context in comments.

Comments

5

If you want to just declare it in the constructor you can have the code:

     ArrayList<String> name = new ArrayList<String>();

Otherwise you can declare it as a field, and then initialize it in the constructor.

   private ArrayList<String> name;

And then in the constructor:

    name = new ArrayList<String>();

Making it a field would be useful, as you would then be able to create accessor/mutator methods in order to retrieve and use the List from different classes, without having to declare it public (which is rarely a good thing).

Comments

2

If you want to declare it in the constructor, then you (most likely) want to declare the outer field, so you want:

list = new ArrayList<String>();

Currently you are shadowing the List<String> list class variable, meaning that you are creating a new instance of list, rather than that you are initializing the list instance variable.

I personally prefer initializing it at declaration time though, so what you previously had. I prefer this to make the code more concise and you most likely won't end up forgetting to initialize it if you teach yourself that habbit.

Comments

2

Generally the practice is to declare before the constructor, and initialize in the constructor. Here's an example:
class myClass ArrayList<String> strings public myClass() { strings=new ArrayList<String>(); }

Comments

2

How can you do this ??

public void setValues(String list) {

    // for(String s : test)
    // {
    list.add(this.list);
    // }
}

There is no method like add() to manipulate Strings, Instead you would have done this :

public void setValues(List<String> list) {

    // for(String s : test)
    // {
    list.add(this.list);
    // }
}

And regarding declaring ArrayList in the constructors you can do like this :

String string;
List<String> list;// for example does this line need to say List<String>
                    // list = new ArrayList<String>();

// constructors
public ArrayListConstructorDemo() {
    string = "null";
    list = new ArrayList<String>();// is there anyway I can do this here
                                    // instead of 6 lines up?
}// end default constructor

2 Comments

That method isn't finished, It will eventually be something like public void setValues(List<String> list, String... strings) { for(String s : strings){ list.add(this.s); } } or something like that
ya... that sounds ok now !! and btw, using variable names as of the predefined keywords is bad practice !
0

java offers you also an Initializing Fields

http://docs.oracle.com/javase/tutorial/java/javaOO/initial.html see Initializing Instance Members

1 Comment

where did it mention java prefers to initializing the list as a field?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.