DEV Community

DEV Community

Emil Ossola

Posted on Jun 1, 2023

How to Avoid Unchecked Casts in Java Programs

Unchecked cast refers to the process of converting a variable of one data type to another data type without checks by the Java compiler.

This operation is unchecked because the compiler does not verify if the operation is valid or safe. Unchecked casts can lead to runtime errors, such as ClassCastException, when the program tries to assign an object to a variable of an incompatible type.

Hence, it is important to avoid unchecked casts in Java programs to prevent potential errors and ensure the program's reliability.

Image description

Consequences of Unchecked Casts

In Java programs, unchecked casts can lead to several issues. The most common problem is a ClassCastException at runtime, which occurs when we try to cast an object to a wrong type. This can cause the program to crash or behave unexpectedly.

Unchecked casts also violate the type safety of the Java language, which can lead to bugs that are difficult to detect and debug. Additionally, unchecked casts can make the code less readable and maintainable, as they hide the true type of objects and dependencies between components.

Therefore, it is important to avoid unchecked casts and use other mechanisms, such as generics or polymorphism, to ensure type safety and code quality in Java programs.

Image description

How Unchecked Casts Occur

Unchecked casts in Java programs occur when an object of one type is assigned to a reference of another type without proper type checking. This can happen when a programmer assumes that a reference to a superclass is actually a reference to its subclass and tries to cast it into that subclass. If the assumption is incorrect, the cast will result in a ClassCastException at runtime.

Unchecked casts can also occur when dealing with raw types, which are generic types without any type parameters specified. In such cases, the compiler cannot perform type checking and the programmer must ensure that the proper type conversions are made. Failing to do so can result in unchecked casts and potential runtime errors.

Why unchecked casts are problematic

In Java, unchecked casts allow a programmer to cast any object reference to any other reference type without providing any type information at compile-time. While this flexibility may seem useful, it can lead to serious run-time errors. If the object being casted is not actually of the type specified, a ClassCastException will occur at run-time.

Unchecked casts can cause difficult-to-debug errors in large and complex codebases, as it may not be immediately clear where the error originated. Additionally, unchecked casts can undermine Java's type system, creating code that is harder to read, maintain, and reason about. As a result, avoiding unchecked casts should be a priority when writing Java programs.

Examples of Unchecked Casts in Java

Unchecked casts are a common source of Java program errors. Here are some examples of unchecked casts:

This cast statement above can result in a class cast exception if the object referred to by obj is not a List.

In this case, the cast could fail at runtime if the array contains objects of a type other than String.

Finally, this cast could fail if the object referred to by obj is not a Map.

Using Generics to Avoid Unchecked Casts in Java

In Java, Generics is a powerful feature that allows you to write classes and methods that are parameterized by one or more types. Generics are a way of making your code more type-safe and reusable. With generics, you can define classes and methods that work on a variety of types, without having to write separate code for each type.

Using generics in Java programs has several advantages. It enables type safety at compile-time, which can prevent ClassCastException errors at runtime. With generics, the compiler can detect type mismatches and prevent them from happening, which leads to more robust and reliable code. It also allows for code reuse without sacrificing type safety and improve performance by avoiding unnecessary casting and allowing for more efficient code generation.

Generics allow Java developers to create classes and methods that can work with different data types. For example, a List can be defined to hold any type of object using generics. Here's an example:

In this example, we create a List that holds String objects. We can add String objects to the list and iterate over them using a for-each loop. The use of generics allows us to ensure type safety and avoid unchecked casts. Another example is the Map interface, which can be used to map keys to values of any data type using generics.

Using the instanceof operator to Avoid Unchecked Casts in Java

The instanceof operator is a built-in operator in Java that is used to check whether an object is an instance of a particular class or interface. The operator returns a boolean value - true if the object is an instance of the specified class or interface, and false otherwise.

The instanceof operator is defined as follows:

where object is the object that is being checked, and class/interface is the class or interface that is being tested against.

The instanceof operator can be useful in situations where we need to perform different operations based on the type of an object. It provides a way to check the type of an object at runtime, which can help prevent errors that can occur when performing unchecked casts.

Here are some examples of using the instanceof operator:

In this example, we use the instanceof operator to check whether the object obj is an instance of the String class. If it is, we perform an explicit cast to convert the object to a String and call the toUpperCase() method on it.

In this example, we use the instanceof operator to check whether the List object passed as a parameter is an instance of the ArrayList or LinkedList classes. If it is, we perform an explicit cast to convert the List to the appropriate class and perform different operations on it depending on its type.

Overall, using the instanceof operator can help us write more robust and flexible code. However, it should be used judiciously as it can also make code harder to read and understand.

Using Polymorphism to Avoid Unchecked Casts in Java

Polymorphism is a fundamental concept in object-oriented programming. It refers to the ability of an object or method to take on multiple forms. It allows us to write code that can work with objects of different classes as long as they inherit from a common superclass or implement a common interface. This helps to reduce code duplication and makes our programs more modular and extensible.

Some of the advantages of using polymorphism are:

  • Code reusability: We can write code that can work with multiple objects without having to rewrite it for each specific class.
  • Flexibility: Polymorphism allows us to write code that can adapt to different types of objects at runtime.
  • Ease of maintenance: By using polymorphism, changes made to a superclass or interface are automatically propagated to all its subclasses.

Here are a few examples of how you can use polymorphism to avoid unchecked casts in Java:

Example 1: Shape Hierarchy

In this example, the abstract class Shape defines the common behavior draw(), which is implemented by the concrete classes Circle and Rectangle. By using the Shape reference type, we can invoke the draw() method on different objects without the need for unchecked casts.

Example 2: Polymorphic Method Parameter

In this example, the makeAnimalSound() method accepts an Animal parameter. We can pass different Animal objects, such as Dog or Cat, without the need for unchecked casts. The appropriate implementation of the makeSound() method will be invoked based on the dynamic type of the object.

By utilizing polymorphism in these examples, we achieve type safety and avoid unchecked casts, allowing for cleaner and more flexible code.

Tips to Avoid Unchecked Casts in Java Programs

Unchecked casts in Java programs can introduce runtime errors and compromise type safety. Fortunately, there are several techniques and best practices you can employ to avoid unchecked casts and ensure a more robust codebase. Here are some effective tips to help you write Java programs that are type-safe and free from unchecked cast exceptions.

  • Use generic classes, interfaces, and methods to ensure that your code handles compatible types without relying on casting.
  • Embrace polymorphism by utilizing abstract classes and interfaces, define common behavior and interact with objects through their common type.
  • Check the type of an object using the instanceof operator. This allows you to verify that an object is of the expected type before proceeding with the cast.
  • Favor composition over inheritance, where classes contain references to other classes as instance variables.
  • Familiarize yourself with design patterns that promote type safety and avoid unchecked casts. Patterns such as Factory Method, Builder, and Strategy provide alternative approaches to object creation and behavior, often eliminating the need for explicit casting.
  • Clearly define the contracts and preconditions for your methods. A well-defined contract helps ensure that the method is called with appropriate types, improving overall code safety.
  • Refactor your code and improve its overall design. Look for opportunities to apply the aforementioned tips, such as utilizing generics, polymorphism, or design patterns.

Unchecked casts in Java programs can introduce runtime errors and undermine type safety. By adopting practices like using generics, leveraging polymorphism, checking types with instanceof, favoring composition over inheritance, reviewing design patterns, employing design by contract, and improving code design, you can avoid unchecked casts and enhance the robustness of your Java programs. Prioritizing type safety will result in more reliable code and a smoother development process.

Lightly IDE as a Programming Learning Platform

So, you want to learn a new programming language? Don't worry, it's not like climbing Mount Everest. With Lightly IDE, you'll feel like a coding pro in no time. With Lightly IDE , you don't need to be a coding wizard to start programming.

Uploading image

One of its standout features is its intuitive design, which makes it easy to use even if you're a technologically challenged unicorn. With just a few clicks, you can become a programming wizard in Lightly IDE. It's like magic, but with less wands and more code.

If you're looking to dip your toes into the world of programming or just want to pretend like you know what you're doing, Lightly IDE's online Java compiler is the perfect place to start. It's like a playground for programming geniuses in the making! Even if you're a total newbie, this platform will make you feel like a coding superstar in no time.

Read more: How to Avoid Unchecked Casts in Java Programs

Top comments (0)

pic

Templates let you quickly answer FAQs or store snippets for re-use.

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink .

Hide child comments as well

For further actions, you may consider blocking this person and/or reporting abuse

mrcaption49 profile image

MERN stack application with a MongoDB connection using ES6 syntax

Pranav Bakare - Sep 8

mustafacam profile image

Stateless vs Stateful

Mustafa Çam - Sep 8

sujithvsuresh profile image

NPM Package & CDN for Pagination in Javascript / Nodejs

Sujith V S - Sep 8

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Java Warning “unchecked conversion”

Last updated: January 8, 2024

idea unchecked assignment

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Download the E-book

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode , for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, visit the documentation page .

You can also ask questions and leave feedback on the Azure Container Apps GitHub page .

Java applications have a notoriously slow startup and a long warmup time. The CRaC (Coordinated Restore at Checkpoint) project from OpenJDK can help improve these issues by creating a checkpoint with an application's peak performance and restoring an instance of the JVM to that point.

To take full advantage of this feature, BellSoft provides containers that are highly optimized for Java applications. These package Alpaquita Linux (a full-featured OS optimized for Java and cloud environment) and Liberica JDK (an open-source Java runtime based on OpenJDK).

These ready-to-use images allow us to easily integrate CRaC in a Spring Boot application:

Improve Java application performance with CRaC support

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

To learn more about Java features on Azure Container Apps, you can get started over on the documentation page .

And, you can also ask questions and leave feedback on the Azure Container Apps GitHub page .

Whether you're just starting out or have years of experience, Spring Boot is obviously a great choice for building a web application.

Jmix builds on this highly powerful and mature Boot stack, allowing devs to build and deliver full-stack web applications without having to code the frontend. Quite flexibly as well, from simple web GUI CRUD applications to complex enterprise solutions.

Concretely, The Jmix Platform includes a framework built on top of Spring Boot, JPA, and Vaadin , and comes with Jmix Studio, an IntelliJ IDEA plugin equipped with a suite of developer productivity tools.

The platform comes with interconnected out-of-the-box add-ons for report generation, BPM, maps, instant web app generation from a DB, and quite a bit more:

>> Become an efficient full-stack developer with Jmix

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema .

The way it does all of that is by using a design model , a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

>> Take a look at DBSchema

Get non-trivial analysis (and trivial, too!) suggested right inside your IDE or Git platform so you can code smart, create more value, and stay confident when you push.

Get CodiumAI for free and become part of a community of over 280,000 developers who are already experiencing improved and quicker coding.

Write code that works the way you meant it to:

>> CodiumAI. Meaningful Code Tests for Busy Devs

The AI Assistant to boost Boost your productivity writing unit tests - Machinet AI .

AI is all the rage these days, but for very good reason. The highly practical coding companion, you'll get the power of AI-assisted coding and automated unit test generation . Machinet's Unit Test AI Agent utilizes your own project context to create meaningful unit tests that intelligently aligns with the behavior of the code. And, the AI Chat crafts code and fixes errors with ease, like a helpful sidekick.

Simplify Your Coding Journey with Machinet AI :

>> Install Machinet AI in your IntelliJ

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

Download the E-book

Do JSON right with Jackson

Get the most out of the Apache HTTP Client

Get Started with Apache Maven:

Working on getting your persistence layer right with Spring?

Explore the eBook

Building a REST API with Spring?

Get started with Spring and Spring Boot, through the Learn Spring course:

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Get started with Spring and Spring Boot, through the reference Learn Spring course:

>> LEARN SPRING

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth , to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project .

You can explore the course here:

>> Learn Spring Security

1. Overview

Sometimes, when we compile our Java source, the compiler may print a warning message “unchecked conversion” or “ The expression of type List needs unchecked conversion .”

In this tutorial, we’re going to take a deeper look at the warning message. We’ll discuss what this warning means, what problem it can lead to, and how to solve the potential problem.

2. Enabling the Unchecked Warning Option

Before we look into the “ unchecked conversion ” warning, let’s make sure that the Java compiler option to print this warning has been enabled.

If we’re using the Eclipse JDT Compiler , this warning is enabled by default.

When we’re using the Oracle or OpenJDK javac compiler, we can enable this warning by adding the compiler option -Xlint:unchecked.

Usually, we write and build our Java program in an IDE. We can add this option in the IDE’s compiler settings.

For example, the screenshot below shows how this warning is enabled in JetBrains IntelliJ :

screenshot_2021-01-21_22-27-48

Apache Maven is a widely used tool for building Java applications. We can configure maven-compiler-plugin ‘s compilerArguments  to enable this option:

Now that we’ve confirmed that our Java compiler has this warning option enabled, let’s take a closer look at this warning.

3. When Will the Compiler Warn Us: “unchecked conversion”?

In the previous section, we’ve learned how to enable the warning by setting the Java compiler option. Therefore, it’s not hard to imagine that “unchecked conversion” is a compile-time warning. Usually, we’ll see this warning when assigning a raw type to a parameterized type without type checking.

This assignment is allowed by the compiler because the compiler has to allow this assignment to preserve backward compatibility with older Java versions that do not support generics .

An example will explain it quickly. Let’s say we have a simple method to return a raw type List :

Next, let’s create a test method that calls the method and assigns the result to a variable with the type List<String> :

Now, if we compile our test above, we’ll see the warning from the Java compiler.

Let’s build and test our program using Maven:

As the output above shows, we’ve reproduced the compiler warning.

A typical example in the real world is when we use Java Persistence API ‘s Query.getResultList() method. The method returns a raw type List object.

However, when we try to assign the raw type list to a list with a parameterized type, we’ll see this warning at compile-time:

Moreover, we know that if the compiler warns us of something, it means there are potential risks. If we review the Maven output above, we’ll see that although we get the “ unchecked conversion ” warning, our test method works without any problem.

Naturally, we may want to ask why the compiler warns us with this message and what potential problem we might have?

Next, let’s figure it out.

4. Why Does the Java Compiler Warn Us?

Our test method works well in the previous section, even if we get the “ unchecked conversion ” warning. This is because the getRawList()  method only adds String s into the returned list.

Now, let’s change the method a little bit:

In the new getRawListWithMixedTypes() method, we add a  Date object to the returned list. It’s allowed since we’re returning a raw type list that can contain any types.

Next, let’s create a new test method to call the getRawListWithMixedTypes() method and test the return value:

If we run the test method above, we’ll see the “ unchecked conversion ” warning again, and the test will pass.

This means a ClassCastException has been thrown when we get the Date object by calling get(3) and attempt to cast its type to String.

In the real world, depending on the requirements, sometimes the exception is thrown too late.

For example, we assign  List<String> strList = getRawListWithMixedTypes(). For each String object in strList, suppose that we use it in a pretty complex or expensive process such as external API calls or transactional database operations.

When we encounter the ClassCastException on an element in the strList , some elements have been processed. Thus, the ClassCastException comes too late and may lead to some extra restore or data cleanup processes.

So far, we’ve understood the potential risk behind the  “unchecked conversion” warning. Next, let’s see what we can do to avoid the risk.

5. What Shall We Do With the Warning?

If we’re allowed to change the method that returns raw type collections, we should consider converting it into a generic method. In this way, type safety will be ensured.

However, it’s likely that when we encounter the “ unchecked conversion ” warning, we’re working with a method from an external library. Let’s see what we can do in this case.

5.1. Suppressing the Warning

We can use the annotation SuppressWarnings(“unchecked”) to suppress the warning.

However, we should use the @SuppressWarnings(“unchecked”) annotation only if we’re sure the typecast is safe because it merely suppresses the warning message without any type checking.

Let’s see an example:

As we’ve mentioned earlier, JPA’s Query.getResultList() method returns a raw typed  List object. Based on our query, we’re sure the raw type list can be cast to List<Object[]> . Therefore, we can add the  @SuppressWarnings above the assignment statement to suppress the “ unchecked conversion ” warning.

5.2. Checking Type Conversion Before Using the Raw Type Collection

The warning message “ unchecked conversion ” implies that we should check the conversion before the assignment.

To check the type conversion, we can go through the raw type collection and cast every element to our parameterized type. In this way, if there are some elements with the wrong types, we can get ClassCastException before we really use the element.

We can build a generic method to do the type conversion. Depending on the specific requirement, we can handle ClassCastException in different ways.

First, let’s say we’ll filter out the elements that have the wrong types:

Let’s test the  castList() method above by a unit test method:

When we build and execute the test method, the “ unchecked conversion ” warning is gone, and the test passes.

Of course, if it’s required, we can change our  castList()  method to break out of the type conversion and throw ClassCastException immediately once a wrong type is detected:

As usual, let’s create a unit test method to test the castList2() method:

The test method above will pass if we give it a run. It means that once there’s an element with the wrong type in rawList , the castList2() method will stop the type conversion and throw ClassCastException.

6. Conclusion

In this article, we’ve learned what the “ unchecked conversion ” compiler warning is. Further, we’ve discussed the cause of this warning and how to avoid the potential risk.

As always, the code in this write-up is all available over on GitHub .

Explore the secure, reliable, and high-performance Test Execution Cloud built for scale. Right in your IDE:

Basically, write code that works the way you meant it to.

AI is all the rage these days, but for very good reason. The highly practical coding companion, you'll get the power of AI-assisted coding and automated unit test generation . Machinet's Unit Test AI Agent utilizes your own project context to create meaningful unit tests that intelligently aligns with the behavior of the code.

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

RWS Course Banner

Stack Exchange Network

Stack Exchange network consists of 183 Q&A communities including Stack Overflow , the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

How can I avoid unchecked cast warning in my generic recursive Iterator?

It's somewhat odd that Java's collection framework has no iterator for recursive data structures. Since I needed something like this, I wrote my own. First off, I need recursive elements:

And then an Iterator :

That code works very well, but I do get a warning from the compiler in the next() method in the line I marked. It is clear to me why this warning occurs, but I have not come up with any solution on how to solve the problem without this warning (save suppressing the warning). Any ideas?

Jamal's user avatar

  • \$\begingroup\$ I don't think you can. Java's generics doesn't allow compound types such as Iterator<T | RecursiveElement<T>> . \$\endgroup\$ –  David Harkness Commented Apr 16, 2014 at 17:39

2 Answers 2

I don't think you can do anything about this. You have to cast here, and in the process you lose all information about the type parameter: The compiler can't know that if you have a RecursiveElement , it's always a RecursiveElement<T> , and "thanks" to type erasure it can't check the runtime type.

Landei's user avatar

  • 1 \$\begingroup\$ As @JvR points out, the problem isn't type erasure but the fact that each collection may contain both items and other collections. This necessitates a cast from T to RecursiveElement<T> which the compiler does not like (rightly so). \$\endgroup\$ –  David Harkness Commented Apr 16, 2014 at 17:34

The type checker is marking a real issue here. To visualise this, replace your RecursiveElement<T> with a generic Iterable<T> , which provides identical type guarantees.

When different layers mix different types, RecursiveIterator unfortunately breaks down. Here is an example:

Your options are:

  • try to push the responsibility of recursing to your actual elements;
  • try some wizardry to accept a finite amount of recursion by adding type variables;
  • drop type safety and wrap in a filtering iterator.

JvR's user avatar

Your Answer

Sign up or log in, post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged java recursion casting iterator or ask your own question .

  • The Overflow Blog
  • The hidden cost of speed
  • The creator of Jenkins discusses CI/CD and balancing business with open source
  • Featured on Meta
  • Announcing a change to the data-dump process
  • Bringing clarity to status tag usage on meta sites

Hot Network Questions

  • Improper Subpanel Concerns
  • Is reading sheet music difficult?
  • How to truncate text in latex?
  • Why does the guardian who admits guilt pay more than when his guilt is established by witnesses?
  • Can population variance from multiple studies be averaged to use for a sample size calculation?
  • How to extrude a profile along multiple curves keeping tilt equal between instances and sane normals?
  • Is it suspicious to write about research with no accompanying letter from a PI for PhD admissions?
  • Is the 2024 Ukrainian invasion of the Kursk region the first time since WW2 Russia was invaded?
  • Can ago be used with since?
  • Generate all the free polyominoes who's width and height is no larger than 8
  • Flats on gravel with GP5000 - what am I doing wrong?
  • Where did they get facehuggers from?
  • What prevents random software installation popups from mis-interpreting our consents
  • How to simplify input to a table with many columns?
  • What happens on a CAN bus when impedance is too low?
  • Where is this railroad track as seen in Rocky II during the training montage?
  • What is the Kronecker product of two 1D vectors?
  • What does こんなところ refer to here
  • Visuallizing complex vectors?
  • Textile Innovations of Pachyderms: Clothing Type
  • What is the optimal number of function evaluations?
  • Is this host and 'parasite' interaction feasible?
  • Setting the desired kernel in GRUB menu
  • Topos notions coming from topology and uniqueness of generalizations

idea unchecked assignment

IntelliJ IDEA 2024.2 Help

Change inspection severity.

Inspection severity levels indicate how seriously the detected code problems affect your project. In IntelliJ IDEA, there is a set of predefined severity levels:

Syntax errors

Code fragments that might produce bugs or require enhancement

Code fragments that can be improved or optimized (redundant code, duplicated code fragments, and so on)

Problems that come from an external build server, for example, from TeamCity

Grammar mistakes. This severity comes from the bundled Grazie Lite plugin. For more information, refer to Grammar .

Spelling mistakes and typos. For more information, refer to Spellchecking .

Code fragments that can be improved. This severity level is not marked on the error stripe and does not have a default highlighting style, but you can select one from the list of existing styles or configure your own.

No code highlighting, but you can invoke fixes by pressing Alt+Enter .

For every severity, you can configure its own highlighting style in the editor.

Severity levels are designed to indicate problems, they don't have any impact on the code execution: if you change the severity for spelling mistakes from Typo to Error , this won't affect the execution of your application.

Change inspection severity in all scopes

Press Ctrl+Alt+S to open settings and then select Editor | Inspections .

Select the profile that you want to modify and then choose an inspection from the list. Make sure that it is enabled.

From the Severity list, select a new severity level. You can also right-click the inspection and select the severity level from the context menu.

If the necessary severity is not on the list, click Edit Severities to create a new one .

From the Highlighting in editor list, select the style that you want to use to highlight code fragments in the editor.

Select Edit Highlighting to modify the existing styles .

Selecting severity level for an inspection

Apply the changes and close the dialog.

The modified inspection will now have the new severity level in the selected profile.

Change inspection severity in specific scopes

From the Scope list, select the scope for which you want to change the severity.

IntelliJ IDEA shows severities for two scopes: the selected one and Everywhere else .

Select the necessary severity level from the Severity list.

Changing inspection severity by scope

Additionally, from the Highlighting in editor list, select the style that you want to use to highlight code fragments in the editor.

If you enable an inspection in multiple scopes, and files in these scopes match, the IDE will process these scopes according to their order in the list. For more information, refer to Change the order of scopes .

Configure error highlighting

Press Ctrl+Alt+S to open the IDE settings and select Editor | Color Scheme | General .

You can also configure highlighting from inspection settings: go to Editor | Inspections , click any enabled inspection, and from the Highlighting in editor list, select Edit Highlighting .

From the Errors and Warnings list, select the style that you want to modify.

Configure the new highlighting rules using the options on the right. To preview the changes before applying them, use the preview section at the bottom of the dialog.

Changing error highlighting

Create a new severity level

Select the profile in which you want to create a new severity level.

Click any inspection and select Edit severities from the list of severity levels.

Click OK when finished.

Creating a new severity

@SuppressWarnings versus //noinspection

Avatar

I am using IDEA 8.1.4.  I have unchecked warnings turned on in my Errors settings. When I have an unchecked warning and I click the option to "Suppress for Statement", sometimes IDEA inserts "//noinspection unchecked" before the statment and sometimes it inserts "@SuppressWarnings({"unchecked"})" at the beginning of the statement.  I don't understand why it behaves differently in different classes.  Is there a way that I can tell IDEA to always insert the annotation @SuppressWarnings?

I may have an answer to my own question.  I am a newbie when it comes to using Java annotations so I am just reporting my observations. If I have a statement like this: List<String> a = (List<String>)b.getSomething(); IDEA will insert @SuppressWarnings: @SuppressWarnings({"unchecked"}) List<String> a = (List<String>)b.getSomething(); If I have a statement like this: doSomething((List<String>)b.getSomething()); IDEA will disable the warning like this: //noinspection unchecked doSomething((List<String>)b.getSomething()); At the statement level, it looks like I can only apply the annotation to an assignment of a local variable.  So I have to rewrite my statement to be something more like this: @SuppressWarnings({"unchecked"}) List<String> a = (List<String>)b.getSomething(); doSomething(a);

Avatar

ASAIK @SuppressWarnings annotation only works on Class and Method level (plus some others by definition, but not on a statement @see ElementType). Idea adds the possibility of supressing inspection alerts on a per statement level, which is very nice. But they had to introduce something new, and it's the //noinspection "tag". cheers On 2009-11-26 07:06:58 +0900, Ed Hager < [email protected] > said:

I am using IDEA 8.1.4.  I have unchecked warnings turned on in my Errors settings. When I have an unchecked warning and I click the option to "Suppress for Statement", sometimes IDEA inserts "//noinspection unchecked" before the statment and sometimes it inserts "@SuppressWarnings({"unchecked"})" at the beginning of the statement.   I don't understand why it behaves differently in different classes.  Is there a way that I can tell IDEA to always insert the annotation @SuppressWarnings? --- Original message URL: http://www.jetbrains.net/devnet/message/5250982#5250982

Avatar

very grateful for your help

Please sign in to leave a comment.

Get the Reddit app

Resources for learning Java

Question regarding "Unchecked call" warning.

Am I correct in understanding that an " unchecked call " is the compiler warning me that I have an unaddressed exception that needs to be added? At least that was my initial thought. I wrapped the code block in question with try/catch, but the warnings persist. The specific warnings I am getting is:

The code in question is intended to import a simple CSV to java beans. The pojo field names map perfectly to the CSV header names. I am using the openCSV library, and the code they suggest in their documentation for this seemed pretty simple at first glance.

Here's the pojo snap shot I am using:

I'm attempting to import the CSV within a constructor in this class below. I'm using this project to learn more about the DAO design pattern. Very new to this so perhaps your guidance can move me along:

My IDE (Intellij IDEA) barks out the aforementioned warnings with what I provided. Can someone lead me down the right trail? Appreciate any time spent on assisting me.

EDIT:: In case you need the Dao interface I used, here it is:

By continuing, you agree to our User Agreement and acknowledge that you understand the Privacy Policy .

Enter the 6-digit code from your authenticator app

You’ve set up two-factor authentication for this account.

Enter a 6-digit backup code

Create your username and password.

Reddit is anonymous, so your username is what you’ll go by here. Choose wisely—because once you get a name, you can’t change it.

Reset your password

Enter your email address or username and we’ll send you a link to reset your password

Check your inbox

An email with a link to reset your password was sent to the email address associated with your account

Choose a Reddit account to continue

w3docs logo

  • Password Generator
  • HTML Editor
  • HTML Encoder
  • JSON Beautifier
  • CSS Beautifier
  • Markdown Convertor
  • Find the Closest Tailwind CSS Color
  • Phrase encrypt / decrypt
  • Browser Feature Detection
  • Number convertor
  • CSS Maker text shadow
  • CSS Maker Text Rotation
  • CSS Maker Out Line
  • CSS Maker RGB Shadow
  • CSS Maker Transform
  • CSS Maker Font Face
  • Color Picker
  • Colors CMYK
  • Color mixer
  • Color Converter
  • Color Contrast Analyzer
  • Color Gradient
  • String Length Calculator
  • MD5 Hash Generator
  • Sha256 Hash Generator
  • String Reverse
  • URL Encoder
  • URL Decoder
  • Base 64 Encoder
  • Base 64 Decoder
  • Extra Spaces Remover
  • String to Lowercase
  • String to Uppercase
  • Word Count Calculator
  • Empty Lines Remover
  • HTML Tags Remover
  • Binary to Hex
  • Hex to Binary
  • Rot13 Transform on a String
  • String to Binary
  • Duplicate Lines Remover

How do I address unchecked cast warnings?

An unchecked cast warning in Java occurs when the compiler cannot verify that a cast is safe at compile time. This can happen when you are casting an object to a type that is not a supertype or subtype of the object's actual type.

To address an unchecked cast warning, you can either suppress the warning using the @SuppressWarnings("unchecked") annotation, or you can modify your code to ensure that the cast is safe.

To suppress the warning, you can add the @SuppressWarnings annotation to the method or block of code that contains the unchecked cast. For example:

To ensure that the cast is safe, you can modify your code to ensure that the object being cast is actually an instance of the target type. For example:

I hope this helps! Let me know if you have any questions.

Related Resources

  • How do I read / convert an InputStream into a String in Java?
  • How do I generate random integers within a specific range in Java?
  • How do I efficiently iterate over each entry in a Java Map?
  • How can I create a memory leak in Java?
  • How do I convert a String to an int in Java?
  • How do I call one constructor from another in Java?
  • HTML Basics
  • Javascript Basics
  • TypeScript Basics
  • React Basics
  • Angular Basics
  • Sass Basics
  • Vue.js Basics
  • Python Basics
  • Java Basics
  • NodeJS Basics

【Intellij IDEA系列】IDEA泛型处理Unchecked assignment:'java.util.Map' to 'java.util.Map&lt;>'

idea unchecked assignment

在 intellij idea 编辑器中,把一个Map类型的数据,强制类型转换的时候。

在中不想看到代码的如下警告的解决方法: 警告信息------------- 简单警告: Unchecked cast: 'java.lang.Object' to 'java.util.List<java.lang.Object>' 或者Unchecked assignment:'java.util.Map' to 'java.util.Map<>' 点开查看详细警告: Unchecked cast: 'java.lang.Object' to 'java.util.List<java.lang.Object>' less... (Ctrl+F1)   Signals places where an unchecked warning is issued by the compiler, for example: void f(HashMap map) {   map.put("key", "value");   }      Hint: Pass -Xlint:unchecked to javac to get more details. 去除代码警告的解决方案: 在此方法上面或者那个强制类型转换的上面加上如下一句话。

@SuppressWarnings("unchecked")

java最后一个注解@SuppressWarnings

idea unchecked assignment

请填写红包祝福语或标题

idea unchecked assignment

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。 2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

idea unchecked assignment

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

How do I address unchecked cast warnings?

Eclipse is giving me a warning of the following form:

Type safety: Unchecked cast from Object to HashMap

This is from a call to an API that I have no control over which returns Object:

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:

Problem was elsewhere when you tried to use the hash you'd get warnings:

Chris Stillwell's user avatar

  • If you're using HttpSession like that, check out Brian Goetz's article on the subject: ibm.com/developerworks/library/j-jtp09238.html –  Tom Hawtin - tackline Commented Feb 4, 2009 at 15:33
  • If an unchecked cast is unavoidable, a good idea is to tightly couple it with something that logically represents it's type (like an enum or even instances of Class<T> ), so you can glance at it and know it's safe. –  Philip Guin Commented Jul 17, 2012 at 2:39
  • 4 Related/dupe: Type safety: Unchecked cast –  blahdiblah Commented Mar 11, 2013 at 19:15
  • 3 possible duplicate of Type safety: Unchecked cast –  Raedwald Commented May 17, 2013 at 12:54
  • 1 I would add, I found I could only add @SuppressWarnings("unchecked") at the method level that contains the offending code. So I broke the code out to a routine where I had to do this. I always thought you could do this immediately above the line in question. –  JGFMK Commented Jan 15, 2020 at 17:23

22 Answers 22

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 Javadocs , it can go on local variables; this way, it doesn't even affect the entire method.

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.

Michael Myers's user avatar

  • 126 +1 for pointing out that it can go on local variables. Eclipse only offers to add it to the whole method... –  thSoft Commented May 26, 2010 at 11:05
  • 17 Eclipse 3.7 (Indigo) has support for adding unchecked to local variables. –  sweetfa Commented Feb 1, 2012 at 0:11
  • 80 The warning is not just because the compiler does not know that the cast is safe. For example String s = (String) new Object() ; gets no warning, even though the compiler does not know that the cast is safe. The warning is because the compiler (a) does not know that the cast is safe AND (b) will not generate a complete run-time check at the point of the cast. There will be a check that it is a Hashmap , but there will not be a check that it is a HashMap<String,String> . –  Theodore Norvell Commented Feb 28, 2013 at 16:46
  • 10 Sadly, even though the cast and the warning are for the assignment , the annotation has to go on the variable declaration... So if the declaration and the assignment are in different places (say, outside and inside a 'try' block respectively), Eclipse now generates two warnings: the original unchecked cast, and a new "unnecessary annotation" diagnostic. –  Ti Strga Commented Jul 31, 2013 at 16:46
  • 6 A workaround for the annotation needing to accompany the local variable declaration, which may be in a different scope on a different line than the actual cast, is to create a local variable within the scope of the cast specifically to perform the cast on the same line as the declaration. Then assign this variable to the actual variable which is in a different scope. This is the method I used also to suppress the warning on a cast to an instance variable as the annotation can't be applied here either. –  Jeff Lockhart Commented Jun 11, 2015 at 5:25

Unfortunately, there are no great options here. Remember, the goal of all of this is to preserve type safety. " Java Generics " offers a solution for dealing with non-genericized legacy libraries, and there is one in particular called the "empty loop technique" in section 8.2. Basically, make the unsafe cast, and suppress the warning. Then loop through the map like this:

If an unexpected type is encountered, you will get a runtime ClassCastException , but at least it will happen close to the source of the problem.

Abdollah's user avatar

  • 7 Much, much better answer than the one provided by skiphoppy, for multiple reasons: 1) This code is much, much shorter. 2) This code actually throws ClassCastException as expected. 3) This code does not do a full copy of the source map. 4) The loops can be easily wrapped in a separate method used in an assert, which would easily remove the performance hit in production code. –  Stijn de Witt Commented Jun 6, 2014 at 19:28
  • 6 Isn't there a possibility that the Java compiler or the JIT compiler will decide that the results of this code is not being used and "optimize" it by not compiling it? –  RenniePet Commented Sep 22, 2014 at 23:13
  • 1 It's not really dead code if it can potentially throw an exception. I don't know enough about the JIT compilers in use today to guarantee that none of them would mess this up, but I feel fairly confident in saying that they're not supposed to. –  GrandOpener Commented May 29, 2016 at 5:19
  • 3 This still doesn't guarantee type safety as the same map is still being used. It might have originally been defined as Map<Object,Object> that just happens to have Strings and Numbers in and then later on if a Boolean is added then the user of this code will get a confusing and rather hard to trace surprise. The only way to guarantee type safety is to copy it into a new map with the requested type that guarantees whats allowed to go into it. –  user2219808 Commented Aug 28, 2018 at 10:19

Wow; 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.

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?

informatik01's user avatar

  • 72 this stuff is confusing, but i think all you have done is traded ClassCastExceptions for AssertionErrors. –  Dustin Getz Commented Mar 1, 2011 at 23:00
  • 64 Dude, that's definitely not worth it! Imagine the poor sap who has to come back and modify some code with that mess in there. I don't like suppressing warnings, but I think that's the lesser evil here. –  Craig B Commented Dec 19, 2011 at 2:21
  • 75 It's not just that it's an ugly, confusing, mess (when you can't avoid one copious comments can walk the maintenance programmer through it); iterating over every element in the collection turns the cast from an O(1) to an O(n) operation. This is something that would never be expected and can easily turn into a horrible mystery slowdown. –  Dan Is Fiddling By Firelight Commented Sep 10, 2012 at 20:46
  • 23 @DanNeely you are correct. In general, nobody should ever do this. –  skiphoppy Commented Dec 7, 2012 at 17:21
  • 4 Some comments...the method signature is wrong because it doesn't "cast" a damn thing, it just copies the existing map into a new map. Also, it could probably be refactored to accept any map, and not rely on HashMap itself (i.e. take Map and return Map in the method signature, even if the internal type is HashMap). You don't really need to do the casting or the storage into a new map - if you don't throw an assertion error, then the given map has the right types inside it as of right now. Creating a new map with the generic types is pointless as you could still make it raw and put whatever. –  MetroidFan2002 Commented Mar 6, 2014 at 20:22

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.

Dave's user avatar

  • 1 Ah, thanks for this :) I was getting a " uses unchecked or unsafe operations. " error in javac , but adding @SuppressWarnings("unchecked") made Eclipse unhappy, claiming the suppression was unnecessary. Unchecking this box makes Eclipse and javac behave the same, which is what I wanted. Explicitly suppressing the warning in the code is much clearer than suppressing it everywhere inside Eclipse. –  dimo414 Commented Feb 8, 2015 at 19:48

You can create a utility class like the following, and use it to suppress the unchecked warning.

You can use it as follows:

Some more discussion about this is here: http://cleveralias.blogs.com/thought_spearmints/2006/01/suppresswarning.html

Esko Luontola's user avatar

  • 22 not downvoting, but the wrapper adds precisely nothing over just suppressing the warning. –  Dustin Getz Commented Mar 1, 2011 at 23:10
  • 4 +1 as this solution does not waste precious code lines. –  Tino Commented Jul 31, 2014 at 22:31
  • 1 @ErikE Too much. Much more expensive bigger and higher-resolution monitors to give room to all those wasted lines, a bigger desk to put all those bigger monitors onto, a bigger room to put the bigger desk into, and an insightful boss .. –  Tino Commented Aug 30, 2018 at 14:54
  • 1 @ErikE Scrollbars, for vi ? Are you kidding? –  Tino Commented Aug 30, 2018 at 15:01

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.

Dustin Getz's user avatar

Here is a shortened example that avoids the "unchecked cast" warning by employing two strategies mentioned in other answers.

Pass down the Class of the type of interest as a parameter at runtime ( Class<T> inputElementClazz ). Then you can use: inputElementClazz.cast(anyObject);

For type casting of a Collection, use the wildcard ? instead of a generic type T to acknowledge that you indeed do not know what kind of objects to expect from the legacy code ( Collection<?> unknownTypeCollection ). After all, this is what the "unchecked cast" warning wants to tell us: We cannot be sure that we get a Collection<T> , so the honest thing to do is to use a Collection<?> . If absolutely needed, a collection of a known type can still be built ( Collection<T> knownTypeCollection ).

The legacy code interfaced in the example below has an attribute "input" in the StructuredViewer (StructuredViewer is a tree or table widget, "input" is the data model behind it). This "input" could be any kind of Java Collection.

Naturally, the code above can give runtime errors if we use the legacy code with the wrong data types (e.g. if we set an array as the "input" of the StructuredViewer instead of a Java Collection).

Example of calling the method:

Iharob Al Asimi's user avatar

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:

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.

Joachim Sauer's user avatar

  • This is really helpful answer. –  GPrathap Commented Nov 18, 2015 at 6:48

In Android Studio if you want to disable inspection you can use:

Jan Moravec's user avatar

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:

  • 1 Awesome; I think I can combine that with my answer to parameterize it and avoid having to suppress warnings altogether! –  skiphoppy Commented Feb 4, 2009 at 0:47
  • 1 +1 probably best recipe (easy to understand and maintain) to do it safely with runtime checks –  Tino Commented Jul 31, 2014 at 22:37

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:

Using the utility is much cleaner, and it's still obvious what you are doing:

NOTE: I feel its important to add that sometimes the warning really means you are doing something wrong like :

What the compiler is telling you is that this cast will NOT be checked at runtime, so no runtime error will be raised until you try to access the data in the generic container.

Gonen I's user avatar

Warning suppression is not a solution. You should not be doing two level casting in one statement.

abbas's user avatar

  • 1 His five-year-old question? Do you need to do that much work? Given Java has type erasure the second hashmap should be identical to the first at runtime; I think it'd be more efficient and avoid the copy if you just iterated through the entries and verified that they were all instances of strings. Or, TBH, inspect the source of the servlet JAR you're using and verify it only ever puts strings. –  Rup Commented Mar 13, 2015 at 14:35
  • 1 To this day I am seeing this warning in projects. His problem was not verification of the type, but a warning caused by a "put" into an uncasted map. –  abbas Commented Mar 14, 2015 at 7:37

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.

phihag's user avatar

  • 2 I'm pretty sure that switching to Map in this case would not change anything, but thanks for the programming tip, which may change the way I do some things, for the better. The source of the object is an API I have no control over (code added). –  skiphoppy Commented Feb 3, 2009 at 22:19

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.

Fortyrunner's user avatar

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...

jfreundo's user avatar

  • key.isAssignableFrom(e.getKey().getClass()) can be written as key.isInstance(e.getKey()) –  user102008 Commented Aug 16, 2011 at 0:36

A quick guess if you post your code can say for sure but you might have done something along the lines of

which will produce the warning when you need to do

it might be worth looking at

Generics in the Java Programming Language

if your unfamiliar with what needs to be done.

Mark Davidson's user avatar

  • 1 Unfortunately it's not that easy a situation. Code added. –  skiphoppy Commented Feb 3, 2009 at 22:19
  • 1 I came here looking for an answer to a slightly different problem: and you told me exactly what I needed! Thanks! –  staticsan Commented Sep 17, 2010 at 0:21

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:

*Except too many levels of indirection.

Tom Hawtin - tackline's user avatar

  • 1 The quote is attributed to the late Professor David Wheeler. en.wikipedia.org/wiki/… –  Stephen C Commented Nov 19, 2013 at 5:56

Here's one way I handle this when I override the equals() operation.

This seems to work in Java 8 (even compiled with -Xlint:unchecked )

Jim Daehn's user avatar

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

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.

Luke 10X's user avatar

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.

mike rodent's user avatar

  • the fact that you don't have comment privileges do not allow you to edit others' answers to add your comments; you edit others' answers to improve them in formatting, syntax, ..., not to add your opinion on them. When you'll reach 50 rep you'll be able to comment everywhere, in the meantime I'm quite sure you can resist (or, if you really can't, write your comments to existing answers in your post). (note for others: I write this because I saw - and rejected - his proposed comments-edits to other posts in the moderation tools) –  Matteo Italia Commented Mar 25, 2011 at 1:03

Just typecheck it before you cast it.

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.

Rick's user avatar

  • 8 Unfortunately, generics render that impossible. It's not just a HashMap, it's a HashMap with type information. And if I eliminate that information, I'll just push the warnings to elsewhere. –  skiphoppy Commented Feb 3, 2009 at 22:23

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.

Marc Riehm's user avatar

  • 11 May I ask why? globally disabling a warning will hide other places where this issue is real. adding a @SuppressWarnings doesn't make the code unreadable at all. –  MByD Commented Feb 28, 2013 at 20:49

Not the answer you're looking for? Browse other questions tagged java generics warnings or ask your own question .

  • The Overflow Blog
  • The hidden cost of speed
  • The creator of Jenkins discusses CI/CD and balancing business with open source
  • Featured on Meta
  • Announcing a change to the data-dump process
  • Bringing clarity to status tag usage on meta sites
  • What does a new user need in a homepage experience on Stack Overflow?
  • Feedback requested: How do you use tag hover descriptions for curating and do...
  • Staging Ground Reviewer Motivation

Hot Network Questions

  • How high does the ocean tide rise every 90 minutes due to the gravitational pull of the space station?
  • Circuit that turns two LEDs off/on depending on switch
  • Humans are forbidden from using complex computers. But what defines a complex computer?
  • What is the translation of this quote by Plato?
  • Improper Subpanel Concerns
  • Power of Toffoli vs T in quantum logic
  • Is the 2024 Ukrainian invasion of the Kursk region the first time since WW2 Russia was invaded?
  • Pólya trees counted efficiently
  • The head of a screw is missing on one side of the spigot outdoor
  • Can the planet Neptune be seen from Earth with binoculars?
  • Can you move between an attack and the attack granted by Horde Breaker?
  • What is the optimal number of function evaluations?
  • What was the typical amount of disk storage for a mainframe installation in the 1980s?
  • Textile Innovations of Pachyderms: Clothing Type
  • Generating function for A261041
  • Are fuel efficiency charts available for mainstream engines?
  • Starting with 2014 "+" signs and 2015 "−" signs, you delete signs until one remains. What’s left?
  • What is the resulting inititive order when a readied action triggers after a summoned monsters action but before the summoner?
  • Is it suspicious to write about research with no accompanying letter from a PI for PhD admissions?
  • What does こんなところ refer to here
  • Which volcano is more hazardous? Mount Rainier or Mount Hood?
  • Minimal permutation degree of the dihedral group
  • What are the steps to write a book?
  • How to fold or expand the wingtips on Boeing 777?

idea unchecked assignment

Unchecked assignment: ‘java.util.List’ to ‘java.util.Collection’

idea unchecked assignment

I am having an adapter where i have two lists one list is for InvestorsList where it comes with the list of investors and the other list is called investorListFull which is used to filter results when searching.

Below is how i have declared the lists

Below is how the lists are assigned in my recyclerview adapter constructor

Below is how i am filtering results in investors list

I am getting Unchecked assignment error in publish results investorList.addAll((List) filterResults.values);

Advertisement

I am getting Unchecked cast error in publish results investorList.addAll((List) filterResults.values);

That’s because you’re doing an unchecked cast. Actually, you’re doing both a checked and an unchecked cast there.

(List) filterResults.values is a checked cast. This means that the Java compiler will insert a checkcast instruction into the bytecode to ensure that filterResults.values (an Object ) really is an instance of List .

However, investorList.addAll expects a List<Investor> , not a List . List is a raw type . You can pass a raw-typed List to a method expecting a List<Something> ; but this is flagged as unsafe because the compiler can’t guarantee that it really is a List<Something> – there is nothing about the List that makes it a “list of Something “, because of type erasure. The compiler can insert a checkcast instruction to ensure it’s a List ; but not one to ensure it’s a List<Something> : this fact is unchecked .

What it’s saying with the warning is “there may be something wrong here; I just can’t prove it’s wrong”. If you know for sure – by construction – that filterResults.values really is a List<Investor> , casting it to List<Investor> is safe.

You should write the line as:

Note that this will still give you an unchecked cast warning, because it’s still an unchecked cast – you just avoid the use of raw types as well.

If you feel confident in suppressing the warning, declare a variable, so you can suppress the warning specifically on that variable, rather than having to add the suppression to the method or class; and document why it’s safe to suppress there:

IMAGES

  1. 【Intellij IDEA系列】IDEA泛型处理Unchecked assignment:'java.util.Map' to 'java

    idea unchecked assignment

  2. How to View Unchecked Assignment || How to Check Assignment and Return to Students || APS || APSACAS

    idea unchecked assignment

  3. Assignment 3 unchecked 2nd

    idea unchecked assignment

  4. Create an easy to edit, weekly assignment sheet for homeschoolers. A

    idea unchecked assignment

  5. fastjson对泛型的反序列化_unchecked assignment: 'java.util.list' to 'java.ut-CSDN博客

    idea unchecked assignment

  6. idea警告:Unchecked cast: 'java.lang.Object' to 'java.util.List

    idea unchecked assignment

VIDEO

  1. easy assignment front page idea✨ #yt #art #frontpage #drawing #ytvideoviral#mineesctaftsfair

  2. #easyfronthandmehndidesign#yt#assignmentcoverpage#desing#assignment #idea#simple#shortsdrawing#sh

  3. #Simple assignment cover idea.💛

  4. A simple assignment front page idea #diy # assignment

  5. Easy assignment cover idea. 💛

  6. # Easy assignment cover idea. 💛

COMMENTS

  1. Intellij Warning

    Java Generics, how to avoid unchecked assignment warning when using class hierarchy? Intellij is giving me the warning below. Not sure how to resolve it, or even if I need to resolve it. The warning details says it only applies to JDK 5, and I am using 6. I am wondering if I need to respond to this, and if so, how? Method call causing warning

  2. Inappropriate 'unchecked assignment' warning in IntelliJ

    Unchecked assignment: java.util.List to java.util.List<com.sencha.gxt.data.shared.loader.FilterConfig> ... Correct way to add external jars (lib/*.jar) to an IntelliJ IDEA project. 784. IntelliJ inspection gives "Cannot resolve symbol" but still compiles code. 680. IntelliJ show JavaDocs tooltip on mouse over. 358.

  3. Java Warning "Unchecked Cast"

    Java Warning "Unchecked Cast"

  4. How to Avoid Unchecked Casts in Java Programs

    Unchecked cast refers to the process of converting a variable of one data type to another data type without checks by the Java compiler. This operation is unchecked because the compiler does not verify if the operation is valid or safe. Unchecked casts can lead to runtime errors, such as ClassCastException, when the program tries to assign an ...

  5. Unchecked warning

    Unchecked warning. Reports code on which an unchecked warning will be issued by the javac compiler. ... Ignore unchecked assignment. Not selected. Ignore unchecked generics array creation for vararg parameter. ... Not selected. Inspection Details. By default bundled with: IntelliJ IDEA 2024.1, Qodana for JVM 2024.1, Can be installed with plugin ...

  6. Taming a Silly Generic Warning

    Unchecked assignment: java.util.List to java.util.List<String> Unfortunately, there's no way to fix that problem. I've tried adding <String> before the dot and after, but neither works.

  7. Java Warning "unchecked conversion"

    Java Warning "unchecked conversion"

  8. Disable and suppress inspections

    Disable and suppress inspections - IntelliJ IDEA

  9. java

    The type checker is marking a real issue here. To visualise this, replace your RecursiveElement<T> with a generic Iterable<T>, which provides identical type guarantees.. When different layers mix different types, RecursiveIterator unfortunately breaks down. Here is an example:

  10. How to Avoid Unchecked Casts in Java Programs

    How to Avoid Unchecked Casts in Java Programs

  11. Change inspection severity

    Change inspection severity in specific scopes . Press Ctrl Alt 0S to open settings and then select Editor | Inspections. Select the profile that you want to modify and then choose an inspection from the list. Make sure that it is enabled. From the Scope list, select the scope for which you want to change the severity.

  12. How to fix this unchecked assignment warning?

    Answer. Since ReflectionHelper.getClasses returns an array of the raw type Class, the local-variable type inference will use this raw type Class[] for var blks and in turn, the raw type Class for var c. Using the raw type Class for c allows passing it to registerSubtype(Class<? extends Block>), without any check, but not without any warning.

  13. @SuppressWarnings versus //noinspection

    IDEA will disable the warning like this: //noinspection unchecked. doSomething ( (List<String>)b.getSomething ()); At the statement level, it looks like I can only apply the annotation to an assignment of a local variable. So I have to rewrite my statement to be something more like this: @SuppressWarnings ( {"unchecked"}) List<String> a = (List ...

  14. unchecked assignment warning on generic array allocation

    {{ (>_<) }}This version of your browser is not supported. Try upgrading to the latest stable version. Something went seriously wrong.

  15. Question regarding "Unchecked call" warning. : r/learnjava

    Warning:(20, 39) Unchecked assignment: 'java.util.List' to 'java.util.List<com.flowplanner.persistence.Transaction>'. Reason: 'new CsvToBeanBuilder(fr).withType(Transaction.class).build()' has raw type, so result of parse is erased. The code in question is intended to import a simple CSV to java beans. The pojo field names map perfectly to the ...

  16. How do I address unchecked cast warnings?

    An unchecked cast warning in Java occurs when the compiler cannot verify that a cast is safe at compile time. This can happen when you are casting an object to a type that is not a supertype or subtype of the object's actual type. To address an unchecked cast warning, you can either suppress the warning using the @SuppressWarnings("unchecked ...

  17. 【Intellij IDEA系列】IDEA泛型处理Unchecked assignment:'java.util.Map' to 'java

    在Java编程中,异常处理是一项重要的技术,用于处理程序在运行时可能出现的错误情况。异常分为两种主要类型:Checked异常和Unchecked异常。本文将深入探讨它们的区别、使用场景以及最佳实践。通过本文的介绍,我们深入了解了Java中Checked异常和Unchecked异常的区别、使用场景以及最佳实践。

  18. How do I address unchecked cast warnings?

    How do I address unchecked cast warnings?

  19. Unchecked assignment: 'java.util.List' to 'java.util.Collection'

    Actually, you're doing both a checked and an unchecked cast there. (List) filterResults.values is a checked cast. This means that the Java compiler will insert a checkcast instruction into the bytecode to ensure that filterResults.values (an Object) really is an instance of List. However, investorList.addAll expects a List<Investor>, not a ...