Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

A Look at Arrays and Generics in Java

DZone 's Guide to

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.

· Java Zone ·
Free Resource

 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
}

}





Topics:
java ,tutorial ,arrays ,generics ,jdk ,erasure ,varargs ,bridge method

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}