Can I get a reference to List<> object having a reference to one of its elements?
For example I have a reference to an mItem
object of my List<mItem> mList
collection. Is tha开发者_如何学运维t possible to get a reference to mList
using mItem
?
The short answer is no. The items in a list don't know they are in a list. (Unless of course you add a reference to the list inside your mItem object.)
Short answer: no.
Adding an item to a list adds a reference to that object to the list. It does not affect the object itself.
You can check to see if an item is in a specific list, with mList.contains(mItem)
which returns true if the item is in mList
. Alternatively if you really need to, you could as others have suggested implement a version of List that informs each item that the list has a reference to that item. The overhead would be rather messy though.
Meta question: why do you need this functionality?
As jzd said... you can add a field to your mItem
class (for example referenceHolder
)
mItem(Object ref){
referenceHolder = ref;
}
class with List:
mList.add(new mItem(this));
something like that should work :) but its kind of weird ;), because normally "The items in a list don't know they are in a list. "
EDIT: and as said before - "One object should be a member of multiple collections" - so you would need to change type of my referenceHolder to some list or array, to make that able to happen.
EDIT2: that's just reference to object holding that list (if one object will have multiple lists, you wont be able to know witch of them is holding that sepecified mItem
object), to reference to List itself you will need (as said in comment ;)) custom list implementation adding references to stored objects with this
in add()
method.
If you have a container for all you lists, you can call contains
on each one to find which list the item is in.
Note: for a list you can have the same element multiple time, and across multiple list.
BTW: If you don't want duplicates in a list and don't care about the order of elements then a Set may be your best choice.
精彩评论