我正在尝试将两个数组连接成新数组,按顺序排序,并交换两个索引值。
我对java有点陌生,之前只使用C,所以很难处理一个对象。
在 main 方法中,它声明了两个对象数组 IntVector vector = new IntVector(3); 和 IntVector vector2 = new IntVector(3);
如果类型是 int[],我只能这样做,但我想用作对象我应该如何编写 concat、sort 和 swap 方法?
公共类 IntVector {
private int[] items_;
private int itemCount_;
private IntVector(int[] data, int n) {
items_ = data.clone();
itemCount_ = n;
}
public IntVector(int itemSize)
{
itemCount_ =0;
if(itemSize<1) itemSize =10;
items_ = new int[itemSize];
}
public void push(int value)
{
if(itemCount_ + 1 >= items_.length)
overflow();
items_[itemCount_++] = value;
}
public void log()
{
for (int i=0 ; i<itemCount_; ++i)
{
System.out.print(items_[i]);
if(i<itemCount_ -1)
System.out.println();
}
}
public void overflow()
{
int[] newItems = new int[items_.length * 2];
for(int i=0 ; i<itemCount_; ++i)
{
newItems[i] = items_[i];
}
items_=newItems;
}
public int getValue(int index)
{
if(index < 0 || index >= itemCount_)
{
System.out.println("[error][IntVector][setValue] Incorrect index=" + index);
return 0;
}
return items_[index];
}
public void setValue(int index, int value)
{
if(index < 0 || index >= itemCount_)
{
System.out.println("[error][IntVector][setValue] Incorrect index=" + index);
return ;
}
items_[index] = value;
}
public IntVector clone()
{
return new IntVector(items_, itemCount_);
}
public IntVector concat()
{
return null;
}
public IntVector sort()
{
return null;
}
public IntVector swap()
{
return null;
}
public static void main(String[] args)
{
IntVector vector = new IntVector(3);
IntVector vector2 = new IntVector(3);
vector.push(8);
vector.push(200);
vector.push(3);
vector.push(41);
IntVector cloneVector = vector.clone();
vector2.push(110);
vector2.push(12);
vector2.push(7);
vector2.push(141);
vector2.push(-32);
IntVector concatResult = vector.concat(vector2);
IntVector sortResult = concatResult.sort();
IntVector swapResult = sortResult.clone();
//swapResult.swap(1,5);
System.out.print("vector : "); vector.log();
System.out.print("\n\ncloneVector : "); cloneVector.log();
System.out.print("\n\nvector2 : "); vector2.log();
System.out.print("\n\nconcatvector : "); concatResult.log();
System.out.print("vector : "); vector.log();
System.out.print("vector : "); vector.log();
}
}