John Diego
John Diego

Reputation: 1

Getting issue in adding data to List

I have two classes namely Test and Demo and in Demo class I have a class variable namely List. I somehow need to put/add the given two strings into List but it will only accept objects of Test class. Is there a way I can add the given strings to List.

class Test{

List<Test> getdataFromDemo(){
   return Demo.getData;
  }
}

class Demo{

public static List<Test> getData=new LinkedList<Test>;

static void D1(){
String str1="TestOne";
String str2="TestTwo";
}

getData.add(str1);//need to add str to getData but this is showing error
getData.add(str2);
System.out.println(getData)

Upvotes: 0

Views: 65

Answers (2)

etienneZink
etienneZink

Reputation: 54

You are trying to store a String in your generic list of Test. You need to create an attribute in Test of the type String and set it within the constructor. Then you need to add the new objects of Test with the Strings str1 and str2 in the constructor to the list.

public class Test {

    public String name;

    Test(String name) {
        this.name = name;
    }

    List < Test > getdataFromDemo() {
        return Demo.getData;
    }
}

class Demo {

    public static List < Test > getData = new LinkedList < Test > ();

    public static void main(String[] args) {
        String str1 = "TestOne";
        String str2 = "TestTwo";
        getData.add(new Test(str1)); // need to add str to getData but this is showing error
        getData.add(new Test(str2));
        System.out.println(getData);
    }
}

Upvotes: 1

QuickSilver
QuickSilver

Reputation: 4045

Add a field variable in test class of string and initialize its in constructor. or just set the string directly using setters and fetch it using getters.

class Test{
public String testString;
public void setTestString() {
  this.testString=testString;
}

public String getTestString() {
  return this.testString;
}

List<Test> getdataFromDemo(){
   return Demo.getData;
  }
}

class Demo{

public static List<Test> getData=new LinkedList<Test>;

static void D1(){
String str1="TestOne";
String str2="TestTwo";
}
Test test1 =  new Test()
test1.setTestString( str1);
getData.add( test1);//need to add str to getData but this is showing error
Test test2 =  new Test()
test2.setTestString(  str2);
getData.add(test2);
System.out.println(getData)

Upvotes: 0

Related Questions