DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
  1. DZone
  2. Coding
  3. Java
  4. A Look at Arrays and Generics in Java

A Look at Arrays and Generics in Java

Check out this post on using both arrays and generics in the same Java project and why it isn't a good idea to use these methods together.

Debapriya Biswas user avatar by
Debapriya Biswas
·
Aug. 20, 18 · Tutorial
Like (8)
Save
Tweet
Share
13.02K Views

Join the DZone community and get the full member experience.

Join For Free

 In this post, I will attempt to explain the problem of using arrays and generics in Java. Let's get started!

Generics was first introduced in JDK5, and all its following libraries have continued to include generics. For a brief introduction on generics, I want to point out that generics provide compile-time type safety. Generics is tough, and I will not dive too deep into the world of generics, but I will show you a basic example using a "ClassCastException," which is extraordinarily tough to debug.

Example

1) First, I create an abstract class Foo<T>

public abstract class Foo<T> {

abstract void add(T... elements);

void addUnlessNull(T... elements) {
for (T element : elements) {
if (element != null)
add(element);
}
}
}


2) Next, we implement a String version of  Foo: 

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class StringFoo extends Foo<String> {

private List<String> list = new ArrayList<>();

@Override
void add(String... elements) {
list.addAll(Arrays.asList(elements));

}

public static void main(String[] args) {
StringFoo ss = new StringFoo();
ss.addUnlessNull("Hello", "World"); // Class Cast Exception
}

}


To my surprise, when I ran this code that supposedly compiles safely, it threw a ClassCastException out of nowhere, and I am stuck. Now, check the below stack trace:

Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;
at StringFoo.add(StringFoo.java:1)
at Foo.addUnlessNull(Foo.java:9)
at StringFoo.main(StringFoo.java:17)


 If you trace the stack log, you will get: 

"StringFoo.add(StringFoo.java:1)"


 This looks at the first line import  java.util.ArrayList , which is misleading and doesn't help us achieve what we are trying to accomplish. So, what might be happening under the hood?

This could be one or more of the following: 

  • Erasure,

  • Varargs,

  • Or, the bridge method

Let me briefly explain each of these:

Erasure: Erasure converts each of T in the Foo<T> class to the lower bound of the T, i.e. the object at compile time. So, at runtime, the JVM has no knowledge of T; all it sees is the object.

Varargs: All varargs parameters are packaged in arrays. In the case of object[], you will need to add T elements that get converted to the add  Object[]  elements at compile time. As a rule of thumb, avoid mixing arrays and generics.

Bridge method: This is the most mysterious method of all. Let's see what happens after compiling the code.

public abstract class Foo<T> {

abstract void add(T... elements);    //Really Object[] after erasure 
    void addUnlessNull(T... elements) {  // Really Object[] after erasure 
for (T element : elements) {
if (element != null)
add(element);
}
}
}

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class StringFoo extends Foo<String> {

private List<String> list = new ArrayList<>();

/** Synthetic bridge method - not present in source! */
/*
 * void add(Object[] a) { // overrides abstract method { add(String[] a) Really throws ClassCastException }
 */

@Override
void add(String... elements) {
list.addAll(Arrays.asList(elements));

}

public static void main(String[] args) {
StringFoo ss = new StringFoo();
ss.addUnlessNull("Hello", "World"); // Class Cast Exception
}

}


The compiler checks that in abstract class Foo<T> there is added to the Object[] elements, but the implementing class StringFoo doesn't have a specific type of implementation. So, the compiler, in its infinite wisdom and mercy, creates a Bridge method: 

void add(Object[] a) {
    add((String[]) a) ;
}


This above code really tries to cast an Object[] to a String[] and, then, throws aClassCastException.

The moral to the story here is: don't mix arrays and generics!

Solution : Avoid using arrays and consider using Collection interface 

public abstract class Foo<T> {

abstract void add(Collection<T> elements);

void addUnlessNull(Collection<T> elements) {
for (T element : elements) {
if (element != null)
add(Collections.singleton(element));
}
}
}
public class StringFoo extends Foo<String> {

private List<String> list = new ArrayList<>();

@Override
void add(Collection<String> elements) {
list.addAll(elements);

}

public static void main(String[] args) {
StringFoo ss = new StringFoo();
ss.addUnlessNull(Arrays.asList("Hello", "World")); // No Class Cast Exception
}

}





Java (programming language)

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Test Execution Tutorial: A Comprehensive Guide With Examples and Best Practices
  • Introduction to Container Orchestration
  • Low-Code Development: The Future of Software Development
  • How Elasticsearch Works

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: