How do I gain type safety with a generic method taking a class object?

How do I achieve type safety with the following code without getting a compile error?
import java.util.ArrayList;
import java.util.List;
public class Main {
    public static void main(String[] args) throws Exception {
        ListenerHolder th = new ListenerHolder();
        List<TestObject<String>> list = createTestObjectList();
        /* *** compiler error here *** */
        th.addListener(TestObject.class, list);
    private final static List<TestObject<String>> createTestObjectList() {
        List<TestObject<String>> list = new ArrayList<TestObject<String>>();
        return list;
    private final static class ListenerHolder {
            /* *** my generic method *** */
            public <T> void addListener(Class<T> listenerType, List<T> listener) { }
    private final static class TestObject<T> { }
}The compiler error is:
C:\java\Main.java:11: <T>addListener(java.lang.Class<T>,java.util.List<T>) in Main.ListenerHolder cannot be applied to (java.lang.Class<Main.TestObject>,java.util.List<Main.TestObject<java.lang.String>>)
Thanks in advance,
Dan

dandubois wrote:
Thanks for the help, that is exactly what I wanted to know.
It didn't occur to me that TestObject<T> would in some respects be considered as an 'extends' of TestObject as I know the compiler converts them all back to plain TestObjects.Maybe I should have written TestObject<?>, to make it more obvious. There's some supertype/subtype relation diagram in the Generics FAQ somewhere, if you need more detailed information.
In the end, I think jtahlborn's solution might be more appropriate in the described scenario, so you should go for it.

Similar Messages

  • How to specify ");" as a regular expression in split method of String class

    How to specify ");" as a regular expression in split method of String class using delimeters?

    Sorry, you can't specify that by using delimiters. Mostly because this requirement makes no sense.
    Do you rather need "\\);"?

  • How link LC (Prod Type 56A) with a loan to display as utilization in TM_60

    Hi,
    I have a  Letter of Credit  and I already created a facility (Product Type 56A) by 1 mill usd, then I need to utilized this LC with a loan  Interest rate instrument (55A) transaction type 200 by 300,000 usd.
    Then I executed the transaction TM_60, But the colum Utilization is cero.
    How I could link the Credit line (Product type 56A) with the Interest rate instrument (55A) to see the Utilization in the report in transaction TM_60?
    Could anybody help me please?
    Thanks,
    Adriana

    The steps are:
    1.- In transaction ftr_create I created the Bilateral Facility with product type 56A, in tab Profiles I Created a new credit line.
    2.- In transaction ftr_create I created Interest rate instrument with product type 55A, in tab Administr. in the file Facility I need to select the button created and assignment the number of the transaction of the facility that I created in the step 1.
    3.-I executed the report TM_60
    Thanks,
    Adriana

  • How to Keep Content Types Current with Updated Data

    Let’s say that I have four content types—content type 1, content type 2, content type 3, and content type 4—all based on the same list, say list A.
    Each content type has its own workflow.
    When the workflow for content type 1 is completed, the data is saved to an individual item, say item Z, in a separate list, list B.
    When the workflow for content type 2 is completed, the data is saved to the same item (item Z) in list B. The reason that there are two lists is that the creation of content types causes new items to be created, but the each
    new item must reference data from the previous item. That means that data has to be copied from the first item to the second item. But what happens to the data in the second item when data from the first item is changed? The solution is to have a single item
    in another list to which all content types write their data.
    What I need to know is how can all the content types retrieve data from list B when those content types are based on list A? For example, let's say that content type 3 uses data originally input through content type 1. As the
    user inputs and saves data through content type 3 he sees data that had been originally input through content type 1. Another user then accesses content type 1 to update and save data through it. When content type 3 is opened again that user will not see the
    updated data entered through content type 1 because it is tied to a different item. The solution seems to be for all content types to save their data to the same item in another list. But then how can those content types be designed so that when they open
    they show updated data from List B when those content types are based on List A?
    Other applications have the notion of a folder containing all the up-to-date data fields. Another way to look at this problem is to state what SharePoint 2007 does to mimic the notion of a folder.

    Thanks for responding, but I don't think that the solution provided solves my problem. What you described will keep the item in List B in sync with the changes made to List A. However, the content types from List A will not be in sync when they are opened
    from List A. Say content type 1 makes changes to various fields. When content type 3 opens it displays some of the fields that content type 1 changed; however, content type 3 and content type 1 by definition display different items--and those items are not
    in sync. Either I have to copy the updated item from List B back to the related items in List A or there has to be another solution.
    Is it possible to have a workflow update all the items in a list based on a key field whenever changes are made to that item. Say content types 1, 2, 3, and 4 already exist and each refers to a different item in List A, but they are "tied" together
    by a key field. When content type 1 is reopened and changes are made, is it possible to iterate over the items in a list to find other items whose key field matches the key field from content type 1? If so, then when matching items are found the fields in
    them can be updated by the same changes made to content type 1.
    If this latter scenario is possible, how is that iteration set up in a SharePoint 2007 workflow? Thanks again.

  • Question on thread safety with Sevlet action method

    I have an application that runs well but seems to have trouble with multiple users and I suspect that there is some thread safety issue involved.
    It is a Struts application and I have all of my execute methods of the Acton classes are all synchronized which I thought would take care of any cross user issues but it does not seem to have done that.
    The Action classes do have some instance variables which may be the problem as well as possibly a few utility string classes with static methods that are not synchornized. I keep some db connection cached in the session object but this should not be shared between users.
    My question is, with the execute method synchronized how or where could I be getting crosstalk between users (each with their own sessions)?
    I was thinking of packaging my Action class as seperate object with the actual Action class just allocate what I need (messages and locale) and pass them through a freshly instantiated "old action class". That should solve any instance variable cross talk.
    I am assuming that any local variables in the execute method would not have any exposure as they should be thread specific and allocated on the runtime stack for that thread call.
    Am I missing anything important?
    Thanks in advance
    ---John Putnam

         * Creates a new instance of a {@link javax.xml.parsers.DocumentBuilder}
         * using the currently configured parameters.
        public DocumentBuilder newDocumentBuilder()
            throws ParserConfigurationException
            /** Check that if a Schema has been specified that neither of the schema properties have been set. */
            if (grammar != null && attributes != null) {
                if (attributes.containsKey(JAXPConstants.JAXP_SCHEMA_LANGUAGE)) {
                    throw new ParserConfigurationException(
                            SAXMessageFormatter.formatMessage(null,
                            "schema-already-specified", new Object[] {JAXPConstants.JAXP_SCHEMA_LANGUAGE}));
                else if (attributes.containsKey(JAXPConstants.JAXP_SCHEMA_SOURCE)) {
                    throw new ParserConfigurationException(
                            SAXMessageFormatter.formatMessage(null,
                            "schema-already-specified", new Object[] {JAXPConstants.JAXP_SCHEMA_SOURCE}));               
            try {
                return new DocumentBuilderImpl(this, attributes, features, fSecureProcess);
            } catch (SAXException se) {
                // Handles both SAXNotSupportedException, SAXNotRecognizedException
                throw new ParserConfigurationException(se.getMessage());
        }It appears to be thread-safe. The 'attributes' and 'features' instances variables are hashtables, which are synchronized. Unless you are modifying DocumentBuilderFactory itself in another thread (say, changing whether it is namespace aware), I do not see any issues with a simple call to newDocumentBuilder().
    - Saish

  • Problem with seting action method to a Hyperlink object

    Hi there,
    as the subject says, I have a problem wih setting the action method of a Hyperlink object. Here is how the program is organized:
    I have an external bean which generates an ArrayList of Hyperlink objects. In the backing bean of my web page I call a method from the above mentioned external bean to generate the list of hyperlink objects. After that in the page bean I insert the hyperlink objects in GridPanel component. So far everything works fine, but the action method of the Hyperlink objects is not called and I can't understant why.
    Here is how I add the objects to the GridPanel component:
    private void populateGridPanel()
            Hyperlink hyper;
            for(int i=0; i< checkboxList.size(); i++)
                    hyper = (Hyperlink) hyperlinkList.get(i);
                    vehicleGridPanel.getChildren().add(hyper);
        }All properties of the Hyperlink objects are set in the external bean not in the page bean, here is how:
    //action method executed when the hyperlink is clicked
    MethodBinding mb = (MethodBinding) FacesContext.getCurrentInstance().getApplication().createMethodBinding("#{Page1.hyperlink_action}", null);
    veHyperlink.setAction(mb);The populateGridPanel() method is called in the init() method of the page bean, after the initialization of all other components.
    An interesting fact is that if I manually drag-n-drop a hyperlink object to my page and programatically set its action method with the code above everything works fine. But using the same code for the dynamically generated hyperlink objects inserted in the grid panel doesn't work.
    Any kind of help is highly appreciated.
    Thanks!
    Message was edited by:
    panayot

    I got this use case to work as follows:
    1. Drag a Grid Panel and set its columns property to 1.
    2. Drag a Message Group.
    3. Use the following code in Page1:
    public void prerender() {
    populateGridPanel();
    private void populateGridPanel() {
    if (gridPanel1.getChildren().size() > 0) {return;}
    for (int i = 0; i < 3; i++) {
    Hyperlink veHyperlink = new Hyperlink();
    //action method executed when the hyperlink is clicked
    MethodBinding mb = (MethodBinding) FacesContext.getCurrentInstance().getApplication().createMethodBinding("#{Page1.hyperlink_action}", null);
    veHyperlink.setAction(mb);
    veHyperlink.setText("dynamic hyperlink " + i);
    veHyperlink.setId("dynamicHyperlink" + i);
    gridPanel1.getChildren().add(veHyperlink);
    public void hyperlink_action() {
    info("Yup it worked at: " + new java.util.Date());
    4. Fix imports, Run, and then click on the hyperlinks.

  • Help with creating a method within a class

    I need help creating another method within the same class.
    Here is part of my progam, and could anyone help me convert the switch statement into a seperate
    method within the same class?
    import javax.swing.JOptionPane;
    public class Yahtzee
         public static void main (String[] args)
              String numStr, playerStr, str, tobenamed;
              int num, times = 13, roll, x, y, maxRoll = 3, z = 0, t;
              int firstDie, secondDie, thirdDie, fourthDie, fifthDie, maxDie = 5, reroll;
              int rerolling = 0, categoryChoice, score, nextDie1, nextDie2, nextDie3, nextDie4;
              Die die1, die2, die3, die4, die5;
              do
              numStr = JOptionPane.showInputDialog ("Enter the number of player: ");
              num = Integer.parseInt(numStr);
              while (num < 1 || num > 6); //end of do loop
              String [] player = new String[num];
              // boolean //finsih later to make category choice only once.
              for (x = 0; x < num; x++)
                   playerStr = JOptionPane.showInputDialog ("Name of Player" + (x + 1) + " :");
                   player[x] = playerStr;  
              } //end of for loop
              die1 = new Die();
               die2 = new Die();
               die3 = new Die();
               die4 = new Die();
               die5 = new Die();
              int scoring [][] = new int [num][13];//scoring aray
              int[] numDie = new int[maxDie];
              String[][] usedCategory = new String [num][times];
              for (x=0; x < 13; x++)
                   for (y = 0; y < num; y++)
                      usedCategory[y][x] = " ";
              for (int choices = 0; choices < times; choices++)
                   //player turns for loop.
                   for (x = 0; x < num; x++)
                        //rolls the die;
                          for (y = 0; y < maxDie; y++)
                               numDie[y] =  die1.roll();
                     numStr = JOptionPane.showInputDialog (player[x] + "\n~~~~~~~~~~~~~~~~~~~~~~~"
                                                                            + "\nDie1: " + numDie[0]
                                                                                + "\nDie2: " + numDie[1]
                                                                                + "\nDie3: " + numDie[2]
                                                                                + "\nDie4: " + numDie[3]
                                                                                + "\nDie5: " + numDie[4]
                                                                                + "\nWhich dice do you want to reroll");
                    reroll = numStr.length();
                    if (reroll == 0)
                        t = maxRoll;
                   else{                                                      
                    //reroll
                         for(t = 0; t < maxRoll; t++ )
                             for (y = 0; y < reroll; y++)
                                    rerolling = numStr.charAt(y);
                                 //create another mwthod later.
                                    switch (rerolling)
                                         case '1':
                                              numDie[0] =  die1.roll();
                                              break;
                                         case '2':
                                              numDie[1] =  die1.roll();
                                              break;
                                         case '3':
                                              numDie[2] =  die1.roll();
                                              break;
                                         case '4':
                                              numDie[3] =  die1.roll();
                                              break;
                                         case '5':
                                              numDie[4] =  die1.roll();
                                              break;
                                         default:
                                         t = maxRoll;//to be changed
                                    } //end of switch class
                              }//end of reroll for loop
                                   JOptionPane.showMessegeDialog (player[x] + "\n~~~~~~~~~~~~~~~~~~~~~~~"
                                                                                      + "\nDie1: " + numDie[0]
                                                                                          + "\nDie2: " + numDie[1]
                                                                                          + "\nDie3: " + numDie[2]
                                                                                          + "\nDie4: " + numDie[3]
                                                                                          + "\nDie5: " + numDie[4]
                                                                                          + "\nWhich dice do you want to reroll"
                                               switch (rerolling)
                                         case '1':
                                              numDie[0] =  die1.roll();
                                              break;
                                         case '2':
                                              numDie[1] =  die1.roll();
                                              break;
                                         case '3':
                                              numDie[2] =  die1.roll();
                                              break;
                                         case '4':
                                              numDie[3] =  die1.roll();
                                              break;
                                         case '5':
                                              numDie[4] =  die1.roll();
                                              break;
                                         default:
                                         t = maxRoll; //not really anything yet, or is it?
                                    } //end of rerolling switch class
                                       //categorychoice = Integer.parseInt(category);
                              }//end of t for loop            
                   }//end of player for loop.

    samuraiexe wrote:
    well, i should have said it is a yahtzee program, and i ask the user what they want to reroll and whatever number they press, the switch will activate the case and the array that it will reroll.
    HOw would i pass it as an argument?You put it in the argument list. Modifying your original code a bit:
    public static void switchReroll (int[] dice, int position) {
         switch (position) {
         case '1':
                 dice[0] =  die1.roll()
                 break;
         case '2':
                 dice[1] =  die1.roll();
                 break;
         case '3':
                 dice[2] =  die1.roll();
                     break;
         case '4':
                 dice[3] =  die1.roll();
                 break;
         case '5':
                  dice[4] =  die1.roll();
                 break;
         default:
                 t = maxRoll;//to be changed
        } //end of switch
    }which you could then call as this:
    switchReroll(numDie, reroll);Note that your code still isn't done; the above won't compile. This is just an example of how you could pass the stuff as an argument (and note how the values have different names in the main method than in the switchReroll method -- this works, but also note that it's the same array of ints in both).
    By the way -- you really don't need a switch statement for this. You can do the same thing with a couple lines of code, which would lessen the advantage for a separate method. But I'd suggest continuing down this path, and then you could change the implementation of the method later.

  • How to get nat type 1 with airport extreme and ps3?

    I use airport extreme as my default router. I have my ps3 connected to a separate airport in a different room. I can only get nat type 2 and want to get nat type 1 as I can barely connect to any hosts online.

    NAT type 1 is when you connect your PS3 directly to your modem with no router in between.  The problem with this is that there will be no way to share your internet connections with other devices.  NAT type 2 is where you have a router in between your modem and your PS3, and NAT type 3 is where you have some or all needed ports blocked which is where you would have issues.
    NAT type 2 is a correct way for your PS3 to work, and your wireless connection strength may be the reason for connection issues.

  • How to recover file type (creator) with SFTP transfer?

    I'm using SFTP to move data files from one 10.6 system to another 10.6 system. On the original system, double-clicking them opens them in the right program. But the names don't have file extensions, and when they are pulled onto a new system, I don't know what software to use to open them (I can't tell what kind of files they are). What can be done to either pull the meta-data with them (whatever their host OS uses to know how to open them) or to figure out what they are from their contents?

    I have solved!!! the problem was on the .mp3 files included on file, after I have converted all the mp3 on mp4 (5 files corrupted was not converted), reload new files on mp4 and all it's ok (saved and closed saved and closed)

  • How do i open EPS file with "rasterize generic EPS format" options in photoshop CS?

    Hi please can someone help!?
    I'm using Photoshop CS on mac- when i open EPS format files i usually get the "rasterize generic EPS format" option so that i can select the size i want the file to be etc without losing quality. However on one file i've opened before i don't seem to be getting that option at all, if i open the EPs file it just goes to a standard size automatically and doesn't give me the chance to change the size.  This is the same file that i have used since being sent the file, i've not resaved it. It used to give me the rasterize generic EPS format option but it no longer works.  Any ideas how i can make those options appear when opening or how i can rasterize/resize it once open without losing quality?
    Just to be clear, i still get the rasterize generic EPS format option when opening other EPS files but it seems not with this one particular file.
    Many Thanks
    Ross

    Encapsulated PostScript-files can contain either vector-content (in which case one gets prompted when opening with Photoshop), pixel-content (in which case Photoshop opens straight away) or a mixture (same as the first case).
    When a file has been rasterized that’s that, You may want to go back to the original file if You can locate it.
    Edit: Sorry, I read Your original post carelessly …
    Have You tried opening the original file in Illustrator yet?

  • Type incompatibility error using remove method of ArrayList class

    This method:
    public int removeFromQueue ( int iIndex )
    return queueFeed.remove( new Integer(iIndex) ) ;
    returns a type error after remove saying its found a boolean but is looking for an int. I want to remove the int value in the ArrayList and use it elsewhere.
    Confused.

    if you are trying to remove an element at the particular index say 5
    i.e., is int value = 5 then you get the return as Object that has been removed. Since ArrayList hols all obejcts and not any primitive data types.
    if you are trying to remove the Object say Integer(5) then you get the return as boolean specifying whether it has been sucessfull or not.
    so you can use either of the following as....
    // To remove Integer Object from Queue
    public boolean removeFromQueue ( int iIndex )
    return queueFeed.remove( new Integer(iIndex) ) ;
    // To remove Object from Queue at specific position
    public Integer removeFromQueue ( int iIndex )
    return (Integer)queueFeed.remove( iIndex ) ;
    }

  • Can someone help with this getPos method of aList class ?

    public class AList<T> implements ListInterface<T>
    private T[] entries; // array of list entries
    private int length; // current number of entries in list
    private static final int MAX_SIZE = 50; // max length of list
    public AList()
    this(MAX_SIZE); // call next constructor
    } // end default constructor
    public AList(int maxSize)
    length = 0;
    entries = (T[]) new Object[maxSize]; // necessary cast to generic type
    } // end constructor
         public boolean add(T newEntry)
              boolean isSuccessful = true;
              if (!isFull())
         // Assertion: Length of list < length of array
         assert length < entries.length;
         // position of new entry will be after last entry in list,
         // that is, at position length+1; corresponding array index is
         // 1 less than this position, so index is length
         entries[length] = newEntry;
                   length++;
              else
                   isSuccessful = false;
              return isSuccessful;
         } // end add
         public boolean add(int newPosition, T newEntry)
         boolean isSuccessful = true;
         if (!isFull() && (newPosition >= 1) && (newPosition <= length + 1))
         makeRoom(newPosition);
         entries[newPosition - 1] = newEntry;
         length++;
         else
         isSuccessful = false;
         return isSuccessful;
         } // end add
         public T remove(int givenPosition)
         T result = null; // return value
         if ((givenPosition >= 1) && (givenPosition <= length))
         assert !isEmpty();     
    result = entries[givenPosition - 1]; // get entry to be removed
         // move subsequent entries toward entry to be removed,
         // unless it is last in list
         if (givenPosition < length)
         removeGap(givenPosition);
         length--;
         } // end if
         return result; // return reference to removed entry, or
    // null if either list is empty or givenPosition
    // is invalid
    } // end remove
         public T getEntry(int givenPosition)
         T result = null; // result to return
         if ((givenPosition >= 1) && (givenPosition <= length))
         assert !isEmpty();
              result = entries[givenPosition - 1];
         } // end if
         return result;
         } // end getEntry
    public int getPos(T anItem)
    }

    I would recommend using a for loop to compare anItem to each member of the array. If you get a match, return the index.

  • Type incompatibility error using'remove' method in ArrayList class.

    This method:
    public int removeFromQueue ( int iIndex )
    return queueFeed.remove( new Integer(iIndex) ) ;
    returns a type error after remove saying its found a boolean but is looking for an int. I want to remove the int value in the ArrayList and use it elsewhere.
    Confused.

    A - Yeah I get it now mate.
    But the API states that the the object is returned:
    "Returns:
    the element that was removed from the list. " i.e my
    integer value that I know is there
    so why does it return a boolean to me. Am I deploying
    incorrectly.no, the method you are calling takes an Object as a parameter
    look in the docs here for the method remove(Object)
    you will see it returns a boolean
    http://java.sun.com/j2se/1.4.2/docs/api/java/util/AbstractCollection.html#remove(java.lang.Object)it is a method inherited from AbstractCollection and is different than
    the method shown in the javadoc for ArrayList that takes an int
    as a parameter.
    A
    hope this helps

  • PowerShell-EWS How to use .Forward Method of EmailMessage Class

    Hello, 
    im new to PowerShell and EWS and would like to know how to forward an E-Mail with the .Forward Method of the EmailMessage Class.
    Is it possible to also forward an Email with an FileAttachment?
    I already have access to the Messages i want to forward but i cant figure out how to .Forward these Messages.
    Thank you for your help
    Greetings 
    Ingo

    >> Is it possible to also forward an Email with an FileAttachment?
    Yes doing a normal forward is EWS should maintain the attachment on the message eg the following would forward the last email in the Mailbox
    $folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox,$MailboxName)
    $Inbox = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)
    $ivItemView = New-Object Microsoft.Exchange.WebServices.Data.ItemView(1)
    $fiItems = $null
    $fiItems = $service.FindItems($Inbox.Id,$ivItemView)
    $messageBodyPrefix = "This is message that was forwarded by using the EWS Managed API";
    $addresses = New-Object Microsoft.Exchange.WebServices.Data.EmailAddress[] 1
    $addresses[0] = "[email protected]";
    $fiItems.Items[0].Forward($messageBodyPrefix, $addresses);
    If your looking to forward the actual message as an attachment you can use something like
    http://gsexdev.blogspot.com.au/2013/07/forwarding-message-as-attachment-using.html
    Cheers
    Glen

  • HT201304 make and Apple ID with out payment method

    How to make and Apple ID with out payment method in iTunes 10 or superior?

    I made this video to help you: http://www.youtube.com/watch?v=DySX3DEryZ8&feature=plcp

Maybe you are looking for

  • New GTXGe Force770 video card but Premiere pro not seeing it?

    Hi - this is probably a dumb question.. but i have upgraded with a new video card which is CUDA enabled but in New Project Settings the Video render box is greyed out. What do I have to do to have Premiere & Photoshop use the maximum power of this ne

  • RMBP 15" right channel output not working properly

    Hello, I recently purchased a Retina Macbook Pro 15" no more than 3 months ago. Today I just noticed that whenever I connect my headphones I can hear the left channel clearly but the right channel is a lower volume and distorted. at first I thought i

  • Is there anyway i can create a new apple id with my outlook email

    somebody help me before this ****** me off!

  • Apex ORA-07445 using db links

    Have installed apex OK and working well. When using forms based on source from database links regularly crashes with the above exception. Please see fragments of trace and alert_xe.log. Current SQL is always COMMIT Any suggestions would be great. Tha

  • Appending results returned by multiple queries into 1 row?

    I have multiple select queries in a procedure. Each query processes different tables and returns one or two columns that need to be inserted to a staging table. The results of these queries should be appended to one row. select col1, col2 from table1