Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 5 of 5

Thread: Problem with static method as parameter of super()

  1. #1
    Junior Member
    Join Date
    Dec 2012
    Posts
    3
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Problem with static method as parameter of super()

    Hi folks:

    I need help from any Java guru, for this little program. This is homework I've done without success, but I want to understand where is my error and how to solve this exercise.

    The problem is:

    Giving an array of ints (with possible duplicate elements) I want to list pairs of numbers in ascending order without repetitions.

    The classes Sequence and FixedSize can't be changed, because they are inherited by other classes (external to this code) and they ran without errors.

    The only class that may (and need to) be changed is SortArray.

    Here's the code:

    public abstract class Sequence
    {
        private int index = -1;
        public final int nextIndex() { return index+1; }
        public boolean hasNext()     { return nextIndex() < size(); }
        public int next()            { return ++index; }
        public abstract int size();
    }
     
     
    public abstract class FixedSize extends Sequence
    {
        private final int size;
        public FixedSize(int sz) { size = sz; }
        public final int size()  { return size; }
    }
     
     
    public class SortArray extends FixedSize
    {
        public static int WithoutRepetitions[];  // static array where the static method 'RemoveDups' stores the result
     
        public SortArray(int a[], int bi, int ei)
        {
            super (RemoveDups (a, bi, ei));  // super() calls a static method that receives the array of integers, 
                                             // removes duplicates and return the number of elements without repetitions
        }
     
        private int idx = 0;  // variable to store the n-th element of the array
     
        @Override
        public int next()
        {
            super.next();
            return WithoutRepetitions[idx++]; // return the n-th element of the array 
                                              // and increment the index to the next element 
                                              // to be shown in the next call to next()
        }
     
     
        // static method for removing duplicates (must be static to pass as argument of super() )
        private static int RemoveDups(int a[], int bi, int ei)
        {
     
            int[] ArrayRange = Arrays.copyOfRange(a, bi, ei);
     
            // sorting array with repetitions
            Arrays.sort(ArrayRange, 0, ArrayRange.length);
     
            // temporary array to store non duplicate elements
            int tmp[] = new int[ArrayRange.length];
     
            boolean dups;
            tmp[0] = ArrayRange[0];
            int DimArray = 0;
            for (int i=1; i<ArrayRange.length; i++)
            {
                dups= false;            
                for  (int j=0; j<tmp.length; j++)
                {
                    if (ArrayRange[i] == tmp[j]) dups= true;
                }
                if (!dups)
                {
                    DimArray++;
                    tmp[DimArray] = ArrayRange[i];
                }
            }     
     
            DimArray++;  // size of array without repeated elements 
     
            // copy to array static array non duplicated elements
            WithoutRepetitions = Arrays.copyOf(tmp, DimArray);
     
            return DimArray; // return number of elements of array > to use in super() - (see above)
     
        }
    }

    When we ran the code snippet:

    public static void main(String[] args) 
    {
     
        int a[] = {7, 5, 8, 5, 2, 1};
        Sequence s1 = new SortArray(a, 1, 6), s2 = new SortArray(a, 3, 5);
     
        while (s1.hasNext()) System.out.print(s1.nextIndex() + ":" + s1.next() + " - ");  
        while (s2.hasNext()) System.out.print(" - " + s2.nextIndex() + ":" + s2.next());  
     
    }

    The expected output should be:

    0:1 - 1:2 - 2:5 - 3:8 - - 0:2 - 1:5 (two sequences of numbers - one for each while - in ascending order without repetitions)

    However this code doesn't run, because the static array "WithoutRepetitions[]" being static is shared by the two instances of Sequence (s1 and s2),
    and both while loops show the second sequence (0:2 - 1:5) crashing the program in the first while because the length of s1 is bigger than the length of s2.

    If I exchange the order of instructions like below, it works:

    public static void main(String[] args) 
    {
     
        int a[] = {7, 5, 8, 5, 2, 1};
     
        Sequence s1 = new SortArray(a, 1, 6);
        while (s1.hasNext()) System.out.print(s1.nextIndex() + ":" + s1.next() + " - ");  
     
        Sequence s2 = new SortArray(a, 3, 5);
        while (s2.hasNext()) System.out.print(" - " + s2.nextIndex() + ":" + s2.next());  
    }

    In that order it works, however I'm not allowded to do this:

    Somebody advice me to instead of a static array, I must use an instance array, however this is not possible, because the method "RemoveDups" must be static to be used inside super() and because of this constraint (static) can't access non static variables.

    Can someone help me to solve this.

    Thank you in advance for your help.


  2. #2
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,896
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Problem with static method as parameter of super()

    Hmm, the only "reasonable" way I can think of solving this problem is to perform the remove duplicates operation twice: The first time is to satisfy the SortArray constructor requirements, and the second time you actually store the data into an instance variable. Not efficient, but it gets the job done.

    You could even call the same code twice if you define the new removeDups method to return an array of un-duplicated items, then in the super constructor call simply pass the length of that array.

    super(removeDups(a, bi, ei).length());

    If you're allowed to modify the contents of the input array, I can think of another hack which would work, but it isn't as robust because it relies on the fact that you can modify the input array (usually a bad idea).

  3. #3
    Junior Member
    Join Date
    Dec 2012
    Posts
    3
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Problem with static method as parameter of super()

    Quote Originally Posted by helloworld922 View Post
    Hmm, the only "reasonable" way I can think of solving this problem is to perform the remove duplicates operation twice: The first time is to satisfy the SortArray constructor requirements, and the second time you actually store the data into an instance variable. Not efficient, but it gets the job done.
    For the purpose of store the data into an instance variable, I change the declaration on the array and the method from:

     
    public static int withoutRepetitions[];
     
    private static int removeDups(int a[], int bi, int ei)

    to...

     
    public int withoutRepetitions[]; // instance array to store the data returned from removeDups(a, bi, ei);
     
    private static int[] removeDups(int a[], int bi, int ei)  // now the method return an array of ints

    when the method removeDups() try to store the data in the instance array, I get the error:

    «non-static variable cannot be referenced from a static context»

    Another question...

    If you're allowed to modify the contents of the input array, I can think of another hack which would work, but it isn't as robust because it relies on the fact that you can modify the input array (usually a bad idea).
    How can I modify the input array, since that in Java all parameters are passed by value?

    Maybe I'm not fully understand what you explain me.

  4. #4
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,896
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Problem with static method as parameter of super()

    You're removeDups method shouldn't access any static fields at all, instead it should operate on a local array. The method can then return that array, so your code would look something like this:

    private static int[] removeDups(int a[], int bi, int ei)
    {
        int[] result;
        // code to get sorted un-duplicated numbers into result
        // basically anywhere you used withoutRepetitions in the past should be changed to use the local result variable
        return result;
    }

    Then, in your constructor you can call the removeDups method to satisfy the super constructor, then call it again to set the instance field.

    How can I modify the input array, since that in Java all parameters are passed by value?
    Yes, and no. It's true all parameters are passed by value, but it depends on what value you're talking about. In the case of primitives (int, long, char, etc.) the raw value is passed. In the case of objects, the reference or "address" of the object is passed (arrays count as objects). So you can modify the object in a method and it will have side effects outside of the method because the same object is referenced outside that method. However, if you change the variable to point to a different object, modifying that object will have no effect to the original object because they are intrinsically two different objects.

    A simple analogy:

    Say your friend Verne has a house. They write down the address and give it to you. Now if you go to that house and modify it, Verne will be able to go to that house and see the changes you've made. However, if you decide you want to change the address you have to a different house, any changes you make to that other house won't be reflected in Verne's house (since they're not the same house).

    Trying this out in code:

    public static void main(String[] args)
    {
        int[] a = new int[]{1};
        modify(a);
        System.out.println("First element in a changed to " + a[0]); // a[0] = 2
        change(a);
        System.out.println("First element in a is still " + a[0]); // a[0] = 2
    }
     
    public static void modify(int[] arr)
    {
        arr[0] = 2;
    }
     
    public static void change(int[] arr)
    {
        arr = new int[1];
        arr[0] = 3;
    }

  5. The Following User Says Thank You to helloworld922 For This Useful Post:

    Cento e Cem (December 28th, 2012)

  6. #5
    Junior Member
    Join Date
    Dec 2012
    Posts
    3
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Problem with static method as parameter of super()

    Many thanks to you helloworld922. Thank you for your help. Your help was the only one that solved my problem. I had asked for help in various forums to several people and not only one could help me. All the answers I got were useless and there was even a forum where the moderators closed my post because they could not understand my question. I got to the point of thinking that it was not possible to solve the problem. Thanks to you, has been resolved. Thank you very much.

Similar Threads

  1. Replies: 3
    Last Post: May 27th, 2012, 11:11 AM
  2. Replies: 1
    Last Post: April 3rd, 2012, 06:32 AM
  3. What's the difference between a static and non-static method?
    By wholegrain in forum Java Theory & Questions
    Replies: 4
    Last Post: February 23rd, 2012, 01:06 AM
  4. non-static method cannot be referenced from a static context
    By Kaltonse in forum What's Wrong With My Code?
    Replies: 2
    Last Post: December 21st, 2010, 07:51 PM
  5. Replies: 10
    Last Post: September 6th, 2010, 04:48 PM