开发者

Java - ArrayList of Modules - how do I

list all modules in the ArraryList? -

I thought it'd be something like below but this won't compile (error - cannot find symbol - method list).

/**
 * This method lists all modules in the ArrayList
 */
public String listAllModules()
{
    return modules.list();
}

Thanks. (new to Java in case that isn't obvious.开发者_如何转开发.)


The method list() isn't available for ArrayList. Use a for loop instead:

for (Module m: modules) {
   System.out.println(m);
}

Assuming that the ArrayList modules has objects with the type of Module


For a String List of your List Elements you can override the toString Method to fit your needs.

and then like

public String listAllModules()
{
    return modules.toString();
}


Do you just need to iterate through a List? Try this:

for (Object o : modules) {
    // do something with each object from the list
}

Hard to understand what you're trying to do without more information.


Depending on what you have, you might want to try out the toString() method. If you want something more customizable, you can do something like this:

public String listAllModules()
{
   StringBuilder str = new StringBuilder();
   for (int i = 0; i < modules.size(); i++)
   {
     str.append(modules.get(i));  // you can append any other data here
   }

   return str.toString();
}

You can take a look at the ArrayList api or more information. In the above code, I am assuming that ArrayList modules is an arraylist of strings, ie: ArrayList modules.


I am unclear about the type of 'modules' variable. If it is array then you can simply use, Arrays.asList(modules);

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜