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 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).
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.
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>();
}
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
java offers you also an Initializing Fields
http://docs.oracle.com/javase/tutorial/java/javaOO/initial.html see Initializing Instance Members
Related
Basically, when I passed arguments in Java, I knew it was passing only value.
However, the following code shows that the add method executed on SubClass's SubMethod affects ArrayList of MainClass.
MainClass.java
public class MainClass{
public satatic void main(String[] args){
List list = new ArrayList<>();
SubClass subClass = new SubClass(list);
subClass.subMethod();
System.out.println(list) // Why added value???
}
}
SubClass.java
public class SubClass{
private List list;
public SubClass(List list){
this.list = list;
}
public void subMethod(){
list.add(1);
list.add(2);
}
}
When I did the same thing with a HashMap's put, there was no effect on the HashMap of the MainClass.
I would like to know why only ArrayList is causing these results and what is happening inside Java.
Update
The code for the hashmap version is as follows:
MainClass.java
public class MainClass{
public satatic void main(String[] args){
Map map = new HashMap<>();
SubClass subClass = new SubClass(map );
subClass.subMethod();
System.out.println(map) // Not putting value
}
}
SubClass.java
public class SubClass{
private Map map;
public SubClass(Map map){
this.map= map;
}
public void subMethod(){
map = someGenerationHashMap(arg1, arg2);
}
}
It's not about ArrayList. Any object you pass as an argument can be modified. What is passed by value is the address of the object, not the object itself.
In the Map version, you are not making any operation that could modify it. In the list version instead, you are making an add.
Make sure not to confuse objects with primitives. For example, make sure not to confuse int with Integer.
I am trying to up create and update an ArrayList by passing an argument, so that I will end up with a list of say 10 names; however, the current function doesn't seem to be working - any ideas pls?
public String addClient(String name) {
ArrayList<String> myList = new ArrayList<String>();
myList.add(name);
return myList;
}
You are creating a new ArrayList every time you call it. This means that every time you call this method you create a brand new Collection and only store the one client in it. You need to keep a reference of a single collection around and keep adding to that. You can do that by passing in the array you want to add it to:
public List<String> addClient(String name, List<String> array) {
array.add(name);
return array;
}
This doesn't seem like a useful function, so I'm guessing this is within a class. So this might be the approach you want:
/**
* Class is not Thread Safe
*/
public class ClientList {
private final ArrayList<string> clients;
public ClientList() {
this.clients = new ArrayList<>();
}
public void addClient(String client) {
this.clients.add(client);
}
public List<String> getClients() {
// Note: Never give a reference to the internal objects of the class
// as that means someone outside this class can own a reference to it
// and can update the object without you knowing (by not going
// through this class)
Collections.unmodifiableList(this.clients);
}
}
This is what you need to do:
ArrayList<String> myList = new ArrayList<String>();
public void addClient(String name) {
myList.add(name);
}
If you create a list inside the method, it will only have one value, and will go away once method execution finishes (unless it's returned). Have a look at different scopes here. You should create a list at a class level and add the elements into it.
Also, method does not need to return anything, so it's better to change the type to void.
The problem with your approach is that everytime you call the method addClient a new ArrayList will be created.
I think this will work for you :
static ArrayList<String> myList;
public static void main(String[] args) {
myList = new ArrayList<>();
}
public void addClient(String name){
myList.add(name);
}
I want to add everything from ArrayList in class Taster in another ArrayList in class Tastatura. It's calling no suitable method error and I don't really know what to do and how to do it . I would be really thankfull if someone quickly explained me how this work and write my code correctly.
This is main class:
public class Tastatura {
public static void main(String[] args) {
Taster slovo = new Taster();
ArrayList<String> collection1 = new ArrayList<String>();
collection1.addAll(slovo); //<--- error here
}
}
another class:
public class Taster {
public Taster(){
ArrayList<String> Slova = new ArrayList<String>();
Slova.add("q");
Slova.add("w"); }}
The problem is by collection1.addAll(slovo); you are adding an object to a collection.
The addAll method requires a Collection as argument.
You class should look like this :
public class Taster {
private ArrayList<String> Slova;
public Taster() {
Slova = new ArrayList<String>();
Slova.add("q");
Slova.add("w");
}
public ArrayList<String> getList() {
return Slova;
}
}
And in you main method :
collection1.addAll(slovo.getList());
OR
You don't need to change the Taster class :
Just change your addAll to :
collection1.addAll(slovo.Slova);
try this :
collection1.addAll(slovo.Slova) ;
and change your Taster class to this :
public class Taster {
public ArrayList<String> Slova = new ArrayList<String>();
public Taster(){
Slova.add("q");
Slova.add("w");
}
}
You are trying to add class Taster into method, which expects String or something like that (ArrayList<String> in this case)
:)
Nafas code should work..
Other way is to write your own "add" method in your Taster class (which takes actual ArrayList and adds in it every item from ArrayList given in param, and returns that result)
It is necessary to change a container type:
import java.util.*;
public class MyContainers {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("title1");
list.add("title2");
System.out.println(list.indexOf("title1"));
// change container type
Set<String> set = new HashSet<String>(list);
}
}
But it will be better to use only one variable. I wrote such code but there was a restriction (see comment):
import java.util.*;
public class MyContainers {
public static void main(String[] args) {
Collection<String> list = new ArrayList<String>();
list.add("title1");
list.add("title1");
System.out.println(list);
// Can't call indexOf because there are no such method in inteface Collection
//System.out.println(list.indexOf("title1"));
// change container type
list = new HashSet<String>(list);
System.out.println(list);
}
}
Please, help me with such questions:
Is it possible to use one variable for different containers and use full set of containers methods?
Is it possible to convert List to Map?
Please, show a code examples.
If some method doesn't exist in one interface, it doesn't exist for a reason. Don't try to have a workaround in order to have it, that'll usually lead to troubles. For example, it doesn't make any sense to have indexOf method for the Set interface.
However, it can be useful sometimes to construct a new object of different type from an existing one, for example, if you have an ArrayList and you don't want to have duplicates, it does make sense to convert it to HashSet.
You should pick the best interface that suits your needs, if you don't find any, you can always implement your own class.
I found the solution, is it good?
import java.util.*;
public class MyContainers {
static Collection<String> collection = new ArrayList<String>();
public static void main(String[] args) {
collection.add("title1");
collection.add("title1");
System.out.println(collection); // [title1, title1]
useIndexOf();
System.out.println(collection); // [title1, title1]
deleteDublication();
System.out.println(collection); // [title1]
}
public static void useIndexOf()
{
List<String> list = new ArrayList<String>(collection);
System.out.println(list.indexOf("title1")); // 0
// Change container type back to universal
collection = list;
}
public static void deleteDublication() {
Set<String> set = new HashSet<String>(collection);
collection = set;
}
}
I have a class that implements getter and setter methods and related code as follows.
ArrayList<String> viewArray = new ArrayList<String>();
public ArrayList<String> getView() {
return viewArray;
}
from my activity, I am trying to get acces to stored array like:
ArrayList<String> al = new ArrayList<String>();
al = parsedExampleDataSet.getView();
But "al" receives no data. However, when getView() is executed, viewArray is filled properly. What am I missing? Thank you.
Others have make some good comments but I thought I'd take you through the code as I see it.
public class SomeClass {
// this is local to this class only
ArrayList<String> viewArray = new ArrayList<String>();
public void process() {
// i'm guessing there is some sort of processing method that is called
}
public ArrayList<String> getView() {
return viewArray;
}
}
Here's your activity class annotated with some details about the value of a1:
public class YourActivity {
ArrayList<String> al = new ArrayList<String>();
public void someMethod() {
// here a1 will be the same blank List you initialized it with
// unless someMethod() has been called before or a1 modified elsewhere
al = parsedExampleDataSet.getView();
// after the call to getView, a1 is now a reference to SomeClass.viewArray
// the ArrayList that a1 was initialized with is then garbage collected
}
}
Please edit your question to explain more what you are having problems with.