2

The following line of code causes javac to give an unsafe operation warning:

LinkedList<Node>[] buckets = new LinkedList[bucketCount];

However, when I try to fix that by doing this:

LinkedList<Node>[] buckets = new LinkedList<Node>[bucketCount];

I get a generic array creation error. How can I solve this?

Cœur
  • 32,421
  • 21
  • 173
  • 232
Overv
  • 7,985
  • 2
  • 32
  • 67

2 Answers2

1

In a nutshell, arrays of generic types are problematic.

Turn buckets into an ArrayList of LinkedLists:

ArrayList<LinkedList<Node>> buckets = new ArrayList<LinkedList<Node>>(bucketCount);
for (int i = 0; i < bucketCount; ++i) {
    buckets.add(new LinkedList<Node>());
}

This way you'll get compile-time type safety.

Community
  • 1
  • 1
NPE
  • 438,426
  • 93
  • 887
  • 970
  • Yeah, Java generics are kinda a hack, and don't handle this situation well. But it's silly to have to go to using a non-array to circumvent an artificial restriction. – Hot Licks Mar 23 '13 at 02:07
0

LinkedList only has two constructors, one is default, and the other accepts a parameter which extends Collection,

public LinkedList(Collection<? extends E> c) {
this();
addAll(c);
}

this is to say that LinkedList cann't have a initialization size, if it's nessary to initialize the capacity of container, you'd better use ArrayList, like following:

List<Node> list = new ArrayList<Node>(bucketCount);

Good luck :)

Hunter Zhao
  • 4,259
  • 21
  • 37