Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I am learning about the ArrayList class in Java. I read in my textbook that ther

ID: 646401 • Letter: I

Question

I am learning about the ArrayList class in Java. I read in my textbook that there is a way to override the toString method but I cannot get the mini program I created to work:

    public static void main(String[] args) {
        ArrayList nameList = new ArrayList<>();
      
        nameList.add("Jose");
        nameList.add("Maria");
        nameList.add("Pepe");
        nameList.add("Teresa");

    @Override
    public String toString() {
            return String.format("The names in the ArrayList are: ", nameList);
        }
    for (String temp1 : nameList) {
        System.out.println(temp1);
    }

I am getting error messages in the toString part but I can't figure out what might be the problem and my textbook is not very clear in this topic. Please kindly tell me how to fix the above problem. If possible, please provide me with at least two more examples using an Integer and a String. Is it possible to incorporate inside the return String.format a (printf) as well? Thank you in advance for your assistance!

Explanation / Answer

import java.util.ArrayList;


class StringVal
{
private String sval;

StringVal(String s)
{
this.sval=s;
}

@Override

public String toString()
{
return "Value is:"+sval;
}
}

class IntVal
{
private int ival;

IntVal(int i)
{
this.ival=i;
}

@Override

public String toString()
{
return "Value is:"+ival;
}
}

class ArrayListDemo
{
public static void main(String args[])
{
ArrayList al=new ArrayList();
al.add(new StringVal("Joe"));
al.add(new StringVal("Ann"));
al.add(new StringVal("Rite"));
al.add(new StringVal("George"));

for(StringVal temp:al)
{
System.out.println(temp);
}

ArrayList al1=new ArrayList();
al1.add(new IntVal(1));
al1.add(new IntVal(2));
al1.add(new IntVal(3));
al1.add(new IntVal(4));

for(IntVal temp:al1)
{
System.out.println(temp);
}
}
}