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
Change
List<String> list = new ArrayList<String>();
to
list = new ArrayList<String>();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With