# Remove Redundant Type Casts

# Description

The rule first searches the next type-cast operation. If the expression is casted to a type which already is exactly the type of the expression, then the type casting expression is removed. Additionally, also parentheses involved in the cast operation will be removed if they are not necessary any more. This rule regards two types as exactly the same only when both types have also exactly the same generic arguments.

# Benefits

This rule increases readability by removing redundant code.

# Tags

# Code Changes

# Type cast on string literal

Pre

((String)"HelloWorld").charAt(0);

Post

"HelloWorld".charAt(0);

# Type cast on string variable

Pre

String helloWorld = "HelloWorld";
((String)helloWorld).charAt(0);

Post

String helloWorld = "HelloWorld";
helloWorld.charAt(0);

# Type cast on List of String

Pre

List<String> l = new ArrayList<>();
((List<String>)l).add("value1");

Post

List<String> l = new ArrayList<>();
l.add("value1");

# Type cast combined with unnecessary parentheses

Pre

long x = ((((long)((long)((100 + 200L)) + 300))));

Post

long x = ((100 + 200L)) + 300;

# Limitations

# Casting expressions using wild cards

It is not safe to remove type casts containing wild cards (?). E.g.:

Not Transformed

List<?> l = new ArrayList<>();
((List<?>)l).size();

# Casting lambda expressions to Object

Lambda expressions are not subtypes of Object and therefore implicit casting is not possible. E.g.:

Not Transformed

Object object = (Supplier<String>) () -> "";

🛠️ Auto-refactor Available

You can auto-refactor this with jSparrow.
Drop this button to your Eclipse IDE workspace to install jSparrow for free:

Drag to your running Eclipse* workspace. *Requires Eclipse Marketplace Client

Need help? Check out our installation guide.

# Properties

Property Value
Rule ID RemoveRedundantTypeCast
First seen in jSparrow version 3.15.0
Minimum Java version 1.1
Remediation cost 5 min
Links