简体   繁体   中英

Proper implementation of an interface and a class in this code?

I have got 3 parts of code.

//IntArray = Class
//IntSequence = Interface
//MyClass = Class

IntArray (Having problem here) -

public IntSequence subSequence(int index, int size) {
   MyClass s5 = new MyClass(size);
      return null;
  }

IntSequence (interface)

public interface IntSequence {
 int length();
 int get(int index);
 void set(int index, int value);
 IntSequence subSequence(int index, int size);
}

MyClass

import java.util.*;

public class MyClass extends IntArray {
    public MyClass(int size) {
        super(size);
    }

    public static ArrayList<Integer> subSequence(int a1, int a2, int[] array) {
        ArrayList<Integer> valuelist = new ArrayList<>();
        for(int i = a1; i <= (a2 + a1); i++)
        {
            if(i >= array.length)
                break;
            else
                valuelist.add(array[i]);
        }
        return valuelist;
    }

}

My problem - I don't really know how I can make the return statement for the subSequence method of IntArray.

All I want to do is the method of IntArray to call the subSequence method of MyClass and take in parameters index, size and an array which is there in IntArray declared somewhere. Can someone provide a solution to how this can be possibly done?

Here's a solution to your API which leverage's Java's powerful Generics:

import java.util.*;


public class Sequence<T>
{
    private List<T> sequence=new ArrayList<T>();

    public int length()
    {
        return sequence.size();
    }

    public T get(int index)
    {
        return sequence.get(index);
    }

    public void set(int index, T value)
    {
        sequence.set(index,value);
    }

    public List<T> subList(int startIndex, int size)
    {
        return sequence.subList(startIndex, startIndex+size);
    }

    public <T> T[] subArray(int startIndex, int size)
    {
        return (T[])subList(startIndex, size).toArray();
    }
}

You might use it like:

class MyClient
{
    public static void main(String[] argv)
    {
        Sequence<Integer> intSeq = new Sequence<Integer>();
        intSeq.set(0,0);
        intSeq.set(1,1);
        int intValue = intSeq.get(1);
        // ...
        Integer[] intArray = intSeq.subArray(1,1);

        Sequence<Double>  doubleSeq = new Sequence<Double>();
        doubleSeq.set(0,1.1);
        doubleSeq.set(1,2.2);
        double doubleValue=doubleSeq.get(1);
        // ...
        Double[] doubleArray = doubleSeq.subArray(1,1);
    }        
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM