簡體   English   中英

處理/ Java ArrayList和LinkedList異常

[英]Processing/Java ArrayList & LinkedList exception

我試圖在我的一款游戲中實現尋路系統,所以我遇到了以下問題。

我在這里得到了一個不錯的ArrayList:

ArrayList<PVector> path = new ArrayList<>();

現在為空,稍后在Process中填充PVector條目:

{5.0,6.0,0},{5.0,7.0,0},{5.0,8.0,0},{5.0,9.0,0}

那很好嗎? 但是我不能使用它,因為我只需要{5.0,6.0,0}的5.0...。

我用path.get(0)試了一下...我只得到{5.0,6.0,0} ...所以我在這里找到了一些新的東西:

path.get(0)[0]; 還是沒有用...因為表達式類型需要是一個數組,但是它解析為一個對象

那么,如何從索引中獲取單個條目? :/如何從{5.0,6.0,0}獲得5.0

所以您有一個PVectorArrayList ,對嗎? 這意味着,當您從ArrayList get時,您將獲得一個PVector 我不知道PVector,但有(希望)的方法PVector拿到第一INT( x()或東西)。

對於此類問題, 參考文獻是您最好的朋友。

但是請記住path.get(0)返回一個PVector 然后,您可以使用PVector API定位其位置。 像這樣:

ArrayList<PVector> path = new ArrayList<PVector>();
//add PVectors to path
PVector p = path.get(0);
float x = p.x;

請注意,我正在使用<PVector>泛型,以便ArrayList知道其擁有的對象類型。 p變量不是必需的; 我只是用它來顯示path.get()返回一個PVector 您也可以一行完成:

ArrayList<PVector> path = new ArrayList<PVector>();
//add PVectors to path
float x = path.get(0).x;

聲明變量時,請始終對將要存儲在其中的最特殊類型的泛型類型進行參數化:

// Declaration:
List<PVector> path = new ArrayList<PVector>();

// Storing:
path.add(new PVector(...));
path.add(new PVector(...));
...

// Reading:
PVector pVector=path.get(n);
pVector.get(...)

這樣,從列表中讀取項目時,您將獲得存儲的對象完全相同的類型

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM