0

I have created ArrayList and make setter and getter for it. In the other class i want to add objects in this array. But my code doesn't works. i think i need to add in method setter for array some other code..

public class DataVar {

private ArrayList<String> arrayLinks = new ArrayList<>();  

public ArrayList<String> getArrayLinks() {
        return arrayLinks;
    }

    public void setArrayLinks(ArrayList<String> arrayLinks) {
        this.arrayLinks = arrayLinks;
    }
}

//Here is another class

public class LinksAd {

public void getAllLinksAd() {

DataVar dataVar = new DataVar();
 String link = "href";
 dataVar.setArrayLinks(link) }}
1
  • 2
    what does not work. please more details. Commented Nov 16, 2015 at 11:20

3 Answers 3

4

Looking at your code you are trying to add a String type, where your code specifies that you are expecting an ArrayList. Assuming you just want to add a string to your arraylist the following will work:

 public void setArrayLinks(String arrayLinks) {
    this.arrayLinks.add(arrayLinks);
}
Sign up to request clarification or add additional context in comments.

1 Comment

@J.Doe Please rename this method to addToArrayLinks or something similar, because this isn't a setter.
0

You can implement generic setter method.

This is DataVar class:

public class DataVar {
    private List<String> itemList=new ArrayList<String>();

    public List<String> getItemlist() {
        return itemList;
    }

    public void setItemList(Object list) {
        if (list.getClass().equals(String.class)) {
            itemList.add((String)list);
        }
        else if (list.getClass().equals(ArrayList.class)) {
            itemList = (ArrayList<String>)list;
        }
        else {
            throw new Exception("Rejected type- You can set String or ArrayList");
        }
    }
}

And this is calling setter method example:

Main class:

public static void main(String[] args) {
    List<String> exampleList = new ArrayList<String>();
    exampleList.add("This example");
    exampleList.add("belongs to");

    String owner = "http://www.javawebservice.com";

    DataVar dataVar = new DataVar();
    dataVar.setItemList(exampleList);
    dataVar.setItemList(owner);

    for(String str:dataVar.getItemlist()){
        System.out.println(str);
    }
}

Output:

This example  
belongs to  
http://www.javawebservice.com

So, you can set ArrayList, also you can set String.

Comments

0

You could do a mehtod to add an Item like this:

public void addStringToList(String s)
{
   arrayLinks.add(s); 
}

In LinksAd you have to wirte:

dataVar.addStringToList(link);

Comments

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.