store ciass已破坏itunes store什么意思思

Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.
Eclipse is giving me a warning of the following form:
Type safety: Unchecked cast from Object to HashMap&String, String&
This is from a call to an API that I have no control over which returns Object:
HashMap&String, String& getItems(javax.servlet.http.HttpSession session) {
HashMap&String, String& theHash = (HashMap&String, String&)session.getAttribute("attributeKey");
return theH
I'd like to avoid Eclipse warnings, if possible, since theoretically they indicate at least a potential code problem.
I haven't found a good way to eliminate this one yet, though.
I can extract the single line involved out to a method by itself and add @SuppressWarnings("unchecked") to that method, thus limiting the impact of having a block of code where I ignore warnings.
Any better options?
I don't want to turn these warnings off in Eclipse.
Before I came to the code, it was simpler, but still provoked warnings:
HashMap getItems(javax.servlet.http.HttpSession session) {
HashMap theHash = (HashMap)session.getAttribute("attributeKey");
return theH
Problem was elsewhere when you tried to use the hash you'd get warnings:
HashMap items = getItems(session);
items.put("this", "that");
Type safety: The method put(Object, Object) belongs to the raw type HashMap.
References to generic type HashMap&K,V& should be parameterized.
19.8k41130178
The obvious answer, of course, is not to do the unchecked cast.
If it's absolutely necessary, then at least try to limit the scope of the @SuppressWarnings annotation. According to its , it can g this way, it doesn't even affect the entire method.
@SuppressWarnings("unchecked")
Map&String, String& myMap = (Map&String, String&) deserializeMap();
There is no way to determine whether the Map really should have the generic parameters &String, String&. You must know beforehand what the parameters should be (or you'll find out when you get a ClassCastException). This is why the code generates a warning, because the compiler can't possibly know whether is safe.
92.8k25204247
W I think I figured out the answer to my own question.
I'm just not sure it's worth it! :)
The problem is the cast isn't checked.
So, you have to check it yourself.
You can't just check a parameterized type with instanceof, because the parameterized type information is unavailable at runtime, having been erased at compile time.
But, you can perform a check on each and every item in the hash, with instanceof, and in doing so, you can construct a new hash that is type-safe.
And you won't provoke any warnings.
Thanks to mmyers and Esko Luontola, I've parameterized the code I originally wrote here, so it can be wrapped up in a utility class somewhere and used for any parameterized HashMap.
If you want to understand it better and aren't very familiar with generics, I encourage viewing the edit history of this answer.
public static &K, V& HashMap&K, V& castHash(HashMap input,
Class&K& keyClass,
Class&V& valueClass) {
HashMap&K, V& output = new HashMap&K, V&();
if (input == null)
for (Object key: input.keySet().toArray()) {
if ((key == null) || (keyClass.isAssignableFrom(key.getClass()))) {
Object value = input.get(key);
if ((value == null) || (valueClass.isAssignableFrom(value.getClass()))) {
K k = keyClass.cast(key);
V v = valueClass.cast(value);
output.put(k, v);
throw new AssertionError(
"Cannot cast to HashMap&"+ keyClass.getSimpleName()
+", "+ valueClass.getSimpleName() +"&"
+", value "+ value +" is not a "+ valueClass.getSimpleName()
throw new AssertionError(
"Cannot cast to HashMap&"+ keyClass.getSimpleName()
+", "+ valueClass.getSimpleName() +"&"
+", key "+ key +" is not a " + keyClass.getSimpleName()
That's a lot of work, possibly for very little reward...
I'm not sure if I'll use it or not.
I'd appreciate any comments as to whether people think it's worth it or not.
Also, I'd appreciate improvement suggestions: is there something better I can do besides throw AssertionErrors?
Is there something better I could throw?
Should I make it a checked Exception?
6,23742244
19.8k41130178
Unfortunately, there are no great options here. Remember, the goal of all of this is to preserve type safety.
"" offers a solutions for dealing with non-genericized legacy libraries, and there is one in particular called the "empty loop technique" in section section 8.2. Basically, make the unsafe cast, and suppress the warning. Then loop through the map like this:
@SuppressWarnings("unchecked")
Map&String,Number& map = getMap();
for (String
s : map.keySet());
for (Number
n : map.values());
If an unexpected type is an encountered, you will get a runtime ClassCastException, but at least it will happen close to the source of the problem.
9,03164470
In Eclipse Preferences, Go to Java->Compiler->Errors/Warnings->Generic types and check the Ignore unavoidable generic type problems check-box.
This satisfies the intent of the question, i.e.
I'd like to avoid Eclipse warnings...
if not the spirit.
3,05212145
This stuff is hard, but here are my current thoughts:
If your API returns Object, then there's nothing you can do -- no matter what, you will be blindly casting the object. You let Java throw ClassCastExceptions, or you can check each element yourself and throw Assertions or IllegalArgumentExceptions or some such, but these runtime checks are all equivalent. You have to suppress the compile time unchecked cast
no matter what you do at runtime.
I'd just prefer to blind cast and let the JVM perform its runtime check for me since we "know" what the API should return, and are usually willing to assume that the API works. Use generics everywhere above the cast, if you need them. You aren't really buying anything there since you still have the single blind cast, but at least you can use generics from there on up so the JVM can help you avoid blind casts in other pieces of your code.
In this particular case, presumably you can see the call to SetAttribute and see the type is going in, so just blind-casting the type to same on the way out is not immoral. Add a comment referencing the SetAttribute and be done with it.
9,208549101
You can create a utility class like the following, and use it to suppress the unchecked warning.
public class Objects {
* Helps to avoid using {@code @SuppressWarnings({"unchecked"})} when casting to a generic type.
@SuppressWarnings({"unchecked"})
public static &T& T uncheckedCast(Object obj) {
return (T)
You can use it as follows:
import static Objects.uncheckedC
HashMap&String, String& getItems(javax.servlet.http.HttpSession session) {
return uncheckedCast(session.getAttribute("attributeKey"));
Some more discussion about this is here:
56.1k66996
In this particular case, I would not store Maps into the HttpSession directly, but instead an instance of my own class, which in turn contains a Map (an implementation detail of the class). Then you can be sure that the elements in the map are of the right type.
But if you anyways want to check that the contents of the Map are of right type, you could use a code like this:
public static void main(String[] args) {
Map&String, Integer& map = new HashMap&String, Integer&();
map.put("a", 1);
map.put("b", 2);
Object obj =
Map&String, Integer& ok = safeCastMap(obj, String.class, Integer.class);
Map&String, String& error = safeCastMap(obj, String.class, String.class);
@SuppressWarnings({"unchecked"})
public static &K, V& Map&K, V& safeCastMap(Object map, Class&K& keyType, Class&V& valueType) {
checkMap(map);
checkMapContents(keyType, valueType, (Map&?, ?&) map);
return (Map&K, V&)
private static void checkMap(Object map) {
checkType(Map.class, map);
private static &K, V& void checkMapContents(Class&K& keyType, Class&V& valueType, Map&?, ?& map) {
for (Map.Entry&?, ?& entry : map.entrySet()) {
checkType(keyType, entry.getKey());
checkType(valueType, entry.getValue());
private static &K& void checkType(Class&K& expectedType, Object obj) {
if (!expectedType.isInstance(obj)) {
throw new IllegalArgumentException("Expected " + expectedType + " but was " + obj.getClass() + ": " + obj);
56.1k66996
In the HTTP Session world you can't really avoid the cast, since the API is written that way (takes and returns only Object).
With a little bit of work you can easily avoid the unchecked cast, 'though. This means that it will turn into a traditional cast giving a ClassCastException right there in the event of an error). An unchecked exception could turn into a CCE at any point later on instead of the point of the cast (that's the reason why it's a separate warning).
Replace the HashMap with a dedicated class:
import java.util.AbstractM
import java.util.C
import java.util.HashM
import java.util.M
import java.util.S
public class Attributes extends AbstractMap&String, String& {
final Map&String, String& content = new HashMap&String, String&();
public Set&Map.Entry&String, String&& entrySet() {
return content.entrySet();
public Set&String& keySet() {
return content.keySet();
public Collection&String& values() {
return content.values();
public String put(final String key, final String value) {
return content.put(key, value);
Then cast to that class instead of Map&String,String& and everything will be checked at the exact place where you write your code. No unexpected ClassCastExceptions later on.
148k26312448
A quick guess if you post your code can say for sure but you might have done something along the lines of
HashMap&String, Object& test = new HashMap();
which will produce the warning when you need to do
HashMap&String, Object& test = new HashMap&String, Object&();
it might be worth looking at
if your unfamiliar with what needs to be done.
2,94232246
If I have to use an API that doesn't support Generics.. I try and isolate those calls in wrapper routines with as few lines as possible. I then use the SuppressWarnings annotation and also add the type-safety casts at the same time.
This is just a personal preference to keep things as neat as possible.
8,66732147
I may have misunderstood the question(an example and a couple of surrounding lines would be nice), but why don't you always use an appropriate interface (and Java5+)? I see no reason why you would ever want to cast to a HashMap instead of a Map&KeyType,ValueType&. In fact, I can't imagine any reason to set the type of a variable to HashMap instead of Map.
And why is the source an Object? Is it a parameter type of a legacy collection? If so, use generics and specify the type you want.
103k19192265
Just typecheck it before you cast it.
Object someObject = session.getAttribute("attributeKey");
if(someObject instanceof HashMap)
HashMap&String, String& theHash = (HashMap&String, String&)someO
And for anyone asking, it's quite common to receive objects where you aren't sure of the type.
Plenty of legacy "SOA" implementations pass around various objects that you shouldn't always trust.
(The horrors!)
EDIT Changed the example code once to match the poster's updates, and following some comments I see that instanceof doesn't play nicely with generics.
However changing the check to validate the outer object seems to play well with the commandline compiler.
Revised example now posted.
Almost every problem in Computer Science can be solved by adding a level of indirection*, or something.
So introduce a non-generic object that is of a higher-level that a Map. With no context it isn't going to look very convincing, but anyway:
public final class Items implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private Map&String,String&
public Items(Map&String,String& map) {
this.map = New.immutableMap(map);
public Map&String,String& getMap() {
@Override public String toString() {
return map.toString();
public final class New {
public static &K,V& Map&K,V& immutableMap(
Map&? extends K, ? extends V& original
// ... optimise as you wish...
return Collections.unmodifiableMap(
new HashMap&String,String&(original)
static Map&String, String& getItems(HttpSession session) {
Items items = (Items)
session.getAttribute("attributeKey");
return items.getMap();
*Except too many levels of indirection.
90.6k14128222
Take this one, it's much faster than creating a new HashMap, if it's already one, but still secure, as each element is checked against it's type...
@SuppressWarnings("unchecked")
public static &K, V& HashMap&K, V& toHashMap(Object input, Class&K& key, Class&V& value) {
assert input instanceof Map :
for (Map.Entry&?, ?& e : ((HashMap&?, ?&) input).entrySet()) {
assert key.isAssignableFrom(e.getKey().getClass()) : "Map contains invalid keys";
assert value.isAssignableFrom(e.getValue().getClass()) : "Map contains invalid values";
if (input instanceof HashMap)
return (HashMap&K, V&)
return new HashMap&K, V&((Map&K, V&) input);
The Objects.Unchecked utility function in the answer above by Esko Luontola is a great way to avoid program clutter.
If you don't want the SuppressWarnings on an entire method, Java forces you to put it on a local. If you need a cast on a member it can lead to code like this:
@SuppressWarnings("unchecked")
Vector&String& watchedSymbolsClone = (Vector&String&) watchedSymbols.clone();
this.watchedSymbols = watchedSymbolsC
Using the utility is much cleaner, and it's still obvious what you are doing:
this.watchedSymbols = Objects.uncheckedCast(watchedSymbols.clone());
The problem lies in here:
... = (HashMap&String, String&)session.getAttribute("attributeKey");
The result of session.getAttribute(...) is an object which could be anything, but since you "know" it's a HashMap&String, String& you're just casting without checking it first.
Thus, the warning.
To be pedantic, which Java wants you to be in this case, you should retrieve the result and verify it's compatibility with instanceof.
5,05321425
If you are sure that the type returned by session.getAttribute() is HashMap then you can not typecast to that exact type, but rely on only checking the generic HashMap
HashMap&?,?& getItems(javax.servlet.http.HttpSession session) {
HashMap&?,?& theHash = (HashMap&?,?&)session.getAttribute("attributeKey");
return theH
Eclipse will then surprise warnings, but of course this can lead to runtime errors that can be hard to debug. I use this approach in not operation-critical contexts only.
This makes the warnings go away...
static Map&String, String& getItems(HttpSession session) {
HashMap&?, ?& theHash1 = (HashMap&String,String&)session.getAttribute("attributeKey");
HashMap&String,String& theHash = (HashMap&String,String&)theHash1;
return theH
4,60051323
Two ways, one which avoids the tag completely, the other using a naughty but nice utility method.
The problem is pre-genericised Collections...
I believe the rule of thumb is: "cast objects one thing at a time" - what this means when trying to use raw classes in a genericised world is that because you don't know what is in this Map&?, ?& (and indeed the JVM might even find that it isn't even a Map!), it obvious when you think about it that you can't cast it.
If you had a Map&String, ?& map2 then HashSet&String& keys = (HashSet&String&)map2.keySet() does not give you a warning, despite this being an "act of faith" for the compiler (because it might turn out to be a TreeSet)... but it is only a single act of faith.
PS to the objection that iterating as in my first way "is boring" and "takes time", the answer is "no pain no gain": a genericised collection is guaranteed to contain Map.Entry&String, String&s, and nothing else.
You have to pay for this guarantee.
When using generics systematically this payment, beautifully, takes the form of coding compliance, not machine time!
One school of thought might say that you should set Eclipse's settings to make such unchecked casts errors, rather than warnings.
In that case you would have to use my first way.
import java.util.HashM
import java.util.I
import java.util.M
import java.util.V
public class YellowMouse {
// First way
Map&String, String& getHashMapStudiouslyAvoidingSuppressTag(HttpSession session) {
Map&?, ?& theHash = (Map&?, ?&)session.getAttribute("attributeKey");
Map&String, String& yellowMouse = new HashMap&String, String&();
for( Map.Entry&?, ?& entry : theHash.entrySet() ){
yellowMouse.put( (String)entry.getKey(), (String)entry.getValue() );
return yellowM
// Second way
Map&String, String& getHashMapUsingNaughtyButNiceUtilityMethod(HttpSession session) {
return uncheckedCast( session.getAttribute("attributeKey") );
// NB this is a utility method which should be kept in your utility library. If you do that it will
// be the *only* time in your entire life that you will have to use this particular tag!!
@SuppressWarnings({ "unchecked" })
public static synchronized &T& T uncheckedCast(Object obj) {
return (T)
Here's one way I handle this when I override the equals() operation.
public abstract class Section&T extends Section& extends Element&Section&T&& {
Object attr1;
* Compare one section object to another.
* @param obj the object being compared with this section object
* @return true if this section and the other section are of the same
* sub-class of section and their component fields are the same, false
* otherwise
public boolean equals(Object obj) {
if (obj == null) {
// this exists, but obj doesn't, so they can't be equal!
// prepare to cast...
Section&?&
if (getClass() != obj.getClass()) {
// looks like we're comparing apples to oranges
// it must be safe to make that cast!
other = (Section&?&)
// and then I compare attributes between this and other
return this.attr1.equals(other.attr1);
This seems to work in Java 8 (even compiled with -Xlint:unchecked)
Warning suppression is not a solution. You should not be doing two level casting in one statement.
HashMap&String, String& getItems(javax.servlet.http.HttpSession session) {
// first, cast the returned Object to generic HashMap&?,?&
HashMap&?, ?& theHash = (HashMap&?, ?&)session.getAttribute("attributeKey");
// next, cast every entry of the HashMap to the required type &String, String&
HashMap&String, String& returingHash = new HashMap&&();
for (Entry&?, ?& entry : theHash.entrySet()) {
returingHash.put((String) entry.getKey(), (String) entry.getValue());
return returingH
Solution: Disable this warning in Eclipse. Don't @SuppressWarnings it, just disable it completely.
Several of the "solutions" presented above are way out of line, making code unreadable for the sake of suppressing a silly warning.
Your Answer
Sign up or
Sign up using Google
Sign up using Facebook
Sign up using Stack Exchange
Post as a guest
Post as a guest
By posting your answer, you agree to the
Not the answer you're looking for?
Browse other questions tagged
Upcoming Events
Stack Overflow works best with JavaScript enabled集邮的英语作文最好用上after class,be interested in,grow up,store,particularly,hobby这些词,_百度作业帮
集邮的英语作文最好用上after class,be interested in,grow up,store,particularly,hobby这些词,
最好用上after class,be interested in,grow up,store,particularly,hobby这些词,
我的爱好集邮英语作文(My hobby is collect stamps)My hobby is collect stamps. I have collected more than two hundred stamps. I began to collect them one year ago.I like stamps because they are very beautiful and very interesting. Every stamp have a wonderful picture and from it you can learn a lot.I have some stamps with Beijing Opera. They show us the traditional art of China. In some stamps there are beautiful animals and birds. And some stamps are about the famous persons.Don’t you think the stamps are very interesting and valuable?
I don't know!
您可能关注的推广回答者:回答者:

我要回帖

更多关于 app store中文意思 的文章

 

随机推荐