Recursion with Generic Methods

public class MergeSort {
     public static <E extends Comparable<E>> void mSort(E[] list) {
          if(list.length > 1){
               Comparable<E>[] firstHalf = (Comparable<E>[]) new Object[list.length / 2];
               System.arraycopy(list, 0, firstHalf, 0, list.length / 2);
               MergeSort.<Comparable<E>>mSort(firstHalf);
}how do i get this to work?

Just realised I hadn't posted my code.
public class MergeSort {
     public static <E extends Comparable<E>> void mSort(E[] list) {
          if(list.length > 1){
               E[] firstHalf = (E[]) new Object[list.length / 2];
               System.arraycopy(list, 0, firstHalf, 0, list.length / 2);
               MergeSort.<E>mSort(firstHalf);
               int secondHalfLength = list.length - list.length / 2;
               E[] secondHalf = (E[]) new Object[secondHalfLength];
               System.arraycopy(list, list.length / 2, secondHalf, 0, secondHalfLength);
               MergeSort.<E>mSort(secondHalf);
               E[] temp = merge(firstHalf, secondHalf);
               System.arraycopy(temp, 0, list, 0, temp.length);     
     private static <E extends Comparable<E>> E[] merge(E[] list1, E[] list2) {
          E[] temp = (E[]) new Object[list1.length + list2.length];
          int current1 = 0;
          int current2 = 0;
          int current3 = 0;
          while(current1 < list1.length && current2 < list2.length) {
               if (list1[current1].compareTo(list2[current2]) < 0)
                    temp[current3++] = list1[current1++];
               else
                    temp[current3++] = list2[current2++];
          while (current1 < list1.length)
               temp[current3++] = list1[current1++];
          while (current2 < list2.length)
               temp[current3++] = list2[current2++];
          return temp;
     public static void main(String[] args) {
          Integer[] integers = {1, 5, 3, 4, 2, 7, 6, 8, 9};
          MergeSort.<Integer>mSort(integers);
          for(Integer i : integers)
               System.out.print(i + " ");
}

Similar Messages

  • Method GET_STATIC_ATTRIBUTES with generic table-structure

    Hi ,
    I am trying to select some rows of a web dynpro alv .
      LS_ALL-TABNAME = VAR_NAME_OF_TABLE.
      CREATE DATA LS_ALL-OBJECT TYPE TABLE OF (VAR_NAME_OF_TABLE).      "<<<<<
      INSERT LS_ALL INTO TABLE LT_ALL.
      LOOP AT LT_ALL INTO LS_ALL.
        ASSIGN LS_ALL-OBJECT->* TO <FS_TABLE>.                 "<<<<<
      ENDLOOP.
      LT_ELEMENTS = WD_THIS->DYN_NODE->GET_SELECTED_ELEMENTS( INCLUDING_LEAD_SELECTION = ABAP_TRUE ).
      LOOP AT LT_ELEMENTS INTO LR_ELEMENT.
        LR_ELEMENT->GET_STATIC_ATTRIBUTES( IMPORTING STATIC_ATTRIBUTES = <FS_TABLE> ).
      "coding...
      ENDLOOP.
    My problem: It's a generic web dynpro alv (with a dynamic context node) and i only have the tablename (and so it's structure) of the alv at runtime in a variable.
    I want to select some rows of this alv and get the data of the selected rows, so I try to work with field-symbols, but because of the move-corresponding in the coding of the method IF_WD_CONTEXT_ELEMENT~GET_STATIC_ATTRIBUTES...:
    method IF_WD_CONTEXT_ELEMENT~GET_STATIC_ATTRIBUTES .
      field-symbols:
        <values> type data.
      assign me->static_attributes->* to <values>.
      move-corresponding <values> to static_attributes.
    endmethod.
    ...i get the short-dump:
    German:
    Falscher Typ eines Operanden bei der Anweisung MOVE-CORRESPONDING.
    English:
    Wrong type of operands during the assignment MOVE-CORRESPONDING.
    So how can i get the structure of my generic table and do a move-corresponding with the method above?
    Many thanks in advance!
    Regards,
    Ludwig
    Edited by: Ludwig Heinz on Mar 13, 2008 9:45 AM

    Ok - but how can i make a declaration of dref_tab?
    my coding:
    TYPES: BEGIN OF TS_ALL,
      TABNAME TYPE DD02L-TABNAME,
      OBJECT  TYPE REF TO DATA,
    END OF TS_ALL.
    "dref_tab TYPE HASHED TABLE OF TS_ALL
    "     WITH UNIQUE KEY TABNAME,
      FIELD-SYMBOLS:
      <FS_LINE>  TYPE ANY,
      <FS_STRUCT> TYPE ANY,
    "<FS_TABLE> TYPE ANY TABLE.
      CREATE DATA LS_ALL-OBJECT TYPE (LF_TABLENAME).    
      INSERT LS_ALL INTO TABLE LT_ALL.
    "CREATE DATA dref_tab TYPE TABLE OF (LF_TABLENAME).
    "ASSIGN dref_tab->* TO <FS_TABLE>.
    LOOP AT LT_ALL INTO LS_ALL.
        ASSIGN LS_ALL-OBJECT->* TO <FS_STRUCT>.             
      ENDLOOP.
      LT_ELEMENTS = WD_THIS->DYN_NODE->GET_SELECTED_ELEMENTS( INCLUDING_LEAD_SELECTION = ABAP_TRUE ).
      LOOP AT LT_ELEMENTS INTO LR_ELEMENT.
        LR_ELEMENT->GET_STATIC_ATTRIBUTES( IMPORTING STATIC_ATTRIBUTES = <FS_STRUCT> ).
    "        append <FS_STRUCT> to <FS_TABLE>.
      ENDLOOP.
    syntax-error:
    "dref_tab" is not a datareference-variable.
    So how is the right declarion of "dref_tab" ?
    Many thanks - i've you can solve this - i think i can finish it
    Regards,
    Ludwig

  • 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.

  • Defining enum with abstract method which returns a generic type

    Is it possible to define an abstract method which returns an geneic type like below? Thanks
    public enum Type{
         A{
              public List<Integer> getData(){}
         B{
              public Set<String> getData{}
         abstract<T> T getData();
    }

    vulee wrote:
    Why not?
    List<Integer> lst = Type.A.getData();Wonder, which compiler you use. Can't be Java6:
    # javac Enums.java
    Enums.java:23: incompatible types
    found   : java.util.Collection<capture#376 of ?>
    required: java.util.List<java.lang.Integer>
                    List<Integer> data = Type.A.getData();
                                                       ^
    1 errorEdit: Unless you do it the generic way as you proposed, which actually is a phoney. Because of the T being a generic method parameter, the compiler will infer it from the type of the variable it gets assigned to. Hence, both of the following will compile:
    List<Integer> lst = Type.A.getData();
    Set<String> lst2 = Type.A.getData(); // Runtime exceptionActually, javac is telling you that giving warnings on the enum constants redefined method return types.
    Edited by: stefan.schulz on Sep 10, 2008 11:38 PM

  • Complicated generic method

    Hi guys,
    I've got a little problem with generics. I have a class, that will have several Map fields that look like:
    Map<Long, Account>;
    Map<Long, Role>;(where both Account and Role implement interface IDatabaseEntity, so these maps could be also defined like Map<Long, ? extends IDatabaseEntity>).
    However, I now need a method with this signature:
    public <T extends IDatabaseEntity> Map<Long, T> getMap(Class<T> entityClass);which return for given class (such class must implement IDatabaseEntity interface) its relevant map. For example:
    getMap(Account.class)should return type
    Map<Long, Account>.However, I can't figure out, how to implement such method :(. Could anyone help how to do something like that??
    Thanks in advance

    After couple of hours, I finally came to this, it may be helpful for someone:
    public class Register {
      private static Register oInstance;
      private Map<Class<? extends Entity>, Map<Long, ? extends Entity>> oLocalRegisters;
      public static Register getInstance() {
        if (oInstance == null) {
          oInstance = new Register();
        return oInstance;
      private Register() {
        oLocalRegisters = new HashMap<Class<? extends Entity>, Map<Long, ? extends Entity>>();
        oLocalRegisters.put(Role.class, new HashMap<Long, Role>());
        oLocalRegisters.put(Account.class, new HashMap<Long, Account>());
      protected <E extends Entity> Map<Long, E> getLocalRegister(Class<E> oClass) {
        Map<Long, ? extends Entity> oLocalRegister = oLocalRegisters.get(oClass);
        //local register for this type does not exist
        if (oLocalRegister == null) {
          throw new IllegalArgumentException("Unsupported entity class: '" + oClass.getName() + "'.");
        return (Map<Long, E>) oLocalRegister;
      public <E extends Entity> void registerEntity(Class<E> oClass, E oEntity) {
        getLocalRegister(oClass).put(oEntity.getLocalId(), oEntity);
      public <E extends Entity> E getEntity(Class<E> oClass, long iLocalID) {
        Map<Long, E> oLocalRegister = getLocalRegister(oClass);
        if (oLocalRegister != null) {
          return oLocalRegister.get(iLocalID);
        } else {
          return null;
      public <E extends Entity> void unregisterEntity(Class<E> oClass, E oEntity) {
        getLocalRegister(oClass).remove(oEntity.getLocalId());
    }

  • Program with generics compiles without -source 1.5 but doesn't run.

    This could probably be considered a bug in J2SE1.5 beta 1.
    A program with generics that is compiled with JDK 1.5 beta1 without the "-source 1.5" option behaves oddly: it compiles but sometimes fails to execute. It shouldn't behave like that. It should fail in the compilation, with a complaint about using the wrong version of the language.
    This odd behaviour doesn't always occur! In the small program below, I get that behaviour when using the EnumSet.range method.
    If I only use the basic EnumSet, it does executes.
    -- Lars
    import java.util.EnumSet;
    import java.util.*;
    public class Example {
         public enum Season { WINTER, SPRING, SUMMER, FALL }
         public static EnumSet<Season> warmSeason = EnumSet.range(Season.SPRING, Season.FALL);
         public static void main(String[] args) {
              System.out.println("Season: ");     
              for (Season s : Season.values()) {
              System.out.println(s);
              System.out.println("Cold Season: ");     
              for (Season s : warmSeason) {
              System.out.println(s);

    Example.java:6: warning: as of release 1.5, 'enum' is a keyword, and may not be used as an identifier
        public enum Season { WINTER, SPRING, SUMMER, FALL }
               ^
    Example.java:6: ';' expected
        public enum Season { WINTER, SPRING, SUMMER, FALL }
                           ^
    Example.java:12: ';' expected
            for (Season s : Season.values()) {
                          ^
    Example.java:17: illegal start of expression
            for (Season s : warmSeason) {
            ^
    Example.java:20: ';' expected
        ^
    4 errors
    1 warning

  • Doubts with generic service in "HCM processes and forms"

    Hello friends:
        Im having troubles trying to figure out how to use generic services. I implemented a badi with generic services and this have the following methods:
    IF_HRASR00GEN_SERVICE~GET_SPECIAL_FIELDS
    IF_HRASR00GEN_SERVICE~GET_FIELD_INFO
    IF_HRASR00GEN_SERVICE~GET_OPERATIONS
    IF_HRASR00GEN_SERVICE~INITIALIZE
    IF_HRASR00GEN_SERVICE~DO_OPERATIONS
    IF_HRASR00GEN_SERVICE~GET_HELP_VALUES
       I could initialize values of my form using only INITIALIZE method, and I could perform some validation using  and then DO_OPERATIONS.
       I cant understand what is the usage of methods like GET_FIELD_INFO and GET_OPERATIONS?? according to the badis help, get_field_info must be implemented, but i didnt do so and it worked anyway?
    I will be grateful with all your help,
    Best regards,

    GET_FIELD_INFO is for adding fields. Suppose you are using the generic service for IT0008 data. The IT0008 fields
    which need to be used on the adobe form has to be added in this method. You need to add field name and data element
    to the field_infos table. GET_OPERATIONS is used to define operations associated with the fields. Suppose you have a
    scenario when user selects personnel area all personnel subareas associated with the selected value should come.
    Then you need to group together personnel area and sub area together into an operation. Also even if a field is not aasociated
    with any operation, to add a field to form scenario you need group them into operations in GET_OPERATIONS.
    Check the class CL_IM_HRRCF_REQUI_REQUEST to determine how this can be used.
    Thanks,
    Aravind

  • Need help with generics

    I have written a java program using jdk1.5. After completing my program I noticed that the compiler was outputting a warning. It tells me that there were a few unsafe operations in my code. Anyway I found out that my code needed to include generics. I was able to figure out how too include some of the generics. I am having trouble with the following:
    [javac] /home/paul/Documents/java/PersonalInfo/src/personalInfo/logic/DB.java:105: warning: [unchecked] unchecked conversion
    [javac] found : personalInfo.logic.FNComparator
    [javac] required: java.util.Comparator<? super java.lang.Object>
    [javac] Arrays.sort(sort, fn);
    [javac] ^
    [javac] /home/paul/Documents/java/PersonalInfo/src/personalInfo/logic/DB.java:105: warning: [unchecked] unchecked method invocation: <T>sort(T[],java.util.Comparator<? super T>) in java.util.Arrays is applied to (java.lang.Object[],personalInfo.logic.FNComparator)
    [javac] Arrays.sort(sort, fn);
    [javac] ^
    [javac] /home/paul/Documents/java/PersonalInfo/src/personalInfo/logic/DB.java:109: warning: [unchecked] unchecked conversion
    [javac] found : personalInfo.logic.LNComparator
    [javac] required: java.util.Comparator<? super java.lang.Object>
    [javac] Arrays.sort(sort, ln);
    [javac] ^
    [javac] /home/paul/Documents/java/PersonalInfo/src/personalInfo/logic/DB.java:109: warning: [unchecked] unchecked method invocation: <T>sort(T[],java.util.Comparator<? super T>) in java.util.Arrays is applied to (java.lang.Object[],personalInfo.logic.LNComparator)
    [javac] Arrays.sort(sort, ln);
    [javac] ^
    The FN/LNComparator class implements the java.util.Comparator class. I have looked at the generics tutorial on the java.sun.com website. I can't figure out what I replace the <T> with to make the code compile and the warning to go away. I have tried <Comparator> but that just gives me an error that says FNComparator does not take any parameters.
    If anyone knows how to fix these warnings let me know
    -Hockeyfan

    I know how to fix it.
    Step 1. Stop writing subject-lines like "Need help with generics". Everyone who starts a topic needs help, that's why people post here!
    Step 2. Don't just post the error message, post the relevant code. In [code ][code ] tags of course.
    Step 3. Stop watching hockey, it'll stunt your growth
    Step 4. Have the FN/LNComparator implement, not the raw Comparator, but Comparator<Object>

  • Doubt regarding Generic methods

    I have 4 generics Methods getEJBHome,getEJBLocalHome ,findEJBLocalHomeAndPopulateCache,findEJBHomeAndPopulateCache
         public <T extends EJBHome> T getEJBHome(final String jndiName,final Class<T> ejbHomeClass) throws NamingException,ClassCastException{
              T ejbHome=null;
              try{
                   if(serviceLocatorCache.containsKey(jndiName)){
                        ejbHome=(T)serviceLocatorCache.get(jndiName);     
                   else{
                        ejbHome=findEJBHomeAndPopulateCache(jndiName,ejbHomeClass);
              catch(NamingException namingException ){
                   System.err.println("Exception in getEJBHome ["+namingException.getMessage()+"]");
                   throw namingException;
              catch(ClassCastException classCastException ){
                   System.err.println("Exception in getEJBHome ["+classCastException.getMessage()+"]");
                   throw classCastException;
              return ejbHome;
         private <T extends EJBHome> T findEJBHomeAndPopulateCache(final String jndiName,final Class<T> ejbHomeClass) throws NamingException{
              T ejbHome=null;
              try{
                   ejbHome=(T)javax.rmi.PortableRemoteObject.narrow(context.lookup(jndiName),ejbHomeClass);
                   serviceLocatorCache.put(jndiName,ejbHome);
              catch(NamingException namingException){
                   System.err.println("Exception in findEJBHomeAndPopulateCache ["+namingException.toString()+"]");
                   throw namingException;
              return ejbHome;
         }i am calling findEJBHomeAndPopulateCache like normal method call,When i try to call findEJBLocalHomeAndPopulateCache from getEJBLocalHome it shows compile time error .
         public <T extends EJBLocalHome> T getEJBLocalHome(final String jndiName) throws NamingException{
              T ejbLocalHome=null;
              try{
                   if(serviceLocatorCache.containsKey(jndiName)){
                        ejbLocalHome=(T)serviceLocatorCache.get(jndiName);     
                   else{
                        ejbLocalHome=this.<T>findEJBLocalHomeAndPopulateCache(jndiName);
                        //ejbLocalHome=findEJBLocalHomeAndPopulateCache(jndiName); ERROR
              catch(NamingException namingException ){
                   System.err.println("Exception in getEJBLocalHome ["+namingException.getMessage()+"]");
                   throw namingException;
              catch(Exception exception ){
                   System.err.println("Exception in getEJBLoacalHome ["+exception.getMessage()+"]");
                   throw new NamingException("Exception in getEJBLoacalHome ["+exception.getMessage()+"]");
              return ejbLocalHome;
         }when i try to call method findEJBLocalHomeAndPopulateCache like ejbLocalHome=findEJBLocalHomeAndPopulateCache(jndiName);
    i am getting compile time error
    ServiceLocator.java:133: type parameters of <T>T cannot be determined; no unique maximal instance ex
    ists for type variable T with upper bounds T,javax.ejb.EJBLocalHome
        [javac]                             ejbLocalHome=findEJBLocalHomeAndPopulateCache(jndiName);
        [javac]     ^
    when i am calling that method like
    this.<T>findEJBLocalHomeAndPopulateCache(jndiName); it is not showing any error.normally we are invoking generic methods like normal methods ?
    Why i am getting a compile time error for findEJBLocalHomeAndPopulateCache method?
    method findEJBLocalHomeAndPopulateCache is as shown
         private <T extends EJBLocalHome> T findEJBLocalHomeAndPopulateCache(final String jndiName) throws NamingException{
              T ejbLocalHome=null;
              try{
                   ejbLocalHome=(T)context.lookup(jndiName);
                   serviceLocatorCache.put(jndiName,ejbLocalHome);
              catch(NamingException namingException){
                   System.err.println("Exception in findEJBLocalHomeAndPopulateCache ["+namingException.toString()+"]");
                   throw namingException;
              return ejbLocalHome;
         }Plz help

    Hi Ben,
    Thanks for your replay, Can you please tell me why in first case ie getEJBHome method call findEJBHomeAndPopulateCache(jndiName,ejbHomeClass) not causing any error.In both case upper bound of ‘T’ is EJBLocalHome .Kindly give me a clear idea.
    Plz help

  • Generic method specialization

    I discovered today that it is possible overload a generic method with a non-generic one. Sounds reasonable, but I hadn't thought about it:
    class Util {
      public static <T> boolean isEmpty(T t) {
        return t == null;
      public static boolean isEmpty(String s) {
        return s == null || s.trim().equals(""");
      public static <A extends HasEmptyTest> boolean isEmpty(A a) {
        //class HasEmptyTest declares method isEmpty
        return a == null || a.isEmpty();
    }My question: Do you consider this in good style or feature abuse?
    Thanks for your response,

    Since generic methods may be substituted with their "erased" variants, your question boils down to this, totally non-generic, question:
    Is it advisable to overload a method with an argument of type A with a version that has an argument of type B when a widening conversion exists from A to B or vice versa?
    I'd answer: No, it's not advisable. It may lead to surprising behaviour.

  • 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.

  • Polymorphism with Overloaded Methods

    I am running into a problem when I try to leverage java��s polymorphism with overloaded Methods. Basically, what I am trying to do is iterate through a generic list of properties and call the correct overloaded method on each one based on the type of containing object.
    Here is the general code (4 classes)
    AbstractCronJob �� EmailCronJob
    BaseProperty �� SubjectLineProperty
    public abstract class BaseProperty implements CronPropertyExecutable{
        public BaseProperty() {
            super();
       public void execute(AbstractCronJob job) {
           System.out.println( "executing on abstract cron job" ) ;
    public class SubjectLineProperty extends BaseProperty {
        public SubjectLineProperty() {
            super();
        public final void execute( EmailCronJob emailCronJob ) {
            System.out.println( "executing on email cron job" ) ;
    public abstract class AbstractCronJob {
        protected int _id ;
        protected PropertyList _propertyList ;
        public AbstractCronJob( int id ) {
            super();
            _id = id ;
            _propertyList = new PropertyList() ;
        protected void createProperties() {
            //fill in with factory crap
            _propertyList.add( new SubjectLineProperty() ) ;
        protected abstract void executeProperties();
        protected abstract void run() ;
        public void execute() {
            createProperties() ;
            executeProperties() ;
            run() ;
    public class EmailCronJob extends AbstractCronJob {
        public EmailCronJob( int id ) {
            super( id ) ;   
        /* (non-Javadoc)
         * @see com.reged.cron.AbstractCronJob#run()
        protected void run() {
            //send email
        protected void executeProperties() {
            //we had this as abstract...unless I'm missing something, we can do this
            //in this class instead of pushing it down
            Iterator iter = _propertyList.iterator() ;
            while ( iter.hasNext() ) {
                //safe cast
                BaseProperty baseProperty = ( BaseProperty ) iter.next() ;
                baseProperty.execute( this ) ;
    }Okay, here is the problem that I am running into. The EmailCronJob knows that it has a list of properties, it doesn't know what type of properties it as. So when it iterates through its property list it upcasts then to the BaseProperty parent class. Then it calls the execute method on each property passing in itself.
    I thought that the execute(EmailCronJob job) method in SubjectLineProperty would be executed since the overloaded method with the mailCronJob parameter lives in that class, instead I am finding that the execute(AbstractCronJob job) method in the BaseProperty class is eing exercised.
    I am confused on why this doesn't work. Does polymorphism work with overloaded methods or just overridden methods?
    Thanks!

    We can think about it based on suppositions, satisfactory explanations, and based on OO design.
    According to the experience from the code above, we can suppose that, at runtime, the virtual machine looks for an exact identical signature of an method to perform the overriding.
    But, why does it work in that way? Is there any good justification, or is it just a implementation decision?
    I think there is a good justification.
    Let me get the Object.equals() method as an example, and let�s make an analogy with the code above. According to our conclusions from the experience above, that we suppose are right and should work, but actually they should not work, in order to use the equals() method, we can simply do this:
    class TheClass {
      private int whatever;
      public TheClass(int param) {
        whatever = param;
      //notice that the param is not Object
      public boolean equals(TheClass param) {
        //we don�t need either to cast to TheClass or
        //verify if the param is an instance of TheClass
        if (this == param) return false;
        if (this.whatever == param.whatever) return true;
        else return false;
    }Apparently, this equals() method above is more efficient, and it does make sense, too, and it would be considered a good and logic implementation of equals() method. Although, these conclusions are wrong, if you consider some OO concepts that are being broken here.
    equals() method is defined in Object class as an contract, like an interface. It says that this method must receive an Object param. And according to this contract, two instances of Object can use this method. You have to obey this contract, because it is Oriented Object Programming.
    If you use equals method without passing Object as an parameter, but passing other different class (like TheClass, in my example), you would not obey the contract, that says that two instances of Object can use this method. Try to do this:
    public static void main(String[] args) {
        TheClass theClass1 = new TheClass(1);
        TheClass theClass2 = new TheClass(1);
        //Good, more or less, because our objective, that is,
        //calling the customized equals(), will be performed.
        System.out.println(theClass1.equals(theClass2));
        String str = "blah";
        //oops! The customized equals() method will not
        //be called this time
        System.out.println(theClass1.equals(str));
        Object obj1 = theClass1;
        Object obj2 = theClass2;
        //Again, the customized equals() method will not
        //be called this time. Thanks God it works in this way!
        //Because if the customized equals() method
        //could be called here, the "OO law"
        //and the "contract" of equals method
        //defined in Object class would be broken
        System.out.println(obj1.equals(obj2));
    }Therefore, I think Java working in this way is good, because it obligates us to "obey the laws", in certain way.

  • Generics methods

    I found an information in an eBook that:
    "If a generic method definition uses the generic type name more than once or uses it outside the formal parameter list of the method, then the generic type cannot be replaced with a wildcard type."
    Could anybody explain it using an example ?
    Thanks,
    Adrian

    Hi,
    I was rather expecting something like:
    static <T extends Number> void doSomething(List<T> l, T element) {}I didn't event think of a return type as that second use of the generic type.
    But even then, the author seams to be not clear on what he says.
    Let's take the example above. Since element is of type T, it is not only
    the case of using the generic type for the second time, but first of all,
    this is indication that we are using it inside the method's body (which
    the author also adds as the second case).
    If the method was:
    static <T extends Number> void doSomething(List<T> l1, List<T> l2) {}then even that we are using that generic type twice, you can rewrite it
    using wildcards...
    To summarize - if you use generic type as a type of a parameter or a return type,
    then you can't use wildcards. And if the generic type is used as a type for a generic
    class, then you can change using wildcards. Am I right here ?
    Thanks,
    Adrian

  • Issue with a method call in a TaskFlow (works 2 times instead of 1)

    Hi guys,
    i'm using jdev11.1.1.1.2.0 and the integrated weblo or remote weblo 10.3.2.0.
    I'm encountering a problem with a method call which is invoked inside a Task Flow.
    Let me tell us the details of :
    I'm invoking a method call which is part of a Task Flow from the backingbean of the view which is placed before the method call in the taskFlow diagram.
    AN outcome String from the method of the backing bean allows to navigate to the method of the Task flow.
    The method call is called and works normally BUT MY PROBLEM IS THAT THE METHOD IS CALLED TWO TIMES SO THE RESULT IS FALSE.
    For information, the second time the method is called it takes care of the result when it is invoked the first time. So its parameters are updated and are a little different from the first time to the second time.
    NB : This method consists of inserting a row in the database. My result is 2 rows inserted instead of one.
    Thanks for help for this strange behaviour

    Hi
    create a temp calculated column
    =IF(ISBLANK([Duration]),"",[Item Start Date]+([Duration])
    and check if it's working OK
    Romeo Donca, Orange Romania (MCSE, MCITP, CCNA) Please Mark As Answer if my post solves your problem or Vote As Helpful if the post has been helpful for you.

Maybe you are looking for