我有3部分代码。
//IntArray = Class
//IntSequence = Interface
//MyClass = Class
IntArray (此处有问题) -
public IntSequence subSequence(int index, int size) {
MyClass s5 = new MyClass(size);
return null;
}
IntSequence(界面)
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;
}
}
我的问题 - 我真的不知道如何为IntArray的subSequence方法创建return语句。
我想做的就是IntArray调用MyClass的subSequence方法的方法,并接受参数index,size和IntArray中声明的数组。有人可以提供解决方案吗?
答案 0 :(得分:1)
这是一个利用Java强大的泛型的API解决方案:
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();
}
}
您可以像以下一样使用它:
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);
}
}