Array of generic class

Hi.
i have to create an array of generic class
ex: GenericClass<E> [ ] x = new GenericClass<E>[ y ]
is it possible?
i can create GenericClass<E> [ ] x; but i can't initiate it in this way..
Someone know how i can do it?

crosspost
http://forum.java.sun.com/thread.jspa?threadID=746524&messageID=4272614#4272614

Similar Messages

  • How to create an array with Generic type?

    Hi,
    I need to create a typed array T[] from an object array Object[]. This is due to legacy code integration with older collections.
    The method signature is simple:public static <T> T[] toTypedArray(Object[] objects)I tried using multiple implementations and go over them in the debugger. None of them create a typed collection as far as I can tell. The type is always Object[].
    A simple implementation is just to cast the array and return, however this is not so safe.
    What is interesting is that if I create ArrayList<String>, the debugger shows the type of the array in the list as String[].
    If I create ArrayList<T>, the class contains Object[] and not T[].
    I also triedT[] array = (T[]) Array.newInstance(T[].class.getComponentType(), objects.length);And a few other combinations. All work at runtime, create multiple compilation warnings, and none actually creates T[] array at runtime.
    Maybe I am missing something, but Array.newInstace(...) is supposed to create a typed array, and I cannot see any clean way to pass Class<T> into it.T[].class.getComponentType()Returns something based on object and not on T, and T.class is not possible.
    So is there anything really wrong here, or should I simply cast the array and live with the warnings?
    Any help appreciated!

    Ok. May be you could keep information about generic type in the your class:
    public class Util {
        public static <T> T[] toTypedArray(Class<T> cls, Object[] objects){
            int size = objects.length;
            T[] t = (T[]) java.lang.reflect.Array.newInstance(cls, size);
            System.arraycopy(objects, 0, t, 0, size);
            return t;
    public class Sample<T> {
        Class<T> cls;
        T[] array;
        public Sample(Class<T> cls) {
            this.cls = cls;
        public void setArray(Object[] objects){
            array = Util.toTypedArray(cls, objects);
        public T[] getArray(){
            return array;
        public static void main(String[] args) {
            Object[] objects = new Object[] { new LinkedList(), new ArrayList()};
            Sample<List> myClass = new  Sample<List>(List.class);
            myClass.setArray(objects);
            for(List elem: myClass.getArray()){
                System.out.println(elem.getClass().getName());
    }

  • How to create an array of generics?

    I have the following snippet of code using array of vectors:
    Vector[] tmpArr = new Vector[n];
    for(int j=0; j<n; j++)
    tmpArr[j] = new Vector();
    String str = ...
    if (!tmpArr[j].contains(str))
    tmpArr[j].add(str);
    And I want to convert to generics:
    Vector<String>[] tmpArr = new Vector<String>[n];
    for(int j=0; j<n; j++)
    tmpArr[j] = new Vector<String>();
    String str = ....
    if (!tmpArr[j].contains(str))
    tmpArr[j].add(str);
    But the first row gives me an error:
    -->Generic array creation.
    If I change it in
    Vector<String>[] tmpArr = new Vector<String>[n];
    (as I've seen in a pdf by G.Bracha talking aout collections)
    it gives me the error:
    -->cannot find symbol
    -->method add(String)
    in the
    tmpArr[j].add(str);
    row.
    The only way it seems to work is
    Vector<String>[] tmpArr = new Vector[n];
    but it gives me the unchecked conversion warning.
    How can I create an array of generics?
    Thank you!
    Matteo

    You can't
    Actually, that depends on the exact definition of a generic array. If by generic array someone means "an array comprised of elements defined by a type parameter", there is a solution.
    import java.lang.reflect.Array;
    public class Something<T> {
        private final Class<T> type;
        public Something(Class<T> type) {
            this.type = type;
        public String getTypeName() {
            return this.type.getName();
        public T[] newArray(final int length) {
            return (T[]) Array.newInstance(this.type, length);
    }The constructor introduces the type information (T) to the runtime environment, which means an instance of Something will know its type. Method newArray therefore does not cause a warning on unchecked type conversion, so this approach is typesafe.
    // Type parameter class is demanded by constructor...
    Something<String> stringThing = new Something<String>(String.class);
    // Cheating won't work, because the compiler catches the error...
    Something<Vector> vectorThing = new Something<Vector>(Integer.class);This approach, however, doesn't enable you to create an array of typed elements (like Vector<String>[]). If that is the definition of a generic array, then it is indeed not possible to create one.
    After all, while Vector[].class exists and can be resolved at runtime, there's no such thing as Vector<String>[].class, so there's no way you could provide the class definition of the component type to the constructor of Something.
    This may be a surprise to mdt_java, because if I remember correctly, templates in C++ cause actually different classes to be created for 'generic' types. This is not the case with Java.

  • Array of generics (JLS seems too restrictive)

    Hi everybody,
    with some friends (in a lab) we currently develop a compiler generator
    (a la SableCC i.e SLR, LR, LALR).
    Because we start last june, we develop using jdk 1.5 and
    generics. For me, i think it save us lot of time mainly because
    Map<NonTerminal,Map<LRItem,Node>> is more readable
    than Map :)
    And this is my question : why CREATION of array of generics is unsafe ?
    I don't understand why a code like below is tagged unsafe :
    HashMap<State,Action>[] maps=new HashMap<State,Action>[5];
    for(int i=0;i<map.length;i++)
      maps=new HashMap<State,Action>();
    For me, the fact that JLS forbids array of generics creation
    is too restrictive, only cases where type parameter are lost
    should be tagged as unsafe.
    Example :
    Object[] array=maps; // unsafe
    Object o=map;            // weird but unsafe because
                                          // Object[] o=(Object[])(Object)maps; must be unsafeWhat do you think about this ?
    R�mi Forax

    The question is why :
    Future<Double>[] futures=new
    Future<Double>[10000];
    is not allowed. It seems safe !First of all, it would not be safe. The example below would exhibit exactly the same vulnerabilities with this assignment as it would with any of the allowed ones. This is because both the declared type and the runtime type would still be the same.
    It seems the current implementation is not able to detect (and warn about) the unsafety of the assignment above. That's why you're not allowed to use it: allowing it would provide a very false sense of type-safety
    and why :
    Object[] o=futures;
    is not tagged unsafe.
    It's unsafe because you can write :
    Object[] o=futures;
    o[0]=new Future<String>(); // for the example, let
    says Future is a class
    R�mi ForaxThis is probably done to avoid redundancy. As far as I can see, in all cases where this could be unsafe, you have been notified about the lack of safety already when you first assigned to futures.

  • Using static .values() method of Enum in Generic Class

    Hi *,
    I tried to do the following:
    public class AClass<E extends Enum<E> >  {
         public AClass() {
              E[] values = E.values(); // this DOESN'T work
              for (E e : values) { /* do something */ }
    }This is not possible. But how can I access all Enum constants if I use
    an Enum type parameter in a Generic class?
    Thanks for your help ;-) Stephan

    Here's a possible workaround. The generic class isn't adding much in this case; I originally wrote it as a static method that you simply passed the class to:
    public class Test21
      public static enum TestEnum { A, B, C };
      public static class AClass<E extends Enum<E>>
        private Class<E> clazz;
        public AClass(Class<E> _clazz)
        {  clazz = _clazz;  }
        public Class<E> getClazz()
        {  return clazz;  }
        public void printConstants()
          for (E e : clazz.getEnumConstants())
            System.out.println(e.toString());
      public static void main(String[] argv)
        AClass<TestEnum> a = new AClass<TestEnum>(TestEnum.class);
        a.printConstants();
    }

  • Calling an array from another class

    Ok I have this little program that I created to display values stored in an array. Well, I want my array to automatically be populated with the same values that are in another array that resides in a different class. Here is my code for the class that I want the values to be displayed:
    import javax.swing.*;
    import java.awt.*;
    public class GUIRead extends JFrame
         double[] interest = new double[3];
         MemicCSVReader[] interestObjectArray = new MemicCSVReader[3];
         interestObjectArray[0] = new MemicCSVReader();
         interestObjectArray[1] = new MemicCSVReader();
         interestObjectArray[2] = new MemicCSVReader():
         for(int x = 0; x < 3; x++)
         JPanel display = new JPanel();
         JTextField interestText = new JTextField(10);
         JPanel display2 = new JPanel();
         JTextField interestText2 = new JTextField(10);
         JPanel display3 = new JPanel();
         JTextField interestText3 = new JTextField(10);
         public GUIRead()
              super("Test");
              setSize(160,200);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              setVisible(true);
              GridLayout config = new GridLayout(3,1);
              FlowLayout config2 = new FlowLayout(FlowLayout.LEFT,10,10);
              Container pane = getContentPane();
              pane.setLayout(config2);
              display.setLayout(config2);
              display.add(interestText);
              interestText.setText(interest[0]);
              interestText.setEditable(false);
              pane.add(display);
              display2.setLayout(config2);
              display2.add(interestText2);
              interestText2.setText(interest[1]);
              interestText2.setEditable(false);
              pane.add(display2);
              display3.setLayout(config2);
              display3.add(interestText3);
              interestText3.setText(interest[2]);
              interestText3.setEditable(false);
              pane.add(display3);
              setContentPane(pane);
         public static void main(String[] args)
              GUIRead run = new GUIRead();
    Here is my code that I want the double[] interest array to pull it's data from:
    public class MemicCSVReader
         double interestArray[];
         MemicCSVReader()
              String[] interestString = {"5.5","5.35","5.75"};
              for(int x = 0; x < 3; x++)
                   interestArray[x] = Double.parseDouble(interestString[x]);
    }

    Ok, thanks for your help. Now I have another problem. I can't get the values to display. Here is my code:
    This is the program that runs the application:
    import javax.swing.*;
    import java.awt.*;
    public class GUIRead extends JFrame
         MemicCSVReader readCSV = new MemicCSVReader();
         double[] interestDouble = readCSV.getInterestArray();
         String[] interest;
         JPanel display = new JPanel();
         JTextField interestText = new JTextField(10);
         JPanel display2 = new JPanel();
         JTextField interestText2 = new JTextField(10);
         JPanel display3 = new JPanel();
         JTextField interestText3 = new JTextField(10);
         public GUIRead()
              super("Test");
              setSize(160,200);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              setVisible(true);
              GridLayout config = new GridLayout(3,1);
              FlowLayout config2 = new FlowLayout(FlowLayout.LEFT,10,10);
              Container pane = getContentPane();
              pane.setLayout(config2);
              display.setLayout(config2);
              display.add(interestText);
              interestText.setEditable(false);
              pane.add(display);
              display2.setLayout(config2);
              display2.add(interestText2);
              interestText2.setEditable(false);
              pane.add(display2);
              display3.setLayout(config2);
              display3.add(interestText3);
              interestText3.setEditable(false);
              pane.add(display3);
              setContentPane(pane);
         public void actionPerformed()
              for(int x = 0; x < 3; x++)
                   interest[x] = Double.toString(interestDouble[x]);
              interestText.setText(interest[0]);
              interestText2.setText(interest[1]);
              interestText3.setText(interest[2]);
         public static void main(String[] args)
              GUIRead run = new GUIRead();
    This is the file that it pulls the array from:
    public class MemicCSVReader
         private double[] InterestArray = new double[3];
         MemicCSVReader()
              double[] InterestArray = {5.5,5.35,5.75};
         public double[] getInterestArray()
              return InterestArray;
    }

  • Hp LaserJet 1200 Generic Class: Waiting for device

    I have 2 computers that I want to print to my hp Laserjet 1200 printer. We are using an iogear 4-port usb 2.0 sharing switch. One computer prints fine but the other always displays a message "Generic Class: Waiting for device." Help!

    Both computers have the printer driver installed. The usb device does not have a driver to install. You just plug in the usb cords to each computer and the printer. You only install a driver if using a pc operating system.

  • Best way to call a function in a generic class from a base class

    Hi,
    I have a generic class that works with subclasses of some other baseclass. When I construct the subclass, I call the constructor of the baseclass which I want to call a function in the generic class. e.g. suppose I have the following classes
    public class List<T extends BaseClass>
        newTCreated(T t)
    }

    Sorry, I pressed Tab and Enter last time when typing the code so I posted without meaning to
    Hi,
    I have a generic class that works with subclasses of some other baseclass. When I construct the subclass, I call the constructor of the baseclass which I want to call a function in the generic class. e.g. suppose I have the following classes
    public class List<T extends BaseClass>
        public void newTCreated(T t)
            // add the t to some internal list
        public T getT(int index)
            // get the object from the internal list
    public class BaseClass
        public BaseClass(List<?> list)
            list.newTCreated(this);
    public class SubClass extends BaseClass
        public SubClass(List<SubCass> list)
            super(list);
    }This doesn't compile because of the call to newTCreated in the BaseClass constructor because BaseClass is not necessarily of type T. Is there any way of checking when I call the newTCreated function that the BaseClass is actually of type SubClass? I could either add the call explicitly in each SubClass's constructor or have a function addToList in BaseClass that is called from the BaseClass constructor but overloaded in each subclass but both of those rely on future subclasses doing the same. Or I could change the newTCreated function to take an argument of type BaseClass and then cast it to type T but this doesn't give a compilation error, only a runtime exception.
    It seems like there should be solution but having only recently started writing Generic classes I can't find it. Thanks in advance for any help,
    Tom

  • Using an array in another class to set text of a button

    I am trying to use an array from one class in another to set the text of a button.
    This is the code in the class where i have made the array.
    public class EnterHomeTeam
         public int NumberOfPlayers = 11;
         public String[] PlayerName = new String [NumberOfPlayers];
    private void button1_Click (Object sender, System.EventArgs e)
              PlayerName [0] = this.HGoalKeeper.toString();
              PlayerName [1] = this.HDef1.toString();
              PlayerName [2] = this.HDef2.toString();
              PlayerName [3] = this.HDef3.toString();
              PlayerName [4] = this.HDef4.toString();
              PlayerName [5] = this.HMid1.toString();
              PlayerName [6] = this.HMid2.toString();
              PlayerName [7] = this.HMid3.toString();
              PlayerName [8] = this.HMid4.toString();
              PlayerName [9] = this.HAtt1.toString();
              PlayerName [10] = this.HAtt2.toString();     
              Players IM = new Players();
              this.Hide();
              IM.Show();
    }Then in the class where i want to use the variables (ie. PlayerName[0]) I have got
    public class Players
    EnterHomeTeam HT = new EnterHomeTeam();
    //and included in the button code
    this.button1.set_Text(HT.PlayerName[0]);I hope i have explained this well enough and hope someone can help me solve this problem! Im not a very competent programmer so i apologise if I havent explained this well enough!
    Adam

    .NET automatically generates quite a bit of code.... this is button1:
    private void InitializeComponent()
              this.button1 = new System.Windows.Forms.Button();
    // button1
              this.button1.set_BackColor(System.Drawing.Color.get_LightBlue());
              this.button1.set_Location(new System.Drawing.Point(88, 32));
              this.button1.set_Name("button1");
              this.button1.set_Size(new System.Drawing.Size(72, 56));
              this.button1.set_TabIndex(0);
              this.button1.set_Text(HT.PlayerName[0]);
              this.button1.add_Click( new System.EventHandler(this.button1_Click) );
    this.get_Controls().Add(this.button1);
         private void button1_Click (Object sender, System.EventArgs e)
              System.out.print(HT.PlayerName[0]);
              GKAction GK = new GKAction();
              this.Hide();
              GK.Show();
         }Hope that helps - im pretty sure that's all the button1 code

  • Getting the name of the generic class?

    I have a generic class declared as such:
    public class MyClass<T>
    and I want to access the name of the <T> class a member function in that class? I just can't figure out which syntax to use.
    Thank you!
    Joshua

    Sorry, I'm a little bit confused at your answer.
    I cannot seem to instantiate an object of class T, like: T item = new T();does not work. If I can't create an object of type T, then I can't get it's type. I need to get the class even if I don't have any instantiated objects (or if I can create a blank one), so that I can use the name to fetch the objects from the persistence engine. Here is the class, so you can see what I'm talking about. I have in there now what seems like it should be right, but doesn't compile.
    A small example of solution please?
    public class PersistentSelectorCellEditor<T> extends AbstractCellEditor
              implements TableCellEditor {
         JComboBox control;
         List<T> choices;
         Session session;
         public PersistentSelectorCellEditor() {
              initializeComponents();
         public PersistentSelectorCellEditor(Object value) {
              initializeComponents();
              this.control.setSelectedItem(value);
         private void initializePersistence() {
              session = LabApp.getSession();
              session.beginTransaction();
         private void initializeComponents() {
              initializePersistence();
              populateList();     //query for selections to fill combo box
              control = new JComboBox((ComboBoxModel)choices);
         private void populateList() {
              //query to populate drop down lists
              Query query = session.createQuery("from " + T.class.getName());
              choices = query.list();
         public void setValue(T value) {
              control.setSelectedItem(value);
         public T getValue() {
              return (T)control.getSelectedItem();
         //interface members
         public Object getCellEditorValue() {
              return control.getSelectedItem();
         public Component getTableCellEditorComponent(JTable table, Object value,
                   boolean isSelected, int row, int column) {
              return control;
    }Thank you!
    Joshua

  • Trying to create an array of a class

    This is the first time ive tried to use an array so its not surprising im having trouble.
    this is my program:
    import java.util.*;
    public class studentRecordDemo
         public static void main(String[] args)
              int studNum, index;
              System.out.println("Enter the number of students you wish to record");
              Scanner keyboard = new Scanner(System.in);
              studNum = keyboard.nextInt();
              studentRecord student[] = new studentRecord[studNum];
              for (index = 0; index < studNum; index++)
              {student[index].readInput();
              student[index].writeOutput();}
    }And it lets me compile it but when i enter a number it gives me the error:
    Exception in thread "main" java.lang.NullPointerException
    at studentRecordDemo.main(studentRecordDemo.java:15)the
    So yeah im trying to create an array of the class "studentRecord" and the number is input by the user. Is there a way to make that work or would it be easier to just make the array a really high number?

    your error is in here:
    student[index].readInput();its null...
    This is the first time ive tried to use an array so
    its not surprising im having trouble.
    this is my program:
    import java.util.*;
    public class studentRecordDemo
         public static void main(String[] args)
              int studNum, index;
    System.out.println("Enter the number of students
    ts you wish to record");
              Scanner keyboard = new Scanner(System.in);
              studNum = keyboard.nextInt();
    studentRecord student[] = new
    ew studentRecord[studNum];
              for (index = 0; index < studNum; index++)
              {student[index].readInput();
              student[index].writeOutput();}
    }And it lets me compile it but when i enter a number
    it gives me the error:
    Exception in thread "main"
    java.lang.NullPointerException
    at
    studentRecordDemo.main(studentRecordDemo.java:15)the
    So yeah im trying to create an array of the class
    "studentRecord" and the number is input by the user.
    Is there a way to make that work or would it be
    easier to just make the array a really high number?

  • How to copy an array element in one class to an array in another class?

    Hi,
    I have a ClassRoom class that stores a list of Student objects in an array. How would I copy a Student object from the Student[] array in the ClassRoom class to an array in another class?
    Is it something like this:
    System.arraycopy(Students, 2, AnotherClass.Array, 0, 2);In an array do the items get copied over existing array elements or can the be added to the end? If so, how would I specify add copied object reference to the end of the array in the other class?

    drew22299 wrote:
    Hi,
    I have a ClassRoom class that stores a list of Student objects in an array. How would I copy a Student object from the Student[] array in the ClassRoom class to an array in another class?
    Is it something like this:
    System.arraycopy(Students, 2, AnotherClass.Array, 0, 2);In an array do the items get copied over existing array elements or can the be added to the end? If so, how would I specify add copied object reference to the end of the array in the other class?System.arrayCopy will overwrite whatever is already in the array. It is your job to make sure it copies into the proper array location.
    That being said, you're only moving a single student. This is not something you would use arrayCopy for, as you can just do that with simple assignment. Also, you should consider giving Class a method to add a student to its student list, as the class should know how many students it has and can easily "append" to the array.
    Note: I hope you noticed the quotes around append. Java's arrays are fixed size. Once allocated, their size cannot change. You may want to consider using one of the List implementations (ArrayList, for example) instead.

  • Using an array in one class from another

    If I create a new string array in a class, and then set the values in that class, how can I use these value in another class? The way I have tried is to create a new instance of the class that holds the array, but when thinking about it, if I create a new instance surely the value in the array wont have been set? hence why when I am trying to use the array all the values are null.
    Thanks

    You could create a member variable in one class, making the the variable of the other class' type. Then simply call one of the member object's methods, passing the array reference as an argument.

  • What is the use of Generic class in java

    hi everyone,
    i want to know that
    what is the use of Generic class in java ?
    regards,
    dhruvang

    Simplistically...
    A method is a block of code that makes some Objects in the block of code abstract (those abstract Objects are the parameters of the method). This allows us to reuse the method passing in different Objects (arguments) each time.
    In a similar way, Generics allows us to take a Class and make some of the types in the class abstract. (These types are the type parameters of the class). This allows us to reuse the class, passing in different types each time we use it.
    We write type parameters (when we declare) and type arguments (when we use) inside < >.
    For example the List class has a Type Parameter which makes the type of the things in the list become abstract.
    A List<String> is a list of Strings, it has a method "void add(String)" and a method "String get(int)".
    A List<File> is a list of Files, it has a method "void add(File)" and a method "File get(int)".
    List is just one class (interface actually but don't worry about that), but we can specify different type arguments which means the methods use this abstract type rather than a fixed concrete type in their declarations.
    Why?
    You spend a little more effort describing your types (List<String> instead of just List), and as a benefit, you, and anyone else who reads your code, and the compiler (which also reads your code) know more accurately the types of things. Because more detail is known, the compiler is able to tell you when you screw up (as opposed to finding out at runtime). And people understand your code better.
    Once you get used to them, its a bit like the difference between black and white TV, and colour TV. When you see code that doesn't specify the type parameters, you just get the feeling that you are missing out on something. When I see an API with List as a return type or argument type, I think "List of what?". When I see List<String>, I know much more about that parameter or return type.
    Bruce

  • How to get the parameter name of a generic class?

    Is it possible to get the name of generic class parameter type without having an instance of that type?
    e.g.
    class MyClass<T> {
      public MyClass() {
      // get the name here
    }

    I need to get a string containing "Object" (or "java.lang.Object") if the class would be used like this:
    MyClass<Object> mc = new MyClass<Object>()

Maybe you are looking for

  • Metadata Navigation and Library Column Filter Bug

    To whom it may concern, When document library metadata navigation is enabled and a user clicks an item in the metadata navigation part, the library updates to reflect the selected filter. Subsequent filtering actions performed on columns in the libra

  • JNI Image Rendering

    I have a problem regarding Java and C++. I want to write a Java application that can display the livestream of PTZ cameras and network cameras. It currently works but the algorithm is not very efficient. I have written a C++ library (compiled with Vi

  • Editing a converted document

    How can I edit a converted pdf to word document?

  • Obtaining References of Controls Inside of Tab Controls

    Does anyone have a way to detemine the id/index number of a control on a tabbed front panel? If there is no front panel I can use the menus: Edit, Set tabbing order. Then I can use this index in the block diagram of a sub-vi to update the control on

  • Have just updated to 11.0 Feedback button does not work

    Firefox was just updated today, Feb. 4 around 7pm central. The feedback button on the firefox menu bar does not work. Is it suppose to?