如何存储在一个ArrayList自定义对象 [英] How to store custom objects in an ArrayList

查看:232
本文介绍了如何存储在一个ArrayList自定义对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在做一个游戏卡,字符卡。

我第一次创建用户所选择的卡,然后将它们添加到列表,洗牌,然后显示'时间一个接一个,用他们的球员的名字(选择在由用户previous活性)。

而事实是,当我尝试从列表中得到一卡类,并调用它的方法getPlayer()及getCharacter(这回玩家的名字和具体卡的人物的名字)我得到空指针异常。

 显示java.lang.NullPointerException:尝试对空对象引用调用虚拟方法java.lang.String中com.example.leonardo.lupusintabula.characters.Card.getCharacter()randomButton.setText(characters.get(0).getCharacter()+/+ characters.get(0).getPlayer());

总的onCreate():

  @覆盖
保护无效的onCreate(捆绑savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.activity_random_assignment);    //检索
      ...
    //完成检索
    initializeVariables();
    createCharacters();
    跑();
}

由于这个问题可能是人物,我列出你所有的code它在:

  //当字符存储
私人的ArrayList<卡>字符;
公共无效initDeck(){
    addCharacter(邪恶的,demoniacAmount,字符);
    addCharacter(后卫,guardAmount,字符);
    addCharacter(中,mediumAmount,字符);
    addCharacter(mythomaniac,mythomaniacAmount,字符);
    addCharacter(猫头鹰,owlAmount,字符);
    addCharacter(werehamster,werehamsterAmount,字符);
    addCharacter(getVillagerBundle(),villagerAmount,字符);
    addCharacter(masonOne,1个字符);
    addCharacter(masonTwo,1个字符);
}公共无效addCharacter(卡牌,INT量,列表与LT;卡>卡){
    如果(度< 0){
        抛出新抛出:IllegalArgumentException(必须添加字符的非负数+ card.getCharacter());
    }    的for(int i = 0; I<金额;我++){
        cards.add(卡);
    }
}//选择一个随机的,并显示它
公共无效拾(查看视图){
    如果(字符!= NULL){
        如果(ⅰ&下; characters.size()){
            randomButton.setText(characters.get(ⅰ).getCharacter()+/+ characters.get(ⅰ).getPlayer());
            我++;
        }其他{
            randomButton.setText(R.string.play);
        }
    }
}无效的run(){
    //初始化字符
    initDeck();    //他们洗牌
    Collections.shuffle(字);    //显示1号卡
    如果(字符!= NULL){
        randomButton.setText(characters.get(0).getCharacter()+/+ characters.get(0).getPlayer());
    }
}
私人无效initializeVariables(){
    ...
    ...    字符=新的ArrayList<卡>();
 }

}

我是什么做错了吗?如果您需要code的另一部分随时问,我会尽快提供给你越好!

这可能会推动你疯了,但它是我发现,实现了人物的创建(每个字符扩展卡类!)的唯一方法:

 公共无效createCharacters(){
    如果(demoniacAmount!= 0){
        着魔=新的恶魔(nameList.get(列表索引));
        列表索引++;
    }如果别人(guardAmount!= 0){
        后卫=新卫士(nameList.get(列表索引));
        列表索引++;
    }否则如果(mediumAmount!= 0){
        中等=新媒体(nameList.get(列表索引));
        列表索引++;
    }如果别人(mythomaniacAmount!= 0){
        mythomaniac =新Mythomaniac(nameList.get(列表索引));
        列表索引++;
    }否则如果(owlAmount!= 0){
        猫头鹰=新的猫头鹰(nameList.get(列表索引));
        列表索引++;
    }否则如果(werehamsterAmount!= 0){
        werehamster =新Werehamster(nameList.get(列表索引));
        列表索引++;
    }否则如果(masonsAmount!= 0){
        masonOne =新的梅森(nameList.get(列表索引));
        masonTwo =新的梅森(nameList.get(列表索引));
        列表索引+ = masonsAmount;
    }否则如果(villagerAmount→5){
            villagerSix =新村民(nameList.get(列表索引));
            villagerBundle.add(villagerSix);            如果(villagerAmount→6){
                villagerSeven =新村民(nameList.get(列表索引));
                villagerBundle.add(villagerSeven);                如果(villagerAmount大于7){
                    villagerEight =新村民(nameList.get(列表索引));
                    villagerBundle.add(villagerEight);                    如果(villagerAmount→8){
                        villagerNine =新村民(nameList.get(列表索引));
                        villagerBundle.add(villagerNine);                        如果(villagerAmount> 9){
                            villagerTen =新村民(nameList.get(列表索引));
                            villagerBundle.add(villagerTen);                            如果(villagerAmount→10){
                                villagerEleven =新村民(nameList.get(列表索引));
                                villagerBundle.add(villagerEleven);                                如果(villagerAmount> 11){
                                    villagerTwelve =新村民(nameList.get(列表索引));
                                    villagerBundle.add(villagerTwelve);                                    Toast.makeText(RandomAssignment.this,工程,Toast.LENGTH_SHORT).show();
                                }
                            }
                        }
                    }
                }
            }
        }
        列表索引+ = villagerAmount;
    }


解决方案

从我的其他答案,从中你了我的code。在 initDeck 方法实际上读这样的

 公共无效initDeck(){
    如果(字符== NULL)
        字符=新的ArrayList<串GT;();        // addCharacter ...

这至少会避免列表上的空指针...


您需要更多code添加到您的问题,但这个问题在此块启动

  addCharacter(邪恶的,demoniacAmount,字符);
addCharacter(后卫,guardAmount,字符);
addCharacter(中,mediumAmount,字符);
addCharacter(mythomaniac,mythomaniacAmount,字符);
addCharacter(猫头鹰,owlAmount,字符);
addCharacter(werehamster,werehamsterAmount,字符);
addCharacter(getVillagerBundle(),villagerAmount,字符);
addCharacter(masonOne,1个字符);
addCharacter(masonTwo,1个字符);

这(大约)称此code

 公共无效addCharacter(卡牌,INT量,列表与LT;卡>卡){
    的for(int i = 0; I<金额;我++){
        cards.add(卡);
    }
}

问题是,地方这些变量是空的,它们被添加到列表中这样


  • 着魔

  • 后卫


  • mythomaniac

  • 猫头鹰

  • werehamster

  • getVillagerBundle()

  • masonOne

  • masonTwo


您既可以解决这个问题通过给所有这些变量在新卡(),或避免像这样的问题。

 公共无效addCharacter(卡牌,INT量,列表与LT;卡>卡){
    的for(int i = 0; I<金额;我++){
        如果(卡!= NULL){
            cards.add(卡);
        }其他{
            Log.e(addCharacter,嘿,你确定你的意思是添加一个空卡吗?);
        }
    }
}


现在你表现出更多code的,误差在这里开始

 如果(demoniacAmount!= 0){
    着魔=新的恶魔(nameList.get(列表索引));
    列表索引++;
}如果别人(guardAmount!= 0){
    后卫=新卫士(nameList.get(列表索引));
    列表索引++;
}

如果 demoniacAmount guardAmount 都是不为零,嗯?只有第一个if条件将被输入。和后卫最终会被空,因为它从来没有初始化。这是没有意义做了一个否则,如果的完全不同的变量!

正常执行用户如果检查像这样所有这些条件。 (我会离开这个混乱的code,也同样困扰着我)

 如果(demoniacAmount!= 0){
    着魔=新的恶魔(nameList.get(列表索引));
    列表索引++;
}如果(guardAmount!= 0){
    后卫=新卫士(nameList.get(列表索引));
    列表索引++;
}

I'm making a game with cards, characters cards.

I first create the cards chosen by the user, then add them to a List, shuffle it and then display 'em one by one, with their players name (chosen in a previous activity by the user).

The fact is, when I try to get the a Card class from the List, and invoking its methods getPlayer() & getCharacter (which return the player's name and the characters' name of the specific card) I get the nullPointer Exception.

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.leonardo.lupusintabula.characters.Card.getCharacter()' on a null object reference

randomButton.setText(characters.get(0).getCharacter() + " / " + characters.get(0).getPlayer());

The onCreate():

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_random_assignment);

    //Retrieving
      ...
    //Done retrieving
    initializeVariables();
    createCharacters();
    run();
}

As the issue is probably in characters, I'm listing you all the code it's in:

// Where the characters are stored
private ArrayList<Card> characters;


public void initDeck() {
    addCharacter(demoniac, demoniacAmount, characters);
    addCharacter(guard, guardAmount, characters);
    addCharacter(medium, mediumAmount, characters);
    addCharacter(mythomaniac, mythomaniacAmount, characters);
    addCharacter(owl, owlAmount, characters);
    addCharacter(werehamster, werehamsterAmount, characters);
    addCharacter(getVillagerBundle(), villagerAmount, characters);
    addCharacter(masonOne, 1, characters);
    addCharacter(masonTwo, 1, characters);
}

public void addCharacter(Card card, int amount, List<Card> cards) {
    if (amount < 0) {
        throw new IllegalArgumentException("Must add a non-negative number of characters for " + card.getCharacter() );
    }

    for (int i = 0; i < amount; i++) {
        cards.add(card);
    }
}



//Pick a random one and display it
public void pick(View view){
    if(characters != null) {
        if (i < characters.size()) {
            randomButton.setText(characters.get(i).getCharacter() + " / " + characters.get(i).getPlayer());
            i++;
        } else {
            randomButton.setText(R.string.play);
        }
    }
}

void run() {
    // initialize the characters
    initDeck();

    // shuffle them
    Collections.shuffle(characters);

    //Display the 1st card
    if(characters != null) {
        randomButton.setText(characters.get(0).getCharacter() + " / " + characters.get(0).getPlayer());
    }
}


private void initializeVariables() {
    ...
    ...

    characters = new ArrayList<Card>();
 }

}

What am I doing wrong? If you need other part of the code feel free to ask, I'll provide it to you as soon as possible!

This may drive you crazy but it's the only way I found to achieve the creation of the characters (each character extends the Card class!):

public void createCharacters() {
    if (demoniacAmount != 0) {
        demoniac = new Demoniac(nameList.get(listIndex));
        listIndex++;
    } else if (guardAmount != 0) {
        guard = new Guard(nameList.get(listIndex));
        listIndex++;
    } else if (mediumAmount != 0) {
        medium = new Medium(nameList.get(listIndex));
        listIndex++;
    } else if (mythomaniacAmount != 0) {
        mythomaniac = new Mythomaniac(nameList.get(listIndex));
        listIndex++;
    } else if (owlAmount != 0) {
        owl = new Owl(nameList.get(listIndex));
        listIndex++;
    } else if (werehamsterAmount != 0) {
        werehamster = new Werehamster(nameList.get(listIndex));
        listIndex++;
    } else if (masonsAmount != 0) {
        masonOne = new Masons(nameList.get(listIndex));
        masonTwo = new Masons(nameList.get(listIndex));
        listIndex += masonsAmount;
    } else if (villagerAmount > 5) {
            villagerSix = new Villager(nameList.get(listIndex));
            villagerBundle.add(villagerSix);

            if (villagerAmount > 6) {
                villagerSeven = new Villager(nameList.get(listIndex));
                villagerBundle.add(villagerSeven);

                if (villagerAmount > 7) {
                    villagerEight = new Villager(nameList.get(listIndex));
                    villagerBundle.add(villagerEight);

                    if (villagerAmount > 8) {
                        villagerNine = new Villager(nameList.get(listIndex));
                        villagerBundle.add(villagerNine);

                        if (villagerAmount > 9) {
                            villagerTen = new Villager(nameList.get(listIndex));
                            villagerBundle.add(villagerTen);

                            if (villagerAmount > 10) {
                                villagerEleven = new Villager(nameList.get(listIndex));
                                villagerBundle.add(villagerEleven);

                                if (villagerAmount > 11) {
                                    villagerTwelve = new Villager(nameList.get(listIndex));
                                    villagerBundle.add(villagerTwelve);

                                    Toast.makeText(RandomAssignment.this, "works", Toast.LENGTH_SHORT).show();
                                }
                            }
                        }
                    }
                }
            }
        }
        listIndex += villagerAmount;
    }

解决方案

From my other answer, from which you took my code. The initDeck method actually reads like this

public void initDeck() {
    if (characters == null)
        characters = new ArrayList<String>();

        // addCharacter...

That will at least avoid a null pointer on the list...


You need to add more code to your question, but the problem starts in this block

addCharacter(demoniac, demoniacAmount, characters);
addCharacter(guard, guardAmount, characters);
addCharacter(medium, mediumAmount, characters);
addCharacter(mythomaniac, mythomaniacAmount, characters);
addCharacter(owl, owlAmount, characters);
addCharacter(werehamster, werehamsterAmount, characters);
addCharacter(getVillagerBundle(), villagerAmount, characters);
addCharacter(masonOne, 1, characters);
addCharacter(masonTwo, 1, characters);

which (roughly) calls this code

public void addCharacter(Card card, int amount, List<Card> cards) {
    for (int i = 0; i < amount; i++) {
        cards.add(card);
    }
}

The issue is that somewhere ANY of these variables are null and they are being added to the list as such

  • demoniac
  • guard
  • medium
  • mythomaniac
  • owl
  • werehamster
  • getVillagerBundle()
  • masonOne
  • masonTwo

You could either fix that by assigning all those variables to a new Card(), or avoid the problem like so

public void addCharacter(Card card, int amount, List<Card> cards) {
    for (int i = 0; i < amount; i++) {
        if (card != null) {
            cards.add(card);
        } else {
            Log.e("addCharacter", "Hey! Are you sure you meant to add a null card?");
        }
    }
}


Now what you have shown more of the code, the error starts here

if (demoniacAmount != 0) {
    demoniac = new Demoniac(nameList.get(listIndex));
    listIndex++;
} else if (guardAmount != 0) {
    guard = new Guard(nameList.get(listIndex));
    listIndex++;
}

What if demoniacAmount and guardAmount are both not zero, hmm? Only that first if condition will be entered. And guard will end up being null because it was never initialized. It makes no sense to do an else-if for completely different variables!

Properly perform your if-checking like so for all those conditions. (And I will leave the messy code as much as it bothers me)

if (demoniacAmount != 0) {
    demoniac = new Demoniac(nameList.get(listIndex));
    listIndex++;
} 

if (guardAmount != 0) {
    guard = new Guard(nameList.get(listIndex));
    listIndex++;
}

这篇关于如何存储在一个ArrayList自定义对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆