This week's book giveaway is in the Mac OS forum. We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line! See this thread for details.
This messages has been a thorn in my side for some time but I have always ignored it since it isn�t an error and doesn�t affect my applications. But I really want to know why i.e why does the compiler show this warning when I use ArrayList(): "xxx.java uses unchecked or unsafe operations."
Java version 5 introduced generics, a new way to work with collections like ArrayList. If you ignore the generics features, you get these warnings. You can read the linked document, and then come back here with questions if you want!
Keeping in mind that I have only been developing for a couple of years now, I can't see any good reason why you would load an ArrayList with more than one type of object anyway. On the backend you would then have to use reflection to figure out what type of object you were getting back.Then you would have to cast it back, which isn't that big of a deal. The biggest problem would be that you would need some sort of a mechanism for dealing with the fact that the object you pull out may not be what you expected it to be, so then what happens? To me, that would be sort of a developmental nightmare. Keeping track of what was where within the collection would be horrible.
I always thought that the point of the standard libraries was to make things as flexible as possible. By being able to declare the type of objects in the container, there is no need to cast it back on the back end. (It also more closely aligns it with C++ and C also). Isn't a collection by definition a group of similar items (or objects)?
author and iconoclast
Isn't the point to be able to put different kinds of objects in it?
It's actually quite rare in real programs to have a specific collection of objects that don't share a common type. If they're not all of the same class, then they'll virtually always share a common interface or superclass -- i.e., if they're not all Cows, then they're probably all Mammals.
So it's nice that ArrayLists can store any kind of object -- but a single individual ArrayList is essentially never called on to store more than one kind of object. I don't know that I've ever programmed an ArrayList that contained (for example) a Cow, a String, and an int.
Anyway, by declaring that you've got an ArrayList<Cow>, you avoid having use ugly (and potentially incorrect) type casts -- i.e., instead of
and the nice thing is that if you've gotten confused and tried to make a Dog moo(), the first version will throw an exception at runtime, but the second version will fail to compile. That means you fix the problem right after you make the mistake, instead of a week later when a user reports the problem to you.