Java LinkedList -- Retrieving the index of an Object - java

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>

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.

Duplicates are allowed in LinkedList's.

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.

"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.

Related

List Implementation in different scenerios

I have a very simple question that I would like to ask. There are 2 ways by which you initialize a variable :
1.
List<SalesReturnJson> salesReturnJsons=new LinkedList<>();
salesReturnJsons=salesRepository.findSales();
2.
List<SalesReturnJson> salesReturnJsons=salesRepository.findSales();
So in this 2 scenerios how is the memory allocated and In the second scenerio which implementation(LinkedList or ArrayList) of List is called.
Any help will be highly appreciated.
If in the first scenario the second line is exactly below the first line, the "new" statement would have no effect. You create an empty LinkedList, put a reference on it, then you change the reference to point to another List (I suppose findSales returns a List) and finally the garbage collector of java will erase the empty LinkedList, since there is no reference to it anymore.
In the second scenario you return a List (as I suppose) and put a reference to this List.
In both cases an object returned by salesRepository.findSales() will be assigned to your variable. Since the implementation is the same in both cases, without knowing the actual implementation we can only say that the object will be of the same class in both cases, however, creating an object and then re-assigning the variable to another reference as in your first example makes little sense. The second will achieve the same result, but with reduced effort.
Both scenarios end up with exactly the same List in your salesReturnJsons variable, with the List type being the one returned by salesRepository.findSales(). From the code given, we can't tell what type is actually returned from this method.
The only difference is, the first scenario creates an absolutely unnecessary empty LinkedList, stores it into your salesReturnJsons variable, and immediately replaces it by the list from salesRepository.findSales(), making the LinkedList garbage. So, please use the second version.
If (for whatever special reason) your intent might be to have a LinkedList of the salesRepository.findSales() results, then you could do:
List<SalesReturnJson> salesReturnJsons=
new LinkedList<SalesReturnJson>(salesRepository.findSales());
That will copy the elements from the method result into a fresh LinkedList, then you are sure about the List type.
But the typical code snippet would be your version 2.

How can we maintain unique object list without using set?

Suppose we have two employee instances having some common attributes like id,name,address (All values are same ).
I want unique objects list without implementing Set.
Please don’t explain the logic with Primitive data type ,I want the uniqueness with Object type.
Simple: you create a "collection" class that calls uses the equals() method of "incoming" objects to compare them against already stored objects.
If that method gives all false - no duplicate, you add to the collection. If true - not unique. No adding.
In other words - you re-invent the wheel and create something that resembles a Java set. Of course, with all the implicit drawbacks - such as repeating implementation bugs that were fixed in the Java set implementations 15 to 20 years ago.
If you don't want to use a Set, use a List. All you need to know to implement uniqueness checking logic is whatequals(Object other) method does:
Indicates whether some other object is "equal to" this one
Now you can test an incoming object against all objects currently on your list, and add it if a match is not found.
Obviously, performance of this method of maintaining a unique collection of objects is grossly inferior to both hash-based and ordering-based sets.
If you cannot use a Set for holding unique instances of your Employee class, you can use a List. This requires you to do two things:
Override equals() (and hashCode()) in Employee to contain the equality logic. This you would need even if you used a Set.
Each time you add items to the list, use List.contains() for checking whether an equal object is already in the list. The method will internally use your Employee.equals() implementation. Add an item only if it's not already in the list. Note that this method is quite inefficient as it needs to iterate through the whole list in worst case (when an item is not already in the list).

Java: Wrapping objects in some type of collection to store duplicates in a set

I want to make a set of some type of collection (not sure which one yet) as a way of "storing duplicates" in a set. For example if I wanted to add the integer 5 with 39 additional copies I could put it into an arraylist at index 39. Thus if I were to get the size of the arraylist, I would know how many copies of 5 existed within the set.
There are a few other ways I could implement this but I have yet to decide on one. The main issue I'm having with implementing this is that I'm not sure how I can "dynamically" make arraylists (or whatever collection I may end up using) so that whenever someone were to call mySet.add(object), the object is first inserted into a unique arraylist then into the set itself.
Can anyone give me some ideas on how I could approach this?
EDIT:
Sorry I should have been more clear in my question. The point of the code that I'm writing is that we have a set-like collection that allows duplicates. And yes some of the associated methods will be re-written/will have to be re-written. Also my code should be written under the assumption that we do not know what type of object is being inserted(only one data type per set though) nor how many instances of the same object will be added nor how many different unique objects will be added.
I would rather go for using a Map like
HashMap list <Object, Integer>
where Object is the Object that you want to count and Integer is the count
You could try guava's MultiSet, I think it's what you want.
It can store the count of each object. What you need to do is just
multiSet.put(object);
And if it is put for the first time, like you said, a new list will be created, or its count will added by one.

Finding position of Object in multidimensional List

I have a data structure that is of type List<List<CustomObject>>. I want to be able to find the position of a particular CustomObject in my data structure. The output would show me the index for e.g. 1,0 which means the CustomObject is the 0th element in the 1st list item.
I have thought of the following ways to implement this:
Loop through the list one by one and compare the CustomObject. Of course i'll have to implement the equals method in CustomObject to compare.
Use the indexOf method to figure out the first index of the data structure which has the CustomObject. However in this the parameter to equals would be List<CustomObject>.
Are there any other efficient ways to get the index?
Iterate over the main list and call .contains () to check if object is there. If true, use indexOf() to locate it.
You must properly implement equals() and hashcode() in your object .
You can also use .lastIndexOf(Object o) method to get the index of your object directly in one call. This method will give you -1 if that object does not exist in the list.
Check the doc for more detail.
http://docs.oracle.com/javase/7/docs/api/java/util/List.html#lastIndexOf(java.lang.Object)
The only issue is this method will give you only the last occurrence of the object. If you have duplicate objects in the list, this will not work.
Also you must properly implement equals and hashcode method for proper comparison to occur.
indexOf iterates for you, so 1) and 2) are actually the same. And if the element you're looking for is in the last slot of the last list you iterate over the entire dataset.
To get better then that, you'll have to store the index explicitly in a second datastructure that allows for more efficient searching. Taking the winner in the "search" category for datastructures from http://bigocheatsheet.com/ - a HashMap in java - you could do it as follows:
In a HashMap<CustomObject, Index> you store per object the desired index. That also needs to be updated each time you update the list. Both updating and searching for an item requires only constant time, in other words is independent of the amount of elements you have.
With such a map in place, instead of searching through your list, you'll do map.get(customObject) and you'll have the result.
The question for you to answer: can you keep such a datastructure up to date consistently and with less effort than searching in a list. Because if you update your list in a way that affects multiple elements you may loose all benefit due to constantly redoing the entire map.
Besides using multiple datastructures, maybe there is 1 that fits both needs better than a list and a map. But that depends on your data and how you need to access it and which part thereof needs to be optimized.

Most efficient way for an object to remove itself from a list

Let's say we have an array list of objects ObjArray.
What is the most efficient way for that object to locate itself within the list, and remove itself from the list?
The way I tend to use is this:
Every object in the list has an ID that corresponds to its place in the list
When object.remove() is called, the object simply simply calls ObjArray.remove(ID).
ObjArray is parsed from index ID upwards calling ObjArray.get(i).ID--. This sets all objects above the removed object to the right ID.
The other method is of course simply parsing ObjArray until a object match is found.
So, is there a better way of doing this? ArrayList is not necessary, if a HashMap or LinkedList can be used to do things better, that's just as good.
More information as requested.
Objects contain information as to where they need to be drawn on screen, and what image is to be drawn. The paint function of the main JPanel is called by a timer. The paint function loops through the list ObjArray and calls the the object's draw function (Obj.draw(Graphics g)).
Objects may be added or removed by clicking.
When an object is removed, it need to remove itself from the ObjArray list. I have stated the two methods that I can think of in the first part.
I would like to know if anyone knows of a more efficient way of doing this.
In short:
What's the most efficient way for an item to find/know its position in a list
Efficient in terms of code:
list.remove(this);
The object must be given a reference to the list of course.
Efficient in terms of performance would require a small redesign, probably involving a Map, but is beyond the scope of this question.
Usethe List's indexOf to get the ID. Drop your idea of an ID for each object._

Categories