This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
I am looking for a good source to look up information regarding generics. More specific is this: On a JDialog, I want to have a JCombobox that houses two differant types of objects. The objects are similar, although they do not inherit from each other and, rather, both inherit from Object. Ok, more specific. I want to (in one combo) have a list of both of these objects (easy) and later (?) upcast (?) back up to the original object again. (hard) I need to be able to find out how to ask the object what it is so that I can perform the upcast(?). Does anyone know of a good source to look that up, or (if the code is a one liner, would mind sharing it with me?)? Thank you!!!
Yes, but I don't think we have any good examples in this thread yet. You really ought to organise the types before you get to instanceof. There a re a few places where it is really useful. For example, if you go through the List interface, you find about twenty methods, which all appear in the ArrayList class, because ArrayList is a List. But there is another method which is only in ArrayList, so you can call it on an ArrayList and not on a LinkedList. So you would need to cast the List to an ArrayList, and instanceof allows you to check that cast. Look:Now, all this adding at the end will take time. ArrayLists are fast, but they like to have space. LinkedLists have no trouble adding at the end like that, but there is a method in ArrayList which makes adding millions of elements very very fast. But you can't call it on a Linked List. So you have to cast.:The ensureCapacity method isn't in List, nor in LinkedList, and the instanceof test ensures yoiu can cast without an Exception. So you can very quickly add those 1000000000 elements and just as quickly run out of memory
Another thing about ArrayLists: If you ever get those 1000000000 Foos into the list, you might want to look for a particular element. So you might want the get() method. But does get() work well? Look for the RandomAccess tagging interface. Now we can test for itYou will have read all about RandomAccess and know it means you can use get or a for loop without an Iterator to iterate the Collection. If fooList is a LinkedList, you would use the second method (in the else block) to find element 123456789.