tags:

views:

184

answers:

2

How to get the data reference/index in Linked list?

e.g. if I have this linked list

java.util.List<Polygon> triangles = new LinkedList<Polygon>();

polygon triangle, selectedTriangle;
Point startDrag,endDrag,midPoint;
....

triangles.add( new Polygon(xs, ys,3));

e.g. How can I set the Polygon selectedTriangle as the same with one of the existing triangle in the linked array list?

EDITED:

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; //
    }
  }
.....

}
+5  A: 

Assuming that Polygon overrides equals appropriately, you can use use:

int index = triangles.indexOf(desiredTriangle);

Note that using indexes with a linked list is relatively inefficient, as getting to any specific index means walking the whole list from the head to that index.

LinkedList doesn't offer an API to find the first equal element, but you could either use indexOf followed by get (requiring two passes) or write your own findFirst method like this:

public static <T> T findFirst(Iterable<? extends T> collection, T value)
{
    for (T t : collection)
    {
        if (t.equals(value))
        {
            return t;
        }
    }
    return null;
}

(With suitable null checking if you need it.)

Jon Skeet
A: 

Depending on exactly what you mean, I'd recommend using the get or indexOf methods. You can see what they each do in the Java API: http://java.sun.com/javase/6/docs/api/java/util/List.html

Basically get takes in a number and returns the object at that index. IndexOf takes in an object and returns the first index it is found at (or -1 if it is not found.)

Matt Boehm