Generic method and HashMap.

I've the following code. The compiler throws error. for the following code. I need this in an project. My objective is to allow multiple type for the first parameter of the method "meth". One implementation of someInterface supports one type, another implementation of someInterface supports other types.
Why the compiler throws error for the method that is shown as bolded.
public interface someInterface<T>
public<U> void meth(U param1, T param2);
public class someClass implements someInterface<HashMap<Enum, Object>>
public<HashMap<Enum, Object>> void meth(HashMap<Enum, Object> param1, HashMap<Enum, Object> param2)
If i implement the method in the following way no compilation error is showing up. Why is this?
public<String> void meth(String param1, HashMap<Enum, Object> param2)
null

Hi dannyyates, thanks for your response. Here is the following code that produces compilation error. Can you help me to know why this error is coming. It will be of great help to me.
It is strange to me the method generic works for String, but not working for HashMap<Contact, Object>.
My objective is to allow multiple type for the first parameter of the method "meth". One implementation of someInterface supports one type, another implementation of someInterface supports other types.
I'm getting the following error for the below code:
"gen.java": > expected at line 31, column 15
"gen.java": illegal start of type at line 34, column 1
"gen.java": <identifier> expected at line 33, column 2
"gen.java": '(' expected at line 34, column 1
gen.java
import java.util.HashMap;
interface someInterface<T>
public<U> void meth(U param1, T param2);
enum Contact
  NAME, NUMBER
// This class need first parameter for meth as HashMap<Contact, Object>
class someClass1 implements someInterface<HashMap<Contact, Object>>
public<HashMap<Contact, Object>> void meth(HashMap<Contact, Object> param1, HashMap<Contact, Object> param2)
// This class need first parameter for meth as String
class someClass2 implements someInterface<HashMap<Contact, Object>>
public<String> void meth(String param1, HashMap<Contact, Object> param2)
public class gen
  public static void main(String args[])
}Message was edited by:
mkumar180875
Message was edited by:
mkumar180875
null
Message was edited by:
mkumar180875

Similar Messages

  • Generic method and wildcards

    Suppose I have this simplified code to do dynamic mapping between specific classes. My question is: the addItem and getItem functions
    are pretty similar however addItem compiles fine and getItem raises compilation error:
    Type mismatch: cannot convert from Class<capture#5-of ? extends List<? extends Object>> to Class<P>
         private Map<Class<? extends Object>,
         Class<? extends List<? extends Object>>> map =
              new HashMap<Class<? extends Object>,
              Class<? extends List<? extends Object>>>();
         public Test() {
              getItem(Object.class);
         public <T extends Object, P extends List<T>> void addItem(Class<T> clz, Class<P> list) {
              map.put(clz, list);
         public <T extends Object, P extends List<T>> Class<P> getItem(Class<T> clz) {
              return map.get(clz);
         }

    Sergey_M. wrote:
    OK, thank you for the response. Then the actual question is how to achieve this functionality:
    1)Store mapping between two referenced classes, for example, Class<? extends MyClass> and Class<? extends List<? extends MyClass>>.
    I mean if we have class MyClass then pair will be (MyClass.class, MyList.class) where MyList implements List<MyClass>.The way you were doing it is fine.
    2)Provide generic method to get second class by supplying the first one.You can do this fine, but the exact type of list will of course be unknown by the calling code (if it knew the type of list it needed, why bother calling getItem in the first place?).
    Just change your method to:
    public <T extends Object> Class<? extends List<?>> getItem(Class<T> clz) {
              return map.get(clz);
         }And by then even the T is not needed, just use:
    public Class<? extends List<?>> getItem(Class<?> clz) {
       return map.get(clz);
    }I am fairly, but not fully sure that you never need <? extends Object>, as that is always just a more verbose way of saying <?>.

  • Generic methods and inheritance

    Hello,
    I have a class structure like this:
    A - - - - > IA (A implements IA)
    C - - - - > IC -------> IB (C implements IC extends IB)
    In IA I have a method create that returns <T extends IB<T>>:
    public interface IA {
        public <T extends IB<T>> T create();
    }IB:
    public interface IB<T> {  
    }IC extends IB like this:
    public interface IC extends IB<IC> { 
    }C implements IC:
    public class C implements IC{
    }Finally the problem: I wan to implement A in order to return an IC in the create method:
    public class A implements IA{
        public IC create() {
            IC c = new C();
            return c;
    }This compiles but I get this warning: 'A.java uses unchecked or unsafe operations.'
    What is the proper way to create such a structure?
    Thanks,
    Miguel

    you can try giving more horrible things, like giving the class you want in the method params, like :
    create(Class<IB> clazz);and then use reflection to create the instance :
    clazz.getInstance();But it's quite heavy, I think...

  • How to create a generic method?

    Hi,
      I am using a std task TS01200205 to create instance for a BOR object. There are 2 key fields. I want to pass these 2 to the ObjectKey field.
    As for as I know, we have to concatenate these two Keyfields and assign it to 'Object Key' parameter.
      How can I concatenate the 2 strings in my Workflow? Is there any std way of doing it?
    Also what is a generic method? How to create it? Can I make use of generic method to achieve this?
    Thanks,
    Sivagami

    If you want to use it in different workflows the best solution is probably to define an interface and define and implement the method there (a nice thing about BOR interfaces is that you can provide an implementation and not just the definition).
    All you then need to do is let your object type(s) implement that interface, which only requires adding the interface since the implementation has been done already.
    However, I am not saying this is a good way of approaching things, I'm just telling you how you can implement what you suggest.

  • Jax-ws 2.1 - problems returning hashtable and hashmap

    Hi,
    We're developing a set of applications that communicate via web services.
    The company decided that to do this we should use jax-ws 2.1.
    Everything is going ok, its really easy to use, except for a web method that returns a java.util.Hashtable.
    In the endpoint there's no problem, it compiles and deploys to a tomcat 5.5 without a problem.
    The client can access the wsdl via url, download it and create the necessary files (we use netbeans 5.5 for this).
    We can invoke the method getConfig without a problem, but the object returned only has the java.lang.Object 's methods, not the java.util.Hastable 's .
    Endpoint:
    package xxx.cdc_pm_i;
    import java.util.Hashtable;
    import javax.jws.WebMethod;
    import javax.jws.WebParam;
    import javax.jws.WebService;
    import javax.xml.bind.annotation.*;
    @WebService()
    public class cdc_pm_i{
    @WebMethod
    public Hashtable getConfig() {
    Hashtable<String,String> config = new Hashtable<String,String>();
         config.put("1","1");
         config.put("2","2");
    return config;
    Client:
    try { // Call Web Service Operation
    xxx.CdcPmIService service = new xxx.cdc_pm_i.CdcPmIService();
    xxx.cdc_pm_i.CdcPmI port = service.getCdcPmIPort();
    // TODO process result here
    xxx.cdc_pm_i.Hashtable result = port.getConfig();
    } catch (Exception ex) {
         ex.printStackTrace();
    I'm fairly unexperienced in Web Services and i have no idea why this works for any kind of return object (as long as its serializable) and has this problem with hashtables and hashmaps.
    Any idea on how to solve this?
    Thanks in advance,
    Rui

    Didn't find the solution for this, but any object that contains an Object in its methods / attributes had the same problems, so i just built my own table that only supports Strings and the problem was solved.
    If anyone knows why i had this problem and wants to share a solution, please do so.

  • Hiding methods and attributes while inheriting

    Hello All,
    This is kinda urgent. While making a subclass I want to block access to methods and attributes of super class when anone creates an object of sub-class. In my particular situation I cannot override the methods.
    Let me explain it with an example:
    I have a class A which contains an attribute of type Object. All the methods accept Object type parameters and act accordingly. Now I want to create a sub-class B which acts on Strings only. I can create a wrapper to class A but I want to add some behavior which is specific to strings and use rest of the behavior as in class A. I cannot override the methods of class A because they take Objects as parameters whereas in class B the same methods take string as parameters.
    I hope you have understood the problem. Please reply ASAP.
    Thanks in advance

    Sorry the diagram turned out wrong. ObjectClass and StringClass are both supposed to be derived
    from the AbstractBaseClass.
    This method is one way to achieve what you want. You make an AbstractBaseList class that has only
    protected methods that take objects.
    To implement a generic Object version of this class you extend it and override the protected methods in
    the AbstractBaseList class to make them public.
    To implement a String list you extend the AbstractBaseList class and override the protected methods to
    make them public (but change the type of the parameters).
    The only problem with this approach is that the return types of the methods cannot be changed. Therefore
    I recommend the AbstractBaseList implement a method called
    protected Object getByIndex(int i) {
    // do list type stuff in here
    Then the ObjectList can implement
    public Object get(int i) {
    return super.getByIndex(i);
    and the StringList can implement
    public String get(int i) {
    return (String) super.getByIndex(i);
    In effect all you need to do is to implement wrapper classes that enforce type casting on the Object based
    set/get values.
    Another option is to use JDK1.5 with its generics classes. These effectivly allow you to specify which type of
    object an instance of a class accepts.
    Another question. What is the matter with the Collections classes provided in the JDK?
    matfud

  • StartDrag using Generic method in Actionscript 3

    Hi,
    AS3:
    How to get general id (or) name from xml loaded images. bcoz, i want to drag and drop that images in generic method. Now, i currently used the event.target.name for each one.
    So, code length was too large. See my code below.
    /*********loading images through xml********/
    var bg_container_mc:MovieClip
    var bg_bg_myXMLLoader:URLLoader = new URLLoader();
    bg_bg_myXMLLoader.load(new URLRequest("xml/backgroundimages.xml"));
    bg_bg_myXMLLoader.addEventListener(Event.COMPLETE, processXML_bg);
    function processXML_bg(e:Event):void {
              var bg_myXML:XML=new XML(e.target.data);
              columns_bg=bg_myXML.@COLUMNS;
              bg_my_x=bg_myXML.@XPOSITION;
              bg_my_y=bg_myXML.@YPOSITION;
              bg_my_thumb_width=bg_myXML.@WIDTH;
              bg_my_thumb_height=bg_myXML.@HEIGHT;
              bg_my_images=bg_myXML.IMAGE;
              bg_my_total=bg_my_images.length();
              bg_container_mc = new MovieClip();
              bg_container_mc.x=bg_my_x;
              bg_container_mc.y=bg_my_y;
              ContentHead.addChild(bg_container_mc);
              for (var i:Number = 0; i < bg_my_total; i++) {
                       var bg_thumb_url=bg_my_images[i].@THUMB;
                        var bg_thumb_loader = new Loader();
                       bg_thumb_loader.load(new URLRequest(bg_thumb_url));
                       bg_thumb_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, thumbLoaded_bg);
                       bg_thumb_loader.name="bg_load"+i;
                       bg_thumb_loader.addEventListener(MouseEvent.MOUSE_DOWN, bg_down)
                       bg_thumb_loader.x = (bg_my_thumb_width-18)*bg_x_counter;
                       bg_thumb_loader.y = (bg_my_thumb_height-45)*bg_y_counter;
                       if (bg_x_counter+1<columns_bg) {
                                 bg_x_counter++;
                       } else {
                                 bg_x_counter=0;
                                 bg_y_counter++;
    function thumbLoaded_bg(e:Event):void {
              var my_thumb_bg:Loader=Loader(e.target.loader);
             var sprite:Sprite = new Sprite();
              var shape:Shape = new Shape();
              shape.graphics.lineStyle(1, 0x0098FF);
              shape.graphics.drawRect(e.target.loader.x-2, e.target.loader.y-2, e.target.loader.width+4, e.target.loader.height+4);
              sprite.addChild(shape);
              sprite.addChild(my_thumb_bg);
              sprite.x=4;
              bg_container_mc.addChild(sprite);
              my_thumb_bg.contentLoaderInfo.removeEventListener(Event.COMPLETE, thumbLoaded_bg);
    //  get name for each image. 
    I want to change this code in generic method. do needful.
    function bg_down(event:MouseEvent):void {
              var bg_name:String=new String(event.currentTarget.name);
              var bg_load:MovieClip=event.currentTarget as MovieClip;
              if (event.currentTarget.name=="bg_load0") {
                      var alaska_mc:alaska_png=new alaska_png();
                       addChild(alaska_mc);
                       alaska_mc.x=stage.mouseX;
                       alaska_mc.y=stage.mouseY;
                       alaska_mc.name="alaska_duplicate"+alaska_inc;
                       alaska_inc++;
                       alaska_mc.startDrag(false);
                      alaska_mc.addEventListener(MouseEvent.MOUSE_UP, stdrag);
                       alaska_mc.addEventListener(MouseEvent.MOUSE_UP, stdrag);
              if (event.currentTarget.name=="bg_load1") {
                       var lake_mc:lake_png=new lake_png();
                       addChild(lake_mc);
                       lake_mc.x=lake_mc.mouseX;
                       lake_mc.y=lake_mc.mouseY;
                       lake_mc.name="lake_duplicate"+lake_inc;
                       lake_inc++;
                       lake_mc.startDrag(false);
                       lake_mc.addEventListener(MouseEvent.MOUSE_UP, stdrag);
              if (event.currentTarget.name=="bg_load2") {
                       var mountn_mc:mountn_png=new mountn_png();
                       addChild(mountn_mc);
                       mountn_mc.x=mountn_mc.mouseX;
                       mountn_mc.y=mountn_mc.mouseY;
                       mountn_mc.name="mountn_duplicate"+mountn_inc;
                       mountn_inc++;
                       mountn_mc.startDrag(false);
                       mountn_mc.addEventListener(MouseEvent.MOUSE_UP, stdrag);
              if (event.currentTarget.name=="bg_load3") {
                       var town_mc:town_png=new town_png();
                       addChild(town_mc);
                       town_mc.x=town_mc.mouseX;
                       town_mc.y=town_mc.mouseY;
                       town_mc.name="town_duplicate"+town_inc;
                       town_inc++;
                       town_mc.startDrag(false);
                       town_mc.addEventListener(MouseEvent.MOUSE_UP, stdrag);
              if (event.currentTarget.name=="bg_load4") {
                       var water_mc:water_png=new water_png();
                       addChild(water_mc);
                       water_mc.x=water_mc.mouseX;
                       water_mc.y=water_mc.mouseY;
                       water_mc.name="water_duplicate"+water_inc;
                       water_inc++;
                       water_mc.startDrag(false);
                      water_mc.addEventListener(MouseEvent.MOUSE_UP, stdrag);
              if (event.currentTarget.name=="bg_load5") {
                       var city_mc:city_png=new city_png();
                       addChild(city_mc);
                       city_mc.x=city_mc.mouseX;
                       city_mc.y=city_mc.mouseY;
                       city_mc.name="city_duplicate"+city_inc;
                       city_inc++;
                       city_mc.startDrag(false);
                      city_mc.addEventListener(MouseEvent.MOUSE_UP, stdrag);
              if (event.currentTarget.name=="bg_load6") {
                        var citywide_mc:citywide_png=new citywide_png();
                       addChild(citywide_mc);
                       citywide_mc.x=citywide_mc.mouseX;
                       citywide_mc.y=citywide_mc.mouseY;
                       citywide_mc.name="citywide_duplicate"+citywide_inc;
                       citywide_inc++;
                       citywide_mc.startDrag(false);
                      citywide_mc.addEventListener(MouseEvent.MOUSE_UP, stdrag);
              if (event.currentTarget.name=="bg_load7") {
                       var downtown_mc:downtown_png=new downtown_png();
                       addChild(downtown_mc);
                       downtown_mc.x=downtown_mc.mouseX;
                       downtown_mc.y=downtown_mc.mouseY;
                       downtown_mc.name="downtown_duplicate"+downtown_inc;
                       downtown_inc++;
                       downtown_mc.startDrag(false);
                      downtown_mc.addEventListener(MouseEvent.MOUSE_UP, stdrag);
              if (event.currentTarget.name=="bg_load8") {
                       var powerlines_mc:powerlines_png=new powerlines_png();
                       addChild(powerlines_mc);
                       powerlines_mc.x=powerlines_mc.mouseX;
                       powerlines_mc.y=powerlines_mc.mouseY;
                       powerlines_mc.name="powerlines_duplicate"+powerlines_inc;
                       powerlines_inc++;
                       powerlines_mc.startDrag(false);
                      powerlines_mc.addEventListener(MouseEvent.MOUSE_UP, stdrag);
              if (event.currentTarget.name=="bg_load9") {
                       var tropical_mc:tropical_png=new tropical_png();
                       addChild(tropical_mc);
                       tropical_mc.x=tropical_mc.mouseX;
                       tropical_mc.y=tropical_mc.mouseY;
                       tropical_mc.name="tropical_duplicate"+tropical_inc;
                       tropical_inc++;
                       tropical_mc.startDrag(false);
                      tropical_mc.addEventListener(MouseEvent.MOUSE_UP, stdrag);
              if (event.currentTarget.name=="bg_load10") {
                       var waters_mc:waters_png=new waters_png();
                       addChild(waters_mc);
                       waters_mc.x=waters_mc.mouseX;
                       waters_mc.y=waters_mc.mouseY;
                       waters_mc.name="waters_duplicate"+waterthumb_inc;
                       waterthumb_inc++;
                       waters_mc.startDrag(false);
                      waters_mc.addEventListener(MouseEvent.MOUSE_UP, stdrag);
    Please suggest me if any  one.
    Regards,
    Viji. S

    Post AS3 questions in the AS3 forum, not the AS1/2 forum.

  • Business scenarios on SD and MM modules for generic datasources and enhance

    Hi,
      Can anybody send some documents on SD and MM module on generic datasource and on enhancements.Pl send it to my MailID:[email protected]
    Thanks,
    Chinna

    Hi,
    MM Process flow:
    The typical procurement cycle for a service or material consists of the following phases:
    1. Determination of Requirements
    Materials requirements are identified either in the user departments or via materials planning and control. (This can cover both MRP proper and the demand-based approach to inventory control. The regular checking of stock levels of materials defined by master records, use of the order-point method, and forecasting on the basis of past usage are important aspects of the latter.) You can enter purchase requisitions yourself, or they can be generated automatically by the materials planning and control system.
    2. Source Determination
    The Purchasing component helps you identify potential sources of supply based on past orders and existing longer-term purchase agreements. This speeds the process of creating requests for quotation (RFQs), which can be sent to vendors electronically via SAP EDI, if desired.
    3. Vendor Selection and Comparison of Quotations
    The system is capable of simulating pricing scenarios, allowing you to compare a number of different quotations. Rejection letters can be sent automatically.
    4. Purchase Order Processing
    The Purchasing system adopts information from the requisition and the quotation to help you create a purchase order. As with purchase requisitions, you can generate Pos yourself or have the system generate them automatically. Vendor scheduling agreements and contracts (in the SAP System, types of longer-term purchase agreement) are also supported.
    5. Purchase Order Follow-Up
    The system checks the reminder periods you have specified and - if necessary - automatically prints reminders or expediters at the predefined intervals. It also provides you with an up-to-date status of all purchase requisitions, quotations, and purchase orders.
    6. Goods Receiving and Inventory Management
    Goods Receiving personnel can confirm the receipt of goods simply by entering the Po number. By specifying permissible tolerances, buyers can limit over- and underdeliveries of ordered goods.
    7. Invoice Verification
    The system supports the checking and matching of invoices. The accounts payable clerk is notified of quantity and price variances because the system has access to PO and goods receipt data. This speeds the process of auditing and clearing invoices for payment.
    Common Tables used by SAP MM:
    Below are few important Common Tables used in Materials Management Modules:
    EINA Purchasing Info Record- General Data
    EINE Purchasing Info Record- Purchasing Organization Data
    MAKT Material Descriptions
    MARA General Material Data
    MARC Plant Data for Material
    MARD Storage Location Data for Material
    MAST Material to BOM Link
    MBEW Material Valuation
    MKPF Header- Material Document
    MSEG Document Segment- Material
    MVER Material Consumption
    MVKE Sales Data for materials
    RKPF Document Header- Reservation
    T023 Mat. groups
    T024 Purchasing Groups
    T156 Movement Type
    T157H Help Texts for Movement Types
    MOFF Lists what views have not been created
    A501 Plant/Material
    EBAN Purchase Requisition
    EBKN Purchase Requisition Account Assignment
    EKAB Release Documentation
    EKBE History per Purchasing Document
    EKET Scheduling Agreement Schedule Lines
    EKKN Account Assignment in Purchasing Document
    EKKO Purchasing Document Header
    EKPO Purchasing Document Item
    IKPF Header- Physical Inventory Document
    ISEG Physical Inventory Document Items
    LFA1 Vendor Master (General section)
    LFB1 Vendor Master (Company Code)
    NRIV Number range intervals
    RESB Reservation/dependent requirements
    T161T Texts for Purchasing Document Types
    Transaction Codes:
    RFQ to Vendor - ME41
    Raising Quotation - ME47
    Comparison of Price - ME49
    Creation of PO - ME21N
    Goods Receipt - MIGO
    Invoice (Bill PAssing) - MIRO
    Goods Issue - MB1A
    Physical Inventory - MI01( Create doc)
    MI04 (Enter Count)
    MI07 (Post)
    Also please check this links.
    http://www.sapgenie.com/sapfunc/mm.htm
    http://www.sap-basis-abap.com/sapmm.htm
    SD Process Flow:
    The sales documents you create are individual documents but they can also form part of a chain of inter-related documents. For example, you may record a customer’s telephone inquiry in the system. The customer next requests a quotation, which you then create by referring to the inquiry. The customer later places an order on the basis of the quotation and you create a sales order with reference to the quotation. You ship the goods and bill the customer. After delivery of the goods, the customer claims credit for some damaged goods and you create a free-of-charge delivery with reference to the sales order. The entire chain of documents – the inquiry, the quotation, the sales order, the delivery, the invoice, and the subsequent delivery free of charge – creates a document flow or history. The flow of data from one document into another reduces manual activity and makes problem resolution easier. Inquiry and quotation management in the Sales Information System help you to plan and control your sales.
    Transaction Codes:
    Inquiry - VA11/VA12/VA13
    Quotation - VA21/VA22/VA23
    Sales Order - VA01/VA02/VA03
    Delivery - VL01N/VL02N/VL03N
    Billing/Invoicing - VF01/VF02/VF03
    Also please check this links.
    http://www.sapgenie.com/sapfunc/sd.htm
    http://www.sap-basis-abap.com/sapsd.htm
    http://www.sapgenie.com/abap/tables_sd.htm
    Production Planning:
    For example, consider a pump manufacturing plant, based on the customer requirement, planning is done for future months ( we plan for a qty on particular
    date). Pump is an assembly - were main component would be manufactured in the plant and others would be procured. As PP, we are concerned only in the inhouse
    manufacturing but the final assembly (considering BOM) can be done only if the procured components are available. MRP helps in planning the shortage, on
    particular date based on the planned date. Work center (ex. lathe) place the components are machined/assembled (were the operation is done). Sequence of
    operation is routing (lead time scheduling data is got from routing). In the MRP Run,basic or lead time scheduling (need to know when to start/finish date)
    is done. On creation of the production order, system checks for which BOM and routing to be picked up (if there are many routings or BOM for that particular
    finished product). Availabilty checks for material,PRT and capacity needs to be done. on release of the order, confirmation of the order can be done (on
    completion of the order or after manufacturing the quantities). GI and GR have to be done.PP flow ends here
    step 1: creation of master data (Material master,BOM,Work center,Routing)
    step 2: Planning - can be done by Planned independent requirement (MD61), Independent requirement (MD81).
    we plan for a quantity, on which date (it would be finish date).
    step 3: MD04 -stock/requirement lsit (plan made can be viewed in MD04)
    step 4: MRP run - MD02, PIR is converted into Planned order
    step 5:Planned order to be converted production order - CO40, CO41
    step 6: production order to be released - CA02
    step 7: confirm the production order (order confirmation-CO15 (after which GI and GR is done)
    assign pts if helpful...

  • Doubt about generic method

    i have a generic method has shown below
    public static <E extends Number> <E>process(E list){
    List<Interger> output = new ArrayList<Interger>(); or List<Number> output = new ArrayList<Number>();
    return output ;
    if delcare the output variable using Interger or Number . when i am returning the output . it is showing me compiler error and it suggests me to add cast List<E>. Why i not able understand. please clarify my doubt.
    Thanks
    Sura.Maruthi
    Edited by: sura.maruthi on Sep 21, 2008 9:48 PM

    Your method declaration is garbled; there can be only one <...> clause, eg
    public static <E extends Number> E process(E list);This declaration says that for any subclass E of Number, the method process takes a single E instance (called list!?) and returns a single E instance. A valid implementation would be
    return list;I'm guessing you want the parameter to have type List<E>?. Like this:
    public static <E extends Number> E process(List<E> list);This declaration says that for any subclass E of Number, the method process takes a list of E's and returns a single E instance. A valid implementation would be
    return list.get(0);Or perhaps you also want to return a list of numbers?
    public static <E extends Number> List<E> process(List<E> list);This declaration says that for any subclass E of Number, the method process takes a list of E's and returns another list of E's. A valid implementation would be
    return list;Note that you cannot just return a list of Integers or Floats, because your generic method must work for any subclass of Number, and you're promising to return back a list of the same type as the argument passed in.
    Edited by: nygaard on Sep 22, 2008 10:05 AM

  • Generic Collections and inheritance

    Hi all
    I have the following code:
    public class GenericTest {
         public static <T,C extends Collection<T>> C process(C collection){
              // do some stuff (using T)
              return collection; // just to make a complete methode
         public void main(String[] args){
              List<String> l1 = new ArrayList<String>();
              List<String> l2;
              l2 = process(l1); // does not compile
    }Compilation fails with message :
    Bound mismatch: The generic method process(C) of type GenericTest is not applicable for the arguments (List<String>) since the type List<String> is not a valid substitute for the bounded parameter <C extends Collection<T>>     
    My questions:
    why doesn't it work?
    How do I fix it?
    regards
    Spieler

    What Compiler are you using?
    Your code compiles just fine on the JDK 1.5 compiler (once I added an inport for java.util.*)
    If the error message is from your IDE, you should check your IDE's web site for an existing bug, and for assistance.
    This is not the correct forum since your code compiles on the SUN JDK.
    Bruce

  • Generic method signatures

    I've searched but can't find that a question I have has been asked (or answered). I apologize in advance if it has. Here is my question.
    In Java Generics FAQ by Angelika Langer states in FAQ 802 ( [http://www.angelikalanger.com/GenericsFAQ/FAQSections/TechnicalDetails.html#FAQ802] ) "the type parameters of a generic method including the type parameter bounds are part of the method signature."
    In FAQ 810, many examples are presented of method declarations, including generic ones, and their corresponding method signatures. For example,
    <T> T method(T arg) has the following signature in the example:
    <$T1_extends_Object>method($T1_extends_Object>)
    It would seem to be intuitively clear that the type parameter and bounds would be part of the method signature but I can't seem to find such a stipulation/requirement of such in the Java Language Specification. Anybody know where it's stipulated in the JLS?
    Best Regards

    user13143654 wrote:
    Yeah, I know. The title of the subsection is "Determining Method Signature," but then it never seems to expressly do that other than in some ephemeral wafting byproduct of overload resolution.I wouldn't call it "ephemeral" and "wafting." It's pretty specific. If you're looking for the $T1_extends_Object notation, you won't find it. That's not part of the spec.
    I can't seem to find a specific spot in the subsection where I can say "OK, now I've got the method signature and now can proceed to ..." Well, it goes on to Phase 3, and then on to 15.12.2.5 Choosing the Most Specific Method. I'm not sure what you're looking for. It does describe in detail how we get from all the methods in the universe, to which type's methods we'll be considering to which signatures could match to which one is the best match. I don't know what else you're looking for.
    If you're looking for somebody to digest, translate, and simplify all that for you, good luck, but it ain't gonna be me. :-)
    If you have specific questions about smaller pieces of it I (or somebody else) might be able to help out. At the moment though, your question is rather vague.
    Edited by: jverd on May 3, 2011 1:48 PM

  • Generic  method to execue procedure

    Hi I was wondering if there was a way to write a generic method to execute a stored procedure in my EJB. I was thinking of the input parameters as being the data source, procedure name, and an array of parameters. I'm new to java and therefore I didn't know if I should be using a callable statement for prepared statement for this. Also how to get around the problen of knowing my datatype when trying to set parameters for a statement since each parameters expects you to provide a specific set method for data type.
    V

    Whoops sorry about the half broken code.
    javax.naming.InitialContext ctx = new javax.naming.InitialContext();
    javax.sql.DataSource ds =                    (javax.sql.DataSource) ctx.lookup("jdbc/sybase");
    conn = ds.getConnection();
    cstmt =     conn.prepareCall(
              "{call dbo.ModifyExchange (?,?,?,?,?,?,?,?,?,?,?,?)}");
    cstmt.setObject(1, (Object) inputs[0]);
    cstmt.setObject(2, (Object) inputs[1]);               
    cstmt.setObject(3, (Object) inputs[2]);
    cstmt.setObject(4, (Object) inputs[3]);
    cstmt.setObject(5, (Object) inputs[4]);
    cstmt.setObject(6, (Object) inputs[5]);
    cstmt.setObject(7, (Object) inputs[6]);
    cstmt.setObject(8, (Object) inputs[7]);
    cstmt.setObject(9, (Object) inputs[8]);
    cstmt.setObject(10,(Object) inputs[9]);
    cstmt.setObject(11,(Object) inputs[10]);
    cstmt.setObject(12,(Object) inputs[11]);
    System.out.println("ExecuteUpdate Beginning");
    result = cstmt.executeUpdate();
    When I execute it I get "com.sybase.jdbc2.jdbc.SybSQLException: Implicit conversion from datatype 'VARCHAR' to 'TINYINT' is not allowed. Use the CONVERT function to run this query."
    Any ideas?

  • Generic method - UnmarshalException (ClassNotFoundException)

    The mechanism was working fine until I added a generic method to the interface. Now it fails on a call to the new method.
    Here's the relevant code: public interface MyServer extends Remote {
        <T extends pub.beans.Bean> T getBeanAs ( Class<T> clazz, int key )
        throws RemoteException;
    public final class MyServerImpl implements MyServer {
        public synchronized <T extends pub.beans.Bean> T
                     getBeanAs ( final Class<T> clazz, final int key )
        throws RemoteException {
            Object bean = null;
            if( clazz == AbcBean.class )  {
                Abc obj = getObj( key );
                if( obj != null )  {
                    AllBeanTranslator x = new AllBeanTranslator();
                        * Translates an entity bean at the core of obj to external form.
                        * Core Data Object is class AbcDO.
                        * Returned object is class AbcBean.
                    bean = x.translateDO( obj.getData() );
            }  else  {  // ...
            return clazz.cast( bean );
    class Client  {
       public static void main ( final String[] args )
        throws Exception {
            System.setProperty("java.security.policy", "./security.policy" );
            if( System.getSecurityManager() == null ) {
                System.setSecurityManager(new RMISecurityManager());
            MyServer server = (BseServer)Naming.lookup( "MyServer" );
            AbcBean aBean = server.getBeanAs( AbcBean.class, 48 );
    // exception ^^^
    }This throws an exception on a class that the Client should know nothing about: AbcDO. The AbcBean hierarchy never references it. Here's the exception stack: Exception in thread "main" java.rmi.UnmarshalException: error unmarshalling return; nested exception is:
         java.lang.ClassNotFoundException: beans.AbcDO
         at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:178)
         at java.rmi.server.RemoteObjectInvocationHandler.invokeRemoteMethod(RemoteObjectInvocationHandler.java:178)
         at java.rmi.server.RemoteObjectInvocationHandler.invoke(RemoteObjectInvocationHandler.java:132)
         at $Proxy0.getBeanAs(Unknown Source)
         at Client.main(Client.java:61)
    Caused by: java.lang.ClassNotFoundException: beans.AbcDO
         at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
         at java.security.AccessController.doPrivileged(Native Method)
         at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
         at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
         at java.lang.ClassLoader.loadClass(ClassLoader.java:252)
         at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320)
         at java.lang.Class.forName0(Native Method)
         at java.lang.Class.forName(Class.java:247)
         at sun.rmi.server.LoaderHandler.loadClass(LoaderHandler.java:434)
         at sun.rmi.server.LoaderHandler.loadClass(LoaderHandler.java:165)
         at java.rmi.server.RMIClassLoader$2.loadClass(RMIClassLoader.java:620)
         at java.rmi.server.RMIClassLoader.loadClass(RMIClassLoader.java:247)
         at sun.rmi.server.MarshalInputStream.resolveClass(MarshalInputStream.java:197)
         at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1575)
         at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1496)
         at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1732)
         at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1329)
         at java.io.ObjectInputStream.readObject(ObjectInputStream.java:351)
         at java.beans.PropertyChangeSupport.readObject(PropertyChangeSupport.java:478)
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
         at java.lang.reflect.Method.invoke(Method.java:597)
         at java.io.ObjectStreamClass.invokeReadObject(ObjectStreamClass.java:974)
         at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1849)
         at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1753)
         at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1329)
         at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1947)
         at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1871)
         at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1753)
         at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1329)
         at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1947)
         at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1871)
         at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1753)
         at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1329)
         at java.io.ObjectInputStream.readObject(ObjectInputStream.java:351)
         at sun.rmi.server.UnicastRef.unmarshalValue(UnicastRef.java:306)
         at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:155)
         ... 4 moreAnother thing that puzzles me: Why no stub? When I saw that I turned on Stub Generation (I'm using Genady's RMI Eclipse Plug-in) but that caused a world of problems so I turned it back off.

    Just making them transient isn't the end of the solution, btw,
         * ChangeSupport serializes any serializable listeners.
         * If the listener is serializable but unknown to the codebase
         * causes UnmarshalException so best make these transient.
        protected transient PropertyChangeSupport pcs;
        protected transient VetoableChangeSupport vcs;After de-serialization pcs and vcs are null and of course the listeners are gone. AbcDO class uses events internally so they need to be re-established. Here's what I did, though I can think of at least two other solutions.
      // Normal constructor - not run during de-serialization
      protected AbcDO ( )  { 
          this.pcs = new PropertyChangeSupport( this );
          addPropertyChangeListener( this );
          this.vcs = new VetoableChangeSupport( this );
          addVetoableChangeListener( new AbcValidator() );
          this.SubObj = new SubObj ();
          this.SubObj .addPropertyChangeListener( this );
       * Re-establish transients after de-serialization.
       * Note how much this looks like the ctor.
       * @return this ready to rock again
       * @throws ObjectStreamException
      private Object readResolve ( )  throws ObjectStreamException  {
          this.pcs = new PropertyChangeSupport( this );
          addPropertyChangeListener( this );
          this.vcs = new VetoableChangeSupport( this );
          addVetoableChangeListener( new AbcValidator() );
          if( this.SubObj != null ) // should be impossible - subObj is final
              this.SubObj .addPropertyChangeListener( this );
          return this;
      }     Note that readResolve() may not be appropriate for a non-final class (see Effective Java). Note also that subObj needs its PropertyChangeSupport re-established.

  • Generic method

    Hi all,
    i have a question related to generic method in a non-generic class.
    the following code cannot be compiled. but I don't know why.
    public class G
           void print(Integer i)
              System.out.println("Inte");
         void print(String s)
              System.out.println("String");     
            <T> void callprint(T t)
              print(t);
            public static void main(String args[])
                    G g = new G();
                    g.callprint(new Integer(5));
    }Edited by: 812302 on Nov 16, 2010 6:58 PM
    Edited by: 812302 on Nov 16, 2010 6:59 PM

    Did you bother to read the error message. I'm sure it says something about not finding the print method and nothing to do with Generics. BTW you use square brackets for code tags or before and after your code.                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Are bridge methods generated for generic methods?

    I've recently come across the notion of bridge methods. They provide type safety while allowing for erasure. However, the only places where they've been mentioned is with your class extending a parameterized type. That is the only case mentioned with bridge methods in the JLS as well as:
    http://www.angelikalanger.com/GenericsFAQ/FAQSections/TechnicalDetails.html#Under which circumstances is a bridge method generated?
    So I've been wondering about generic methods. For example, Collections.max's signature looks like the following in the source:
    public static <T extends Object & Comparable<? super T>> T max(Collection<T> coll)
    and after erasure:
    public static Object max(Collection coll)
    However, one cannot simply pass any type of Collection to the max method, it must implement Comparable and whatnot. Therefore, my question is how does it do that? Mustn't there be some sort of bridge method or generic information in the class file? Else how can the compiler, by just looking at the erasure of generic methods, check type safety, do capture conversion, type inference, etc?

    Generic information is erased from the byte code. It is still there in the class file in the method signatures. That's how the compiler knows.

Maybe you are looking for

  • K7N2 Delta problems

    Hey all..having a huge problem with my computer and have no idea what's going on.....when i try to reformat, i am getting errors with blue screen. errors are as follows: Page_Fault_In_Non_Paged_Area followed by the stop error numbers                

  • My Nano will no longer sync with iTunes. Sync is greyed out under Devices.

    My Nano will no longer sync with iTunes. Sync is greyed out under Devices.

  • Data migration for historical consumption

    Hello, I would like to get information about data migration for historical consumption. To make forecast, we have to load historical consumptions for each materrial (data in forcasting view / Consumption vals). Do you know if this is possible with a

  • If my screen gets too big to use what do i do?

    Hi I would like to know how to fix my phone the screen has got too big for me to access it

  • Forms 9i  JDAPI.

    Could you please help with a small problem. I'm trying to run a class which in turn uses JDAPI provided by oracle with Forms 9i. During initialisation it fails to load a library "ifjapi90". I have changed the java.library.path and sun.boot.library.pa