AVW AVW - 1 month ago 14
Java Question

How do I return/implement the toString for the ArrayList? Also, just want to check that I've correctly created my objects?

import java.util.ArrayList;
import java.util.Date;
import javafx.scene.shape.Circle;

public class List2 {
public static void main(String[] args){
Loan newLoan = new Loan();
Date theDate = new java.util.Date();
Circle newCircle = new Circle();
String s = new String();
//last semicolon is also an error?

private ArrayList<Object> List = new ArrayList<Object>();

List.add(newLoan);
List.add(theDate);
List.add(newCircle);
List.add(s);

//**There's an error underlining all my . and ; when I add them to the List above?

public String toString() {
String results = "";
for (Object d : List) {
results += "," + d.toString();
}
}
}
//I'm pretty new to this stuff

Answer Source

You have a lot of error in your code :

First Don't ever name your variables with Upper letter in beginning, java use camelCase

Second Don't declare your variable with private public in your method.

private ArrayList<Object> List = new ArrayList<Object>();

Third You can't declare a method inside another method you have to close the first when you finish:

public static void main(String args[]){//------Start
  ...
}//---End

public String toString(){//---Start
  ...
}//---End

Forth When you want to call a method with paramettres you can pass them like this :

method(list);

Fifth ArrayList already impliment toString so you don't need to create it again, you can use :

list.toString()

If you want to implement it again you can use :

public static void main(String[] args) {
    King newLoan = new King();
    Date theDate = new java.util.Date();
    Circle newCircle = new Circle();
    String s = new String();

    ArrayList<Object> list = new ArrayList<Object>();

    list.add(newLoan);

    list.add(theDate);

    list.add(newCircle);

    list.add(s);

    System.out.println(newLoan.toString(list));
}

public String toString(ArrayList<Object> list) {
    String results = "";
    for (Object d : list) {
        results += "," + d.toString();
    }
    return results;
}