Generic arraylist

hi, all. i am trying to implement my own queue which extends from the arraylist api and i am trying to use generic class. the problem is i have trouble using add method in the arraylist, when i did it. i got error says.
Compiling 1 source file to H:\NetBean\UniqueQueueTest\build\classes
H:\NetBean\UniqueQueueTest\src\uniquequeuetest\UniqueQueue.java:34: cannot find symbol
symbol : method add(E)
location: class uniquequeuetest.UniqueQueue<E>
add(item);
following is my part of the code.
public class UniqueQueue<E extends Comparable<E> > extends ArrayList<E extends Comparable<E> >
public UniqueQueue()
super();
public UniqueQueue(Collection<? extends E> c)
super(c);
public UniqueQueue(int initialCapacity)
super(initialCapacity);
public < E > boolean offer(E item)
Comparable e;
for(int i=0; i<size(); i++)
e = (Comparable)get(i);
if(((Comparable)item).compareTo(e) == 0)
return false;
this.add(item); <----this line causes error
return true;
thanks

I think you should remove the <E> from the declaration of the 'offer' method. Written your way, it's a different 'E' from the one used in the class definition, so it's not compatible.
Victor

Similar Messages

  • Problem with ' as a queryString in jsp

    Hi All,
    I am trying to send a value that I retrieved from the database as a queryString to other jsp. My String has special characters encoded.
    When I am using the encoded in the code given below I get nothing
    ../common/displayMessage.do?displayMessage=<bean:write name="article" property="errorMessage"/>&article=<bean:write name="article" property="article"/>'Here my errorMessage contains something like Data map dosn (&#39 ;)t contain article info.&article=zta-0016
    Special character encoding for '
    How can I pass this value as a queryString?
    --Any Help appreciated.
    Thanks,
    Sowj.
    Edited by: Sowj on Apr 17, 2009 6:45 AM

    The "Compiler compliance level" is set to 5.0
    I am using WebSphere v6.1 to deploy my web application.
    I have no problem to create a generic ArrayList in JSP. The problem occurs when I try to cast a object which I know and have checked is a generic ArrayList.
    First I check if the object is an instance of ArrayList. Then I check if the content of that ArrayList is an instance of my generic object. So I have taken every step to assure that it is what it is supposed to be.

  • Can't Figure Out How To Implement IEnumerable T

    I have no problem implementing IEnumerable but can't figure out how to implement IEnumerable<T>. Using the non-generic ArrayList, I have this code:
    class PeopleCollection : IEnumerable
    ArrayList people = new ArrayList();
    public PeopleCollection() { }
    public IEnumerator GetEnumerator()
    return people.GetEnumerator();
    class Program
    static void Main(string[] args)
    PeopleCollection collection = new PeopleCollection();
    foreach (Person p in collection)
    Console.WriteLine(p);
    I'm trying to do the same thing (using a List<Person> as the member variable instead of ArrayList) but get compile errors involving improper return types on my GetEnumerator() method. I start out with this:
    class PeopleCollection : IEnumerable<Person>
    List<Person> myPeople = new List<Person>();
    public PeopleCollection() { }
    public IEnumerator<Person> GetEnumerator()
    throw new NotImplementedException();
    IEnumerator IEnumerable.GetEnumerator()
    throw new NotImplementedException();
    class Program
    static void Main(string[] args)
    // Create a PeopleCollection object.
    PeopleCollection peopleCollection = new PeopleCollection();
    // Iterate over the collection.
    foreach (Person p in peopleCollection)
    Console.WriteLine(p);
    Console.ReadLine();
    That code compiles (basically because I haven't really done anything yet), but I get compile errors when I try to implement the GetEnumerator() methods.

    The List<T> class implements the IEnumerable<T> interface, so your enumerator can return the GetEnumerator call from the list.
    class PeopleCollection : IEnumerable<Person>
    List<Person> myPeople = new List<Person>();
    public PeopleCollection() { }
    public IEnumerator<Person> GetEnumerator()
    return myPeople.GetEnumerator();
    IEnumerator IEnumerable.GetEnumerator()
    return myPeople.GetEnumerator();
    class Program
    static void Main(string[] args)
    // Create a PeopleCollection object.
    PeopleCollection peopleCollection = new PeopleCollection();
    // Iterate over the collection.
    foreach (Person p in peopleCollection)
    Console.WriteLine(p);
    Console.ReadLine();

  • Java.lang.NoSuchMethodException: unbound

    Hi,
    I have a class com.vo.EmpInfo with a funtion as below.
    private int leaveCount;
    public void setLeaveCount(int leaveCount) {
    this.leaveCount = leaveCount;
    And I'm accessing this function from a class com.emp.EmpMonitor.
    ((EmpInfo) empList.get(i)).setLeaveCount(leaveCount);
    where empList is an ArrayList of EmpInfo objects.
    When I run this peice of code, I'm getting the following exception
    java.lang.NoSuchMethodException: <unbound>=EmpInfo.setLeaveCount(Integer);
    Continuing ...
    I'm using Jdk1.5.
    Can anyone please help me understand what excatly this exception states ?
    Thanks in Advance.
    Jane Antony

    To get better help sooner, post a [_SSCCE_|http://mindprod.com/jgloss/sscce.html] that clearly demonstrates your problem.
    Use code tags to post codes -- [code]CODE[/code] will display asCODEOr click the CODE button and paste your code between the {code} tags that appear.
    I'm using Jdk1.5.Are you sure you are compiling to Java 1.5 or to an earlier version? Autoboxing, or under-the-covers conversion between (for instance) int and Integer shouldn't give you a problem in 1.5 or later.
    Oh, and the error means that your method accepts an int (primitive data type) parameter, whereas it is being invoked with an Integer (wrapper class object) parameter. What's the type of the variable leaveCount in this line?((EmpInfo) empList.get(i)).setLeaveCount(leaveCount);On an aside, you should be using Generics (ArrayList<EmpInfo> empList) )instead of casting the type of the value returned from empList.get(...).
    db

  • Use of Generics in ArrayList now mandatory?

    Hi,
    I'm writing a little Applet involving the population of ArrayList (my Java compiler is version 1.6.0_22).
    My code is similar to
    ArrayList vertexPoints = new ArrayList();
    - it compiles OK, but when I try and run the applet, it falls out saying that there is a NullPointerException in the above line. I was under the impression that the use of generics in ArrayLists is not compulsory? Or will I have to
    change the code to something like
    ArrayList<3DPoint> vertexPoints = new ArrayList<3DPoint>():
    Some websites with tutorials give the impression that providing a type is optional, hence my confusion.

    799615 wrote:
    but accessing a method of an array of objects. I'll soldier on....Since you have not provided any more information we can only make educated guesses. Perhaps you are doing something like:
    Foo[] fooList = new Foo[5];
    fooList[0].doStuff(); // NullPointerExceptionWhy? The first line only creates an array. It does not automagically create any Foo objects for you. Therefore the array is full of the deafult value and for Objects (reference types) it is null. So effectively the second line is null.doStuff().

  • identifier expected with ArrayList in JDK5RC

    Just started with J2SE1.5 but still am unable to compile. Already fixed the generics.
    Error is <identifier> expected. See code.
    Who can help me with this? I am stuck :-(
    import java.util.List;
    import java.util.Vector;
    import java.awt.Dimension;
    import javax.swing.JFrame;
    import javax.swing.JTable;
    import javax.swing.JScrollPane;
    import javax.swing.table.AbstractTableModel;
    public class TableWithVectorData extends JFrame {
         private JTable table;
         private Model model;
         public static void main(String[] arg) {
              TableWithVectorData t = new TableWithVectorData();
              t.setVisible(true);
              t.setSize(new Dimension(600, 300));
              t.validate();
         public TableWithVectorData() {
              super("Walter's Table Demo");
              model = new Model(); // getDummy2Data());
              table = new JTable(model);
              JScrollPane scrollPane = new JScrollPane(table);
              getContentPane().add(scrollPane);
         public class Model extends AbstractTableModel {
              public static final int MAC_CODE_COL = 0;
              public static final int MAC_NAME_COL = 1;
              public static final int IP_COL = 2;
              public static final int OS_COL = 3;
              public static final int DOMAIN_COL = 4;
              public List<String> colNames = new ArrayList<String>();
              // the next line gives error message <identifier> expected
              // api doc: public boolean add(E o)
              colNames.add("Machine Code");
              colNames.add("Machine Name");
              colNames.add("IP Address");
              colNames.add("Operating System");
              colNames.add("Domain");
              public List<Class> colTypes = new ArrayList<Class>();
              colTypes.add(Integer.class);
              colTypes.add(String.class);
              colTypes.add(String.class);
              colTypes.add(String.class);
              colTypes.add(String.class);
              public List<MachineData> data = new Vector<MachineData>();
              data.add(new Integer(100), "Robert", "288.209.140.223", "Win NT", "Engineering");
              data.add(new Integer(105), "Rahul", "288.209.140.214","Solaris 5", "Engineering");
              data.add(new Integer(110), "Daina", "288.209.140.220","HP UX", "Engineering");
              public void SimpleTableModel() { // List macDataVector) {
                   super();
                   //m_macDataVector = macDataVector;
              public int getColumnCount() {
                   return colNames.size();
              public int getRowCount() {
                   return data.size();
              public void setValueAt(Object value, int row, int col) {
                   MachineData mD = (MachineData) data.get(row);
                   switch(col) {
                        case MAC_CODE_COL : mD.setMacCode((Integer) value);
                             break;
                        case MAC_NAME_COL : mD.setMacName((String) value);
                             break;
                        case IP_COL : mD.setMacIP((String) value);
                             break;
                        case OS_COL : mD.setMacOS((String) value);
                             break;
                        case DOMAIN_COL : mD.setMacDomain((String) value);
                             break;
              public String getColumnName(int col) {
                   return colNames[col];
              public Class getColumnClass(int col) {
                   return colTypes[col];
              public Object getValueAt(int row, int col) {
                   MachineData mD = (MachineData) data.get(row);
                   switch(col) {
                        case MAC_CODE_COL : return mD.getMacCode();
                        case MAC_NAME_COL : return mD.getMacName();
                        case IP_COL : return maD.getMacIP();
                        case OS_COL : return mD.getMacOS();
                        case DOMAIN_COL : return mD.getMacDomain();
                   return new String();
         public class MachineData {
              private Integer m_macCode;
              private String m_macName;
              private String m_macIP;
              private String m_macOS;
              private String m_macDomain;
              public MachineData() {
              public MachineData (Integer macCode, String macName, String macIP, String macOS, String macDomain) {
                   m_macCode = macCode;
                   m_macName = macName;
                   m_macIP = macIP;
                   m_macOS = macOS;
                   m_macDomain = macDomain;
              public Integer getMacCode() {
                   return m_macCode;
              public String getMacName() {
                   return m_macName;
              public String getMacIP() {
                   return m_macIP;
              public String getMacOS() {
                   return m_macOS;
              public String getMacDomain() {
                   return m_macDomain;
              public void setMacCode(Integer macCode) {
                   m_macCode = macCode;
              public void setMacName(String macName) {
                   m_macName = macName;
              public void setMacIP(String macIP) {
                   m_macIP = macIP;
              public void setMacOS(String macOS) {
                   m_macOS = macOS;
              public void setMacDomain(String macDomain) {
                   m_macDomain = macDomain;

    Now the table is not displayed.
    import java.util.List;
    import java.util.Vector;
    import java.util.ArrayList;
    import java.awt.Dimension;
    import javax.swing.JFrame;
    import javax.swing.JTable;
    import javax.swing.JScrollPane;
    import javax.swing.table.AbstractTableModel;
    public class TableWithVectorData extends JFrame {
         private JTable table;
         private Model model;
         public static void main(String[] arg) {
              JFrame.setDefaultLookAndFeelDecorated(true);
              TableWithVectorData app = new TableWithVectorData();
              app.setSize(new Dimension(600, 300));
              app.setVisible(true);
              app.validate();
         public TableWithVectorData() {
              super("Walter's Table Demo");
              model = new Model();
              table = new JTable(model);
              table.setPreferredScrollableViewportSize(new Dimension(500,200));
              JScrollPane scrollPane = new JScrollPane(table);
              add(scrollPane);
         public class Model extends AbstractTableModel {
              public static final int MAC_CODE_COL = 0;
              public static final int MAC_NAME_COL = 1;
              public static final int IP_COL = 2;
              public static final int OS_COL = 3;
              public static final int DOMAIN_COL = 4;
              public List<String> colNames = new ArrayList<String>();
              public List<Class> colTypes = new ArrayList<Class>();
              public List<MachineData> data = new Vector<MachineData>();
              public void Model() {
                   colNames.add("Machine Code");
                   colNames.add("Machine Name");
                   colNames.add("IP Address");
                   colNames.add("Operating System");
                   colNames.add("Domain");
                   colTypes.add(Integer.class);
                   colTypes.add(String.class);
                   colTypes.add(String.class);
                   colTypes.add(String.class);
                   colTypes.add(String.class);
                   data.add(new MachineData(new Integer(100), "Robert", "288.209.140.223", "Win NT",
    "Engineering"));
                   data.add(new MachineData(new Integer(105), "Rahul", "288.209.140.214","Solaris
    5", "Engineering"));
                   data.add(new MachineData(new Integer(110), "Daina", "288.209.140.220","HP UX",
    "Engineering"));
              public int getColumnCount() {
                   return colNames.size();
              public int getRowCount() {
                   return data.size();
              public void setValueAt(Object value, int row, int col) {
                   MachineData mD = (MachineData) data.get(row);
                   switch(col) {
                        case MAC_CODE_COL : mD.setMacCode((Integer) value);
                             break;
                        case MAC_NAME_COL : mD.setMacName((String) value);
                             break;
                        case IP_COL : mD.setMacIP((String) value);
                             break;
                        case OS_COL : mD.setMacOS((String) value);
                             break;
                        case DOMAIN_COL : mD.setMacDomain((String) value);
                             break;
              public String getColumnName(int col) {
                   return colNames.get(col);
              public Class getColumnClass(int col) {
                   return colTypes.get(col);
              public Object getValueAt(int row, int col) {
                   MachineData mD = (MachineData) data.get(row);
                   switch(col) {
                        case MAC_CODE_COL : return mD.getMacCode();
                        case MAC_NAME_COL : return mD.getMacName();
                        case IP_COL : return mD.getMacIP();
                        case OS_COL : return mD.getMacOS();
                        case DOMAIN_COL : return mD.getMacDomain();
                   return new String();
         public class MachineData {
              private Integer m_macCode;
              private String m_macName;
              private String m_macIP;
              private String m_macOS;
              private String m_macDomain;
              public MachineData() {
              public MachineData (Integer macCode, String macName, String macIP, String macOS, String
    macDomain) {
                   m_macCode = macCode;
                   m_macName = macName;
                   m_macIP = macIP;
                   m_macOS = macOS;
                   m_macDomain = macDomain;
              public Integer getMacCode() {
                   return m_macCode;
              public String getMacName() {
                   return m_macName;
              public String getMacIP() {
                   return m_macIP;
              public String getMacOS() {
                   return m_macOS;
              public String getMacDomain() {
                   return m_macDomain;
              public void setMacCode(Integer macCode) {
                   m_macCode = macCode;
              public void setMacName(String macName) {
                   m_macName = macName;
              public void setMacIP(String macIP) {
                   m_macIP = macIP;
              public void setMacOS(String macOS) {
                   m_macOS = macOS;
              public void setMacDomain(String macDomain) {
                   m_macDomain = macDomain;
    }

  • Question regarding generics and collections

    Hi,
    I am stuying the Sierra and Bates book for SCJP.
    One particular answer to a question in it is puzzling me at the moment:
    Given a method as
    public static <E extends Number> List<E> process(List<E> nums)
    A programmer wants to use this method like this:
    //INSERT DECLARATION HERE
    output = process(input)
    which pairs of delcarations could be placed at //INSERT DECLARATION HERE to allow this to compile.
    Correct answers given as :
    ArrayList<integer> input = null;
    List<Integer> output = null;
    List<Number> input = null;
    List<Number> output = null;
    List<Integer> input = null;
    List<Integer> output = null;
    My main problem is understanding what this line means:
    public static <E extends Number> List<E> process(List<E> nums)
    How do I read this? I assume <E extends Number>List<E> all relates to the return type?
    If it just said List<E> I would read it as saying the return type must be a List than can only accept objects of type E but I'm confused by the extra
    part before it.
    Hope someone can help.
    Thanks

    Have you seen generics before? E is a type variable. If the method had the simpler definition:
    <E> List<E> process(List<E> nums)This would mean that E could be replaced by any type, like you had an unbounded number of definitions:
    List<A> process(List<A> nums)
    List<B> process(List<B> nums)
    List<C> process(List<C> nums)
    ...For every possible type: A, B, C, ...
    But E has the bound "extends Number" which mean that this is like have the definitions:
    List<Number> process(List<Number> nums)
    List<Integer> process(List<Integer> nums)
    List<Long> process(List<Long> nums)
    ...For Number and every subclass of Number.

  • HOW DO I KEEP AN ARRAYLIST IN RANDOM ORDER AFTER EXITING THE SUB ROUTINE CONTAINING IT

    PLEASE HELP!I am trying to go from VB4 which I loved to VB2010 which I find somewhat more challenging. I’ve searched the web for help and have adapted the following to my project. This code does
    rotate randomly through every card in the deck and displays unique cards until all have been drawn. BUT I want to draw one card
    only from the first “hat” of Boy’s names; then draw the second card from the second “hat” of Girl’s names and repeat this process until all cards in both decks have been drawn. How do I get the TextBox (OR any
    MsgBox) to display JUST ONE unique random card at a time so I can exit that deck and go to the next deck?
    On my form, I have two TextBoxes (to display the names (as drawn), two buttons (to re-load each deck once exhausted) and one command (&End)control (to end the process). I created two ArraysLists
    (to hold the Boys names and Girls names separately) and two ArrayLists to hold the cards for the random decks when created in code.
    I can
    NOT get this code to draw random UNIQUE names once I exit the deck. I have tried to ReDim the deck; randomly pull a card from the second (temp) deck, etc
    NOTHING seems to work.
    WHY does my deck lose randomness once I exit it?
    How can I fix it? I don’t understand this. Below is the code for the "hat" with the 10 girl's names.
    Also, when I don't loop through all the cards, I usually get "An Out of Index exception was not handled" error. Hope someone can help me with this problem. It seems like this should
    be easy BUT I'm baffled. Thank you for any help.
    Imports System.Collections.Generic
    Public Class Form1
    Dim Count As Integer
    Dim Rcard As New ArrayList
    Dim Dcard As New ArrayList
    Dim NewRDeck As New ArrayList
    Dim NewDDeck As New ArrayList
    Dim temp_Rnum As Integer
    Dim temp_Dnum As Integer
    Dim MyRand As New Random()
    Public Sub Rcards_Click(sender As Object, e As System.EventArgs) Handles Rcards.Click
    While Rcard.Count > 0
    Dim temp_Rnum As Integer = Int(MyRand.Next(Rcard.Count))
    NewRDeck(temp_Rnum) = Rcard(temp_Rnum)
    Rem Check that the ArrayLists work correctly and display properly
    MsgBox(Rcard(temp_Rnum), , "New random card selected is: ")
    Console.WriteLine(Rcard(temp_Rnum))
    Rcard.Text = (Rcard(temp_Rnum))
    REM Now remove the Rcard with the random number generated so it can't be drawn again
    Rcard.RemoveAt(temp_Rnum)
    End While
    REM When all 10 cards have been picked, alert player to re-load deck if desired.
    MsgBox("No new cards left in deck; please Re-Load the cards. Thank you.")
    EndSub
    End Class

    Hi Acamar,
    Thank you for such a fast response. Sorry if my text wasn't clear. I'm really struggling with creating unique random elements in Collections in VB2010 and feel I understand ArrayLists better than some of the other Collection types.The code works perfectly
    and generates unique random cards until the original deck is exhausted. Then it prompts the user to re-load the original deck so it can be reused if needed. But I need to draw one card only and exit the deck. Then when I click on the TextBox again, I want
    that deck to be in the same random order - just minus any cards I have already drawn and thrown away.  Thanks again for your help.
    Here's the rest of the code for just the girl's "hats" of names, if it helps:
    Private Sub btnShuffleRCards_Click(sender
    As System.Object, e
    As System.EventArgs)
    Handles btnShuffleRCards.Click
    Dim j As
    Integer
    For j = 1 To 10
    NewRDeck.Add(j)
    Next j
    Randomize()
    REM Create original Deck with names for the girls.
    Rcard.Add("1 HELEN”)
    Rcard.Add("2 OLIVIA")
    Rcard.Add("3 <st1:city w:st="on"><st1:place w:st="on">ALICE</st1:place></st1:city>")
    Rcard.Add("4 VALERIE")
    Rcard.Add("5 DONNA")
    Rcard.Add("6 ZELDA")
    Rcard.Add("7 MARGARIE")
    Rcard.Add("8 <st1:city w:st="on"><st1:place w:st="on">NANCY</st1:place></st1:city>")
    Rcard.Add("9 WANDA")
    Rcard.Add("10 IRENE")
    End Sub

  • A bunch of ArrayLists

    Overview
    My program needs to store 11 different types of data (numbered 1 through 12, skipping 5, although I may find a way to fill this gap soon). Each type of data needs to have a bunch of entries of undeterminate size (ArrayList), but I know there will always be 11 different types of data. I figured instead of having 11 different ArrayList variables and 11 getters, 11 setters, and 11 removers, I could just store them all in an array of some sort, and then only have 1 getter/setter/remover/etc which takes an argument of what data type it is.
    Problem
    Problem is, I'm not exactly sure what to use to group these ArrayLists together. I tried an array, but it complains about the generic typing:
    ArrayList<Resource> resList[] = new ArrayList<Resource>[13]();
    or any combination/order of [13] and () and it always complains "Cannot create a generic array of ArrayList<Resource> or "Cannot convert from ArrayList<Resource> to ArrayList<Resource>[]"
    Solution
    Using basic google skills, I discovered I could use:
    ArrayList resList[] = new ArrayList[12];
    essentially just dropping the type...
    and then loop through the 13 new ArrayList<Resource>();
    Resulting Problem
    Then when I go to add one of the datatypes to its respective data type ArrayList
    resList[Resource.PATH].add(new Path());
    it warns me: "...Type Safety... raw type ArrayList... should be Parameterized"
    it also says the same thing, somewhat surprisingly, when I generalize the path data type back down to Resource:
    resList[Resource.PATH].add((Resource)new Path());
    since I did declare each arraylist of type <Resource>. Yet it makes the same complaint.
    Conclusion
    There's basically 4 possible outcomes to this that I can think up.
    1) (Mostly desirable) There is a solution to my Type Safety warning.
    2) (Undesirable) use @SuppressWarnings
    3) An alternative to bunching them in arrays (I had a glance at Arrays.asList, but wasn't so sure about it)
    4) (Undesirable) just leave them as 11 different ArrayList variables and make them public.
    Thanks in advance,
    -IsmAvatar

    @musicalscale, thanks, I think. Is this just creating
    an ArrayList of ArrayLists? Because I don't think
    that's appropriate here because the 11 data types are
    unchanging (until I fill in the gap at 5, in which
    case it's simply a matter of slight recoding which
    I'm more than happy to do).Yes, it's an ArrayList of ArrayLists. It will get rid of the generics warnings. If you don't plan on changing the size of the outer ArrayList, then you don't have to change it. Only your one class that keeps the private ArrayList of ArrayLists will have direct access to the outer list (unless you code it otherwise). So, you don't have to worry that someone else will mess up the list.
    Or, after you create the initial list of lists, store the private reference as an unmodifiable List:
    private final List< List < Resource > > resList;// In your constructor (or another method):
    // create tempResList with generics as described,
    // then set the instance variable as
    resList = Collections.unmodifiableList(tempResList);Then even your local class can't add or remove things from the outer list (they can still modify the inner lists).
    As for HashMap, I guess it doesn't matter that the
    order may change, since we have the key paired with
    it. But is HashMap also dynamically resizable? Maybe
    I'm just blind to the internal workings.Yes, a HashMap is dynamically resizable. Since you have a key, yes, the order doesn't matter (there is also a TreeMap that keeps the keys sorted, but you don't really need that for your stated purposes). You can make an unmodifiable Map similar to how you make an unmodifiable List.

  • Get the Type of a generic field at runtime, How to?

    Hello,
    As the topic already says, i need to get the Type of a particular field of a class. This field is declared private and generic. In C# there is a method
    Type Object.getTypeIs there any specific way to do this in Java 1.5?
    Please excuse my poor english.
    Thanks in advance.
    Markus

    McNepp wrote:
    endasil wrote:
    McNepp wrote:
    If you want to know the parametrized type (String in the example), I think there is no way of knowing this in Java 1.5 or Java 1.6, since the parametrized type is erased and not available at run time.The type of a parameterized field is not erased.For most intents and purposes, it is. Type erasure refers to the fact that at runtime, there are not actually multiple class binaries depending on the generic arguments to a class. Therefore, an ArrayList<T> is actually just an ArrayList with no generics.
    Frankly, I don't understand why you insist that the information on generic fields that the OP was asking about is lost at runtime.I wasn't trying to insist that. At the time, I was replying more to Saish and trying to reaffirm that most information about generics is lost at run-time. I mistakenly ignored how you qualified it with "field."
    What you write about instances of generic classes losing their type information is of course correct, albeit not to the point of the original question.Nope, you're right. I was just trying to reconcile the fact that many people get confused that there's any information available at run-time, and so start down the path of thinking that type erasure doesn't exist. But it very much does.
    The original question was about how to obtain the type of a generic field.And I did show in my example that even that is fairly limited, given that if the type is provided by the parameter of the class, it doesn't give you anything useful (I'm not trying to say you said it would!).
    The compiler preservers this information in the class file, so it can be obtained at runtime. Frameworks like JPA put this to use extensively, proving that it is of real value.Definitely. However I don't see this having as much to do with generics as basic reflection functionality. If you can get the type of a field at run-time, you should be able to get the parameters as well! That should in no way belittle its value, though. But I would have guessed (knowing little about) that JPA wouldn't put that to use so much as the type parameters of an accessor return type or mutator argument type. Especially since I thought we'd shown that you would need your fields to be non-private for JPA to be able to gain information about their type.
    Edit: getDeclaredField works fine with private members, and returns the expected "java.lang.String" from jschell's example above
    Edited by: endasil on 28-Apr-2009 10:39 AM

  • Generic working in eclipse compiler but not through builds

    The following code snippet works fine in my eclipse development environment (1.6.0_06), but the build system running 1.6.0_06 throws exception:
    MyClass:343: incompatible types
    found : java.util.List<C>
    required: java.util.List<B>
    entries = createListFromSmartCopy(myAList, new B(), true);
    Types:
    A is an interface
    B is an interface of A
    C is an implementation of B
    List<A> aList = new ArrayList<A>();
    aList.add(new A());
    List<B> return = createListFromSmartCopy(aList, new C(), true);
        * <p>Creates a copy of a list where the source list could be an ancestor
        * type of the returned list. It also uses a reference object to actually
        * construct the objects that populate the return list.</p>
        * @param <T> - The ancestor type of the source list
        * @param <R> - The derived type of the destination list
        * @param <S> - The more derived type of the prototype object used to
        * construct the list of R's
        * @param sourceList - The source list
        * @param referenceObject - The object used to construct the return list
        * @param deepCopy - Deep copy serializable objects instead of just copying
        * the reference
        * @return a list of R's (as defined by the caller) of entries with the
        * object constructed as a copy of referenceObject with the properties of the
        * sourceList copyied in after construction
    public static <T extends Serializable, R extends T, S extends R> List<R> createListFromSmartCopy(
                List<T> sourceList, S referenceObject, boolean deepCopy)
          List<R> retr = new ArrayList<R>();
          for(int i = 0; i < sourceList.size(); i++)
             retr.add(copyOf(referenceObject));
             copyInto(sourceList.get(i), retr.get(i), deepCopy);
          return retr;
       }Any thoughts on either:
    1. How does this pass the compiler validation inside eclipse, even through 'R' has not been defined? I believe that the code is doing some sort of return type inference to return the exactly correct type of list as referred by the return result or else it is simply ignoring the invariant capture of R all together and silently dropping the error. The funny thing is that the code does work just fine in practice in my development system without an issue.
    or
    2. Why if the code is valid does the independent build system disallow this generic return type 'inference' to occur? Are there compiler flags I can use to withhold this special condition?

    Thanks for the response, I wasn't trying to show a full example but just my implementation's snippet. I'll list one now:
    package test;
    import java.io.ByteArrayInputStream;
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.io.Serializable;
    import java.util.ArrayList;
    import java.util.List;
    public class TestMe
        * <p>This method performs a deep copy of an object by serializing and
        * deserialzing the object in question.</p>
        * @param <T> - The type of data to copy
        * @param original - The original object to copy
        * @return The object who's state should be the same as the original. This
        * call uses serialization to guarantee this copy is fully separate from the
        * original, so all sub-object references are also deep copies of their
        * originals
       @SuppressWarnings("unchecked")
       public static <T extends Serializable> T clone(T original)
          T obj = null;
          try
             ByteArrayOutputStream bos = new ByteArrayOutputStream();
             ObjectOutputStream out = new ObjectOutputStream(bos);
             out.writeObject(original);
             out.flush();
             out.close();
             ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(
                      bos.toByteArray()));
             obj = (T)in.readObject();
          catch(IOException e)
             e.printStackTrace();
          catch(ClassNotFoundException cnfe)
             cnfe.printStackTrace();
          return obj;
        * <p>Copies the properties from one object to another. The destined object
        * in this method must be derived from the source object. This allows for a
        * faster and smoother transition.</p>
        * @param <T> The type of source
        * @param <R> The type of destination
        * @param source - The source object
        * @param destination - The destination object
        * @param deepCopy - Copies the reference objects instead of just passing
        * back the reference pointer reference
       public static <T, R extends T> void copyInto(T source, R destination,
                boolean deepCopy)
       // Stubbed because it links into a ton of unnecessary methods
        * <p>Copies the values of a list of an ancestor class into the values of
        * another list who's value is derived from the ancestor.</p>
        * @param <T> - The ancestor type of the source list
        * @param <R> - The derived type of the destination list
        * @param sourceList - The source list
        * @param destinationList - The destination list
        * @param deepCopy - Deep copy serializable objects instead of just copying
        * the reference
       public static <T, R extends T> void copyIntoList(List<T> sourceList,
                List<R> destinationList, boolean deepCopy)
          if(sourceList.size() > destinationList.size())
             throw new IllegalArgumentException(
                      "Cannot copy entire source set into destination list");
          for(int i = 0; i < sourceList.size(); i++)
             copyInto(sourceList.get(i), destinationList.get(i), deepCopy);
        * <p>Creates a copy of a list where the source list could be an ancestor
        * type of the returned list. It also uses a reference object to actually
        * construct the objects that populate the return list.</p>
        * @param <T> - The ancestor type of the source list
        * @param <R> - The derived type of the destination list
        * @param <S> - The more derived type of the prototype object used to
        * construct the list of R's
        * @param sourceList - The source list
        * @param referenceObject - The object used to construct the return list
        * @param deepCopy - Deep copy serializable objects instead of just copying
        * the reference
        * @return a list of R's (as defined by the caller) of entries with the
        * object constructed as a copy of referenceObject with the properties of the
        * sourceList copyied in after construction
       public static <T extends Serializable, R extends T, S extends R> List<R> createListFromSmartCopy(
                List<T> sourceList, S referenceObject, boolean deepCopy)
          List<R> retr = new ArrayList<R>();
          for(int i = 0; i < sourceList.size(); i++)
             retr.add(clone(referenceObject));
             copyInto(sourceList.get(i), retr.get(i), deepCopy);
          return retr;
       public static void main(String[] args)
          List<A> aList = new ArrayList<A>();
          aList.add(new AImpl());
          aList.add(new AImpl());
          List<B> bList = createListFromSmartCopy(aList, new C(), true);
          for(B bItem : bList)
             System.out.println("My String = "
                      + bItem.getString() + " and my number = " + bItem.getInt());
       public static interface A extends Serializable
          public void setString(String string);
          public String getString();
       public static class AImpl implements A
          private static final long serialVersionUID = 1L;
          @Override
          public void setString(String string)
          @Override
          public String getString()
             return null;
       public static interface B extends A
          public void setInt(int number);
          public String getInt();
       public static class C implements B
          private static final long serialVersionUID = 1L;
          public C()
          @Override
          public String getInt()
             return null;
          @Override
          public void setInt(int number)
          @Override
          public String getString()
             return null;
          @Override
          public void setString(String string)
    }In my eclipse (20090920-1017), this compiles and runs just fine. I stripped out the functional pieces that weren't pertinent to the discussion.

  • How do I convert an arrayList to an array []

    I want to create a generic method that I can pass a Collection ( An ArrayList if I have to be specific ) and also tell this method the underlying Object type the Collection contains and have it call the Collections.toArray method and create an array [] of the type I specify.
    Part of the problem is how do I have the method resolve the return type at run time and how do I use the Class variable to tell it the type of objects the Collection holds.
    Fo instance I load an ArrayList with 3 MyClass objects.
    I want to pass this to the method and have it return me an array of Type MyClass containing 3 items.
    I don't want to have to be tied to a method with the signature
    public MyClass [] convert( ArrayList myList  ){ ... }Thanks ...

    Since it is an "old system" I doubt that is feasible. Also I believe that this was intentionally left out of the API because specifying the array type is more natural than the Class object and using the normal approach you get back the same zero-length array that you passed in if the collection is of size zero. It does look nice from a "caller" perspective though.

  • How to define generics in interfaces

    I want to define an interface for Person, which has 2 attributes, 'Owner' and 'Access', but these attributes may be different types for different implementations of the interface. I have another interface that takes Person, so I have something like this:
    public interface Person<O, A>
        public abstract O getOwner();
        public A getAccess();
    public interface Entry
        public void addPerson(Person<?, ?> person);
    }I then have a base Entry implementation that does
    import java.util.ArrayList;
    import java.util.List;
    public abstract class BaseEntry implements Entry
        protected List<Person<?,?>>  persons;
        public void addPerson(Person<?, ?> person)
            if (persons == null)
                persons = new ArrayList<Person<?,?>>();
            persons.add(person);
    }and finally I have a concrete class that wants to use Entry and Person interfaces to do somthing like
    public class RealEntry extends BaseEntry
        private int personCount;
        public void addPerson(Person<String, String> person)
            super.addPerson(person);
            personCount++;
    }and I might have another implementation that does
    public class ListEntry extends BaseEntry
        public void addPerson(Person<String, List<String>> person)
            super.addPerson(person);
    }but the concrete implementations do not compile in Eclipse with the message
    Name clash: The method addPerson(Person<String,String>) of type RealEntry has the same erasure as addPerson(Person<?,?>) of type BaseEntry but does not override it
    I've read the generics tutorial, but it's not helped me. I'm not absolutely certain I should be using wildcards as opposed to generic method.
    Anyone know what I'm doing wrong?
    Thanks
    Antony

    Hi Stefan, I see how your example breaks things, thanks.
    My 'Entry' is a simple queue class. I compiles OK if I add the O, A to Entry and implementations, i.e.
    public interface Entry<O, A>
        public void addPerson(Person<O, A> person);
    }but it seems strange (to me) that I have to define the O, A types for the Entry interface - it makes it cluttered. I thought it should be possible to have a generic Entry interface that takes a Person objects without having to tell Entry the subtypes of classes that make up the O and A inside Person.
    I could be trying to do something impossible, but I something think it has to be possible as it seems such a common type of usage, i.e. I can have many classes that all define different types of Person implementations and can store them in Entry implementations.

  • 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());
    }

  • Array of Maps without generic or warnings?

    How would I create an array of maps without getting an error about a generic type or a warning?
    This will give me an error.
    HashMap<Integer,Integer> test = new HashMap<Integer,Integer>[5];This will give me a warning.
    HashMap<Integer,Integer> test = new HashMap[5];

    Dennis_Martinez wrote:
    Could I see an example? I'm a little lost on doing so.I suspect you know how to use lists and ask for an example demonstrating the inherent unsafety. So here it is:
    List<String>[] generic = new List<String>[1]; // assume this works
    List<Integer> ints = new ArrayList<Integer>();
    ints.add(42);
    Object[] o = generic;
    o[0] = ints; // this should not work, but it does (erasure)
    List<String> strings = generic[0]; // really it's a list of Integers, ohoh
    // now you pass that list somewhere completely unrelated and try to get an element:
    String s = strings.get(0); // ClassCastExceptionCompare this to:
    String[] strings = new String[1];
    Object[] objects = strings;
    objects[0] = 42; // ArrayStoreExceptionWith kind regards
    Ben

Maybe you are looking for