代码之家  ›  专栏  ›  技术社区  ›  Organiccat

GWT中的泛型和集合,空指针

  •  1
  • Organiccat  · 技术社区  · 17 年前

    在GWT中调用向集合添加对象的方法时,我得到一个空指针错误。我不知道为什么,因为我所做的一切都创建了一个非常简单的对象(只包含一个字符串)。以下是调用函数和函数的代码:

    public class PlantMenu extends VerticalPanel {
    
        private Collection<PlantData> plantList;
        private Collection<PlantData> newPlantData;
    
        public PlantMenu() {
            createPlants();
            /*
            for(Iterator<PlantData> i = plantList.iterator(); i.hasNext();) {
                Window.alert(i.next().getPlantName());
            }*/
        }
    
        public Collection<PlantData> createPlants() {
            PlantData plant1 = new PlantData("Herbs");
            PlantData plant2 = new PlantData("Flowers");
            PlantData plant3 = new PlantData("Vegetable");
    
            newPlantData.add(plant1);
            newPlantData.add(plant2);
            newPlantData.add(plant3);
            return newPlantData;
        }
    
    }
    

    尝试添加第一个工厂时出错(空指针),此行:

    PlantData plant1=新的PlantData(“草药”);

    感谢您的帮助:)

    2 回复  |  直到 17 年前
        1
  •  5
  •   Adeel Ansari    17 年前

    您没有初始化集合。尽管如此,你已经告诉我它不在那条线上,但我怀疑。不过,显示完整的异常堆栈会更有帮助。异常可能发生在PlantData构造函数中,但您没有在此处显示它。

    你可以这样做,

    private Collection<PlantData> plantList = new ArrayList<PlantData>();
    private Collection<PlantData> newPlantData = new ArrayList<PlantData>();
    

    我使用了ArrayList,因为通常我们使用ArrayList。根据需要,也可以使用其他实现。

        2
  •  0
  •   rustyshelf    17 年前

    public class PlantMenu extends VerticalPanel {
    
        private List<PlantData> plantList = new ArrayList<PlantData>();
        private List<PlantData> newPlantData = new ArrayList<PlantData>();
    
        public PlantMenu() {
            createPlants();
            for(PlantData plant : newPlantData) {
                    Window.alert(plant.getPlantName());
            }
        }
    
        public List<PlantData> createPlants() {
            newPlantData.add(new PlantData("Herbs"));
            newPlantData.add(new PlantData("Flowers"));
            newPlantData.add(new PlantData("Vegetable"));
            return newPlantData;
        }
    
    }