Reputation: 1239
I guess this question that would have already been asked here. I searched but could not find anything similar. So here goes --
I have a custom data object Method
and Method
is as follows --
public Class Method {
List<String> inputParameters;
String resultVariableName;
}
Now i have a LinkedList<Method>
which acts as a repository of Method
objects.
Given a Method
object is there a way in which the correct index of the Method
object can be concretely determined.
My question arises from the face that LinkedList
class has an indexOf
routine but this routine returns the first occurrence of the object but then there is no given that 2 copies of Method
object can not reside in the LinkedList
(right ?)
Would tagging every Method
object as I add it to the LinkedList
solve my purpose and if so is there an ideal way to do it ?
EDIT :
Explaining my use case a little further.
My code basically reads a Velocity template top-down and creates Method
objects. One Method
object is created for every velocity routine encountered.
This explains why the same element can be stored at multiple indices in the LinkedList
as there is no real restriction on how many number of time a Velocity
routine is called or the inputs/results provided to the Velocity
routine.
Now, i have a UI component, one JButton
per Method
object reference in the LinkedList<Method>
by using which the user can click and edit the Method
object.
Thus i need to know which exact Method
object reference to edit in the event that same elements reside twice or more number of times in the LinkedList<Method>
Upvotes: 0
Views: 3027
Reputation: 8101
"there is not given 2 copies of Method object can not reside in the LinkedList", if this is a scenario, how will you identify which object to retrieve??
In this case, I would suggest you to use a LinkedHashMap, where you can use a Identifier as a key to uniquely identify a Method's
object.
Upvotes: 0
Reputation: 616
LinkedList does not avoid duplicates, it may have more than one copy.
You can put a logic to avoid multiple instances, extend the linkedlist class and override the add function to check if Method object already exists.
OR
If you want to get all instances of the Method object, you can use a ListIterator and collect all instances of it, and return this collection as a result.
Upvotes: 0
Reputation: 1499730
What do you mean by the "correct" index in the first place? If the linked list can contain the same element twice or more (and be careful here - the list will only contain a reference to a Method
object, not the object itself) then which index would be "correct" in your view?
Of course you can just iterate over the linked list yourself and return all indexes at which a given Method
reference occurs, but it's not clear what you're trying to do with it.
Note that indexes aren't often used with linked lists to start with, as obtaining the element at a given index is an O(n) operation.
Upvotes: 2