开发者

Java + Linked-List + Polymorphic Objects [closed]

开发者 https://www.devze.com 2023-04-10 12:47 出处:网络
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical andcannot be reasonably answered in its current form. For help clari
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

"Would you recommend inheriting off of the built in Linked List in order to customize 开发者_C百科it for my polymorphic objects? or should I build a Linked List from scratch?"


I'm not really sure what the context is here, but I would never (well, almost never) build a Linked List from scratch. What you could consider instead of inheritance is using delegation by the way. Define an interface for your 'polymorphic objects' and simply delegate all linked list related calls to the Linked List.


I wouldn't write your own unless you really really really have to. By "polymorphic objects" I am assuming you mean you have a class hierarchy and want to put instances of any of those classes in the list. Nothing prevents you from doing that, although the generics will place limits on the types the compiler sees, you can get around by casting as a last resort. Or you can just declare a list with no generic types, although in that case you lose all the compile-time checking you could get.

For 99.9999% of cases, the default LinkedList implementation is going to be fine. It's probably a better idea to use it than roll your own, unless the default implementation is completely inadequate. If you think it might be, update your question or start a new one with very explicit details. There is probably a good way to work with the default implementation.

All that said, if this is for learning, feel free to write you own linked list. Also note that anything you come up with will at best have to follow the same rules of generics/typing that the default LinkedList has. If you build your 'polymorphic objects' directly into the list, that's fine, but you have just created a really specific implementation that will only be useful for you (which might be ok).


If you need to create your own version of LinkedList that changes the behavior of one or more methods, you should use the Decorator pattern. I would also suggest using Guava's ForwardingList class which does most of the work for you.

0

精彩评论

暂无评论...
验证码 换一张
取 消