本文介绍了如何在Java中添加StringBuilder的反义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

与此相反的是:

savedPlanets.append(planet.getDisplayName()+",");

我有一个列表,每次用户点击复选框时我都会添加行星的名称,如果清除复选框,我想从savedPlanets中删除该名称

I have a list and I am adding the name of the planet every time the user clicks on a checkbox, I want to remove the name from the savedPlanets if the checkbox is cleared

推荐答案

您可以执行以下操作:

 savedPlanets.replace(planet.getDisplayName(),"");

理想情况下我会做以下解决方案:

Ideally I would do a solution like following:

Set<String> selectedPlanets = new HashSet<String>();

selectedPlanets.add(planet.getDisplayName());        // Whenever a planet is selected
selectedPlanets.remove(planet.getDisplayName());     // Whenever a planet is removed 

// Prepare a String with all planets        
StringBuilder savedPlanets = new StringBuilder("");
for(String planetName : selectedPlanets ){
    savedPlanets.append(planetName).append(",");
}
// Removing , from the end if any       
if(savedPlanets.toString().endsWith(","))
    finalValue = savedPlanets.substring(0, savedPlanets.length()-1);

// finalValue is what you are looking for

这篇关于如何在Java中添加StringBuilder的反义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 13:36