Question

When Im writing the result into a TextView It show me like this:

ChampionList[[[Annie],[Blitzcrank],[Cassiopeia],[Corki],[Lucian]]]

I dont know how to dont show the array " [] ".Can Anyone help me please?

Thats the code:

import java.util.ArrayList;


public class ChampionList {

    private ArrayList<Champion> champions;

    public ArrayList<Champion> getChampions() {
        return champions;
    }

    @Override
    public String toString() {


        return "ChampionList [" + champions + "]";

    }

    public void setChampions(ArrayList<Champion> champions) {
        this.champions = champions;
    }



}

Champion class:

package src.jriot.objects;

public class Champion {


    private String name;


    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    @Override
    public String toString() {

        return "[" + name + "]";
    }

Thank you!

Was it helpful?

Solution

Try something like this:

@Override
public String toString() {

   StringBuilder sb = new StringBuilder();
   for (Iterator<Champion> iterator = champions.iterator(); iterator.hasNext();) {
       Champion champion = (Champion) iterator.next();
       sb.append(champion.toString() + ",");

}
String result = sb.toString();
return result.substring(0,result.length()-1);


}

You may also need to override the toString function in your Champion class.

Assuming Champion class looks like this:

public class Champion {
    private String championName;
    //The Tostring() method can look like this
    @Override
    public String toString() {
        return championName;
    }

}

OTHER TIPS

You need to override the toString() method to create your own presentable output which will iterate through your arraylist and adding the elements to a string. Like so:

String championsList = "";

for(int i = 0; i< champions.size(); i++)
{
    championsList += championsList.get(i) + ", ";
}

System.out.println(championsList);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top