[英]List Linked List reference
如何在鏈接列表中獲取數據參考/索引?
例如,如果我有此鏈表
java.util.List<Polygon> triangles = new LinkedList<Polygon>();
polygon triangle, selectedTriangle;
Point startDrag,endDrag,midPoint;
....
triangles.add( new Polygon(xs, ys,3));
例如,如何將Polygon selectedTriangle設置為與鏈接數組列表中的現有三角形之一相同?
編輯:
java.util.List<Polygon> triangles = new LinkedList<Polygon>();
polygon triangle, selectedtriangle;
....
triangles.add( new Polygon(xs, ys,3));
.....
public void mousePressed(MouseEvent e) {
....
startDrag = new Point(e.getX(), e.getY());
endDrag = startDrag;
for (Polygon p : triangles) {
if (p.contains(startDrag)) {//inside triangle
//I dont know how to set the selectedTriangle as the same with existing triangle
selectedTriangle = triangles.indexOf(p.contains(startDrag));
break; //
}
}
.....
}
假設Polygon
覆蓋值equals
,則可以使用use:
int index = triangles.indexOf(desiredTriangle);
請注意,將索引與鏈表一起使用相對效率較低,因為到達任何特定索引都意味着將整個列表從頭移到該索引。
LinkedList
不提供用於查找第一個相等元素的API,但是您可以使用indexOf
后跟get
(需要兩次通過)或編寫自己的findFirst
方法,如下所示:
public static <T> T findFirst(Iterable<? extends T> collection, T value)
{
for (T t : collection)
{
if (t.equals(value))
{
return t;
}
}
return null;
}
(如果需要,請進行適當的空檢查。)
根據您的意思,我建議使用get或indexOf方法。 您可以在Java API中查看它們各自的作用: http : //java.sun.com/javase/6/docs/api/java/util/List.html
基本上,get接受一個數字並返回該索引處的對象。 IndexOf接收一個對象並返回在其找到的第一個索引(如果未找到,則返回-1)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.