Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

declaring ArrayList in java Constructor

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
like image 501
demuro1 Avatar asked Dec 12 '22 06:12

demuro1


1 Answers

Change

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

to

list = new ArrayList<String>();
like image 73
casperw Avatar answered Dec 24 '22 01:12

casperw