事先道歉,我是Java新手,我大部分都在使用別人的代碼,所以請耐心等待。我環顧四周,但找不到任何東西來幫助我的問題從ArrayList項中檢索數據
我已經從一個方法中檢索了一個ArrayList,然後我試圖編寫一個foreach循環來檢索某個特定的數據段,觀察「。
無論出於何種原因,當通過ArrayList訪問時,不會允許我檢索存儲在觀察內的任何數據。
ArrayList<Observation>[] npcPositions = stateObs.getNPCPositions();
Vector2d playerPosition = stateObs.getAvatarPosition();
int npcCount = npcPositions.length;
for (int i = 0; i <= npcCount; i++)
{
if (playerPosition.x == npcPositions[i].position)
{
}
}
位置是觀察內的值,但我得到的錯誤是它無法解析或不是字段。部分觀察類在下面,我無法訪問任何這些變量,正在做我目前正在做的事情。
public class Observation implements Comparable<Observation>
{
/**
* Category of this observation (static, resource, npc, etc.).
*/
public int category;
/**
* Type of sprite of this observation.
*/
public int itype;
/**
* unique ID for this observation
*/
public int obsID;
/**
* Position of the observation.
*/
public Vector2d position;
/**
* Reference to the position used for comparing this
* observation with others.
*/
public Vector2d reference;
那麼我需要什麼來訪問這些變量。我注意到當我想要存儲來自stateObs.getNPCPositions的數據時,我必須使用[],這似乎是其他示例不適合我的原因,但我不確定如何解決它。
UPDATE
原來的問題似乎是固定的,試圖檢索的ArrayList的長度然而,當我得到NullPointerException異常。我怎樣才能獲得每次能夠在循環中運行的項目數量?
更新#2
/**
* Returns a list of observations of NPC in the game. As there can be
* NPCs of different type, each entry in the array corresponds to a sprite type.
* Every ArrayList contains a list of objects of type Observation.
* Each Observation holds the position, unique id and
* sprite id of that particular sprite.
*
* @return Observations of NPCs in the game.
*/
public ArrayList<Observation>[] getNPCPositions()
{
return model.getNPCPositions(null);
}
/**
* Returns a list of observations of NPC in the game. As there can be
* NPCs of different type, each entry in the array corresponds to a sprite type.
* Every ArrayList contains a list of objects of type Observation, ordered asc. by
* distance to the reference passed. Each Observation holds the position, sprite type id and
* sprite id of that particular sprite.
*
* @param reference Reference position to use when sorting this array,
* by ascending distance to this point.
* @return Observations of NPCs in the game.
*/
public ArrayList<Observation>[] getNPCPositions(Vector2d reference)
{
return model.getNPCPositions(reference);
}
您的代碼看起來很奇怪,你爲什麼要創建的ArrayList對象的數組? (一般數組和「泛型」不應該混合使用) – GhostCat 2015-04-01 11:52:36
並且您需要使用.get(index)方法獲取arrayList值 – Pratik 2015-04-01 11:53:11
Eddy,我不是很難過。這是別人的代碼,這就是方法返回的內容。我不允許更改我沒有寫過的任何代碼。 – 2015-04-01 11:54:55