在下面的代码中,我想知道如何使用另一个对象。具体来说,当我将两个ArrayList传递给append方法时,如何使它们具有不同的值。
下面的代码应该将两个Arraylist附加在一起而不修改它们中的任何一个。
我了解到要执行此操作,我需要创建一个单独的Arraylist“值”实例,这就是为什么我使用另一个对象的原因,但是我想知道如何为Arraylist的每个实例分配单独的值
package com.company;
import java.util.ArrayList;
public class MergeSequence {
public ArrayList<Integer> values;
public MergeSequence(){
values = new ArrayList<Integer>();
}
public void add(int n) {
values.add(n);
}
public String toString() {
return values.toString();
}
public MergeSequence append(MergeSequence other)
{
MergeSequence result = new MergeSequence(); // Create a new result object.
// Iterate through the "local" ArrayList and add each value to the result
for (int i = 0; i < values.size(); i++)
{
int j = values.get(i);
result.add(j);
}
// Now, iterate through the "external" ArrayList and add each value to the result
for (int i = 0; i < other.values.size(); i++)
{
int j = other.values.get(i);
result.add(j);
}
result.toString();
// Then return the result. Neither source ArrayList is modified.
return result;
}
}
答案 0 :(得分:0)
toString
本身不输出任何内容至标准输出。因此,在调用result.toString();
之后,您将不会在控制台中看到结果。您需要使用System.out.println(result)
来输出结果。
顺便说一句,在append
方法中打印值是一个副作用。最好在append
之外打印这些值。例如:
public static void main(String[] args) {
final MergeSequence a1 = new MergeSequence();
a1.add(1);
a1.add(2);
final MergeSequence a2 = new MergeSequence();
a2.add(3);
final MergeSequence a3 = a1.append(a2);
System.out.println(a1); // [1, 2]
System.out.println(a2); // [3]
System.out.println(a3); // [1, 2, 3]
}
答案 1 :(得分:0)
只需添加一种主要测试方法
public static void main(String[] args) {
MergeSequence m1 = new MergeSequence();
m1.add(1);
m1.add(2);
MergeSequence m2 = new MergeSequence();
m2.add(3);
MergeSequence m3 = m1.append(m2);
System.out.println(m3.toString());
}