我试图插入字符串类型的键和LinkedList类型的值(它本身是Sprite类型)到TreeMap。然而,当我的代码调用put()方法时,它抛出一个空指针异常,我不知道为什么。
我的整个班都可以在这里找到。但为简洁起见,我将其缩小到以下问题部分。
这是我的Treemap声明(我使用Java 7,所以它喜欢菱形)
TreeMap<String, LinkedList<Sprite>> paneSprites = new TreeMap<>();
这是我的方法的一部分(其余的对其他精灵做同样的事情,注释掉这里的put()方法只是在后面的另一个put()方法中抛出另一个异常)。
public void initGUIControls()
{
canvas = new RambleOnPanel(this, (RambleOnDataModel)data);
LinkedList<Sprite> spriteList = new LinkedList<>();
//Sprite for Welcome Pane
SpriteType st = new SpriteType(settings.WELCOME_BACKGROUND_TYPE);
BufferedImage img = loadImage(settings.WELCOME_IMAGE_PATH);
st.addState(settings.DEFAULT_STATE, img);
st.addState(settings.INVISIBLE_STATE, img);
int x = 0;
int y = 0;
int vX = 0;
int vY = 0;
Sprite s = new Sprite(st,x,y,vX,vY, settings.DEFAULT_STATE);
spriteList.add(s);
guiButtons.put(st.getSpriteTypeID(), s);
//put sprite types for this pane in the hash map and clear the list
getPaneSprites().put(settings.WELCOME_PANE_TYPE, spriteList); //EXCEPTION THROWN HERE
spriteList.clear();
//Sprites for Select Account Pane
同样,这里使用的所有字符串都在另一个类中实例化,如下所示
package ramble_on;
public class Settings
{
//Game Settings
public final String APP_TITLE = "Ramble On!";
public final int FRAME_RATE = 30;
public final int GAME_HEIGHT = 700;
public final int GAME_WIDTH = 1200;
//Sprite States
public final String INVISIBLE_STATE = "INVISIBLE STATE";
public final String DEFAULT_STATE = "DEFAULT STATE";
//Pane Types
public final String WELCOME_PANE_TYPE = "WELCOME PANE TYPE";
public final String SELECT_ACCOUNT_PANE_TYPE = "SELECT ACCOUNT PANE TYPE";
public final String CURRENT_ACCOUNT_PANE_TYPE = "CUTTENT ACCOUNT PANE TYPE";
//Sprite Types
public final String WELCOME_BACKGROUND_TYPE = "WELCOME BACKGROUND TYPE";
public final String SELECT_ACCOUNT_BACKGROUND_TYPE = "SELECT ACCOUNT TYPE";
public final String NEW_USER_BUTTON_TYPE = "NEW USER BUTTON TYPE";
public final String CURRENT_ACCOUNT_BACKGROUND_TYPE = "CURRENT ACCOUNT BACKGROUND TYPE";
public final String LARGE_RETURN_BUTTON_TYPE = "LARGE RETURN BUTTON TYPE";
//Sprite Image paths
public final String IMAGES_PATH = "./data/images/";
public final String WELCOME_IMAGE_PATH = IMAGES_PATH + "welcome.png";
public final String SELECT_ACCOUNT_BACKGROUND_IMAGE_PATH = IMAGES_PATH + "selectAccount.png";
public final String NEW_USER_BUTTON_PATH = IMAGES_PATH + "newUser.png";
public final String Current_Account_SCREEN_BACKGROUND_IMAGE_PATH = IMAGES_PATH + "currentAccount.png";
public final String LARGE_RETURN_BUTTON_IMAGE_PATH = IMAGES_PATH + "newUser.png";
}
在
行中有两个nullpointerexception选项getPaneSprites () .put(设置。WELCOME_PANE_TYPE spriteList);
- getPaneSprited()返回null
- 设置。WELCOME_PANE_TYPE为null
要查看它是否为1,您可以将get调用和put调用拆分为两个不同的行。然后调试getter是否返回null。
Treemap键不能为空,所以也可以是这样。它与泛型无关,因为一旦编译后,由于类型擦除,泛型无论如何都会消失。