Nested generics problem?

J

jski

public class Box<T>
{

private T t;

...
}

import java.util.List;
public class BoxMain
{

public static void main(String[] args)
{
Box<Float> box = new Box<Float>();
List<Box<Float>> boxes = new List<Box<Float>>(); <--- ERROR:
Cannot instantiate the type

List<Box<Float>>

box.add(new Float(3.14156));
boxes.add(box);
}
}

The ERROR above results in Eclipse. Why? ---jski
 
A

angrybaldguy

public class Box<T>
{

   private T t;

    ...

}

import java.util.List;
public class BoxMain
{

   public static void main(String[] args)
   {
      Box<Float> box = new Box<Float>();
      List<Box<Float>> boxes = new List<Box<Float>>();  <--- ERROR:
Cannot instantiate the type

List<Box<Float>>

      box.add(new Float(3.14156));
      boxes.add(box);
   }

}

The ERROR above results in Eclipse.  Why?  ---jski

Your error has nothing to do with generics - List is an interface, and
cannot be directly instantiated. You could write, for example,

List<Box<Float>> boxes = new ArrayList<Box<Float>> ();
// 3.14f is a float literal, which will be boxed to a Float object.
boxes.add (new Box (3.14f));

-o
 
J

jski

The pains of a newbie! THANKS, jski

jski said:
public class Box<T>
{
   private T t;
    ...
}
import java.util.List;
public class BoxMain
{
   public static void main(String[] args)
   {
      Box<Float> box = new Box<Float>();
      List<Box<Float>> boxes = new List<Box<Float>>();  <--- ERROR:
Cannot instantiate the type
List<Box<Float>>

      box.add(new Float(3.14156));
      boxes.add(box);
   }
}
The ERROR above results in Eclipse.  Why?  ---jski

java.util.List is an interface, not a class. The line should be:

List<Box<Float>> boxes = new ArrayList<Box<Float>>();

You can substitute any class that implements List for "ArrayList".

Patricia
 
R

Roedy Green

List<Box<Float>> boxes = new List<Box<Float>>(); <--- ERROR:

You can have an interface on the left of = but not after new. You must
instantiate some concrete class that implements List, not List itself.
i.e. ArrayList, AttributeList, CopyOnWriteArrayList, LinkedList,
RoleList, RoleUnresolvedList, Stack, Vector



--
Roedy Green Canadian Mind Products
http://mindprod.com

We are almost certainly going to miss our [global warming] deadline.
We cannot get the 10 lost years back, and by the time a new global agreement to
replace the Kyoto accord is negotiated and put into effect, there will probably
not be enough time left to stop the warming short of the point where we must not
go. ~ Gwynne Dyer
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

Forum statistics

Threads
473,961
Messages
2,570,130
Members
46,689
Latest member
liammiller

Latest Threads

Top