老师说,下面这段代码是有问题的,可是上课的时候没听清到底是什么问题,好像是跟数组不支持泛型有关,哪位大侠可以给解释解释么?class OrderedList<A>
{
  private int size;
  private A[] list;
}

解决方案 »

  1.   

    Hi,Yes,You 're right.To be the backward compatible.the Generics doesn't 
    carry A at the runtime of J2SE.
    But.The class Class exists. You can solve this problem like this as follows:
    import java.lang.reflect.Array;
    class OrderedList<A>
    {
      private int size;
      private final A[] list;
      public OrderedList(Class<A> cla,int capacity){
             list = (A[])Array.newInstance(cla,capacity);
      }
    }
      

  2.   


    import java.lang.reflect.Array;
    class OrderedList <A>
    {
        private int size;
        private final A[] list;
        public   OrderedList(Class <A> cla,int capacity){
                      list = (A[])Array.newInstance(cla,capacity);
        }

      

  3.   

    Java 5 does not permit the construction of generic arrays. Suppose for example that we wish to provide an array implementation of the interfacepublic interface Stack<E> {
        ...
    }Then, for an 8-element array, the following code might be natural:private E[] stack = new E[8];but this is illegal. A workaround is to construct an array of objects with a type-cast:private E[] stack = (E[]) new Object[8];but this will generate a compiler warning about an unchecked type conversion. This is only generated, however, when the source file containing the type-cast is compiled, not when a file of application code importing this class is compiled.There is considerable discussion of this aspect of Java 5, as a websearch for some phrase such as generic array java will show. In practice, if efficiency is important, it is not possible to use arrays to implement generic data structures without generating such warnings. In implementing the generic version of the DataStructures package, I have been willing to accept such warnings, as the Java source code will show. The implementers of the Collections framework have taken the same approach. This issue will remain opaque, of course, to any client of a pre-compiled package.I hope that it can help to to understand the Generic arrays in J2SE.
      

  4.   

    这段代码编译没问题啊,怎样才算不支持呢?继续等待高手解答public class OrderedList<A> { private int size;
    private A[] list; public static void main(String[] args) {
    OrderedList<String> o = new OrderedList<String>();
    o.list = new String[3];
    o.list[0] = "123";
    System.out.println(o.list[0]);//输出123
    }}
      

  5.   

    需要的话 为什么不用List,Stack,HashMap这些类呢?
      

  6.   

    因为java在数组声明的时候就定义好类型了  往里面传值如果类型不符就会出错
    但是集合类就不一样了 jdk1.4版本之前没有泛型  什么类型的元素只要是对象就可以添加进里面
    但是1.5版本之后添加了泛型 保证集合类中的元素都是同一类型的
      

  7.   

    呵呵我赞成把jdk变成1.5版本的就支持了呵呵我经常用的还行
      

  8.   

    建议楼主看看effectiv java