如何克隆ArrayList并在Java中克隆其项目?
例如,我有:
ArrayList<Dog> dogs = getDogs();
ArrayList<Dog> clonedList = ....something to do with dogs....
Run Code Online (Sandbox Code Playgroud)
我希望那些物品clonedList与狗列表中的物品不同.
我遇到了这篇文章,它非常努力地解释了打印所有字符串的递归解决方案。
public class Main {
private static void permutation(String prefix, String str) {
int n = str.length();
if (n == 0)
System.out.println(prefix);
else {
for (int i = 0; i < n; i++)
permutation(prefix + str.charAt(i),
str.substring(0, i) + str.substring(i + 1));
}
}
public static void main(String[] args) {
permutation("", "ABCD");
}
}
Run Code Online (Sandbox Code Playgroud)
但是当我们开始从堆栈中弹出时,我仍然无法获得该部分。例如,递归一直进行到permutation("ABCD",""),在基本情况下遇到并打印ABCD。但是现在会发生什么?我们permutation("ABC","D")从函数调用堆栈中弹出。我们如何处理这个等等?
有人可以帮忙解释一下吗?
另外,我需要一些有关此时间复杂度的指针。不像完整的计算,而是一些提示。
我正在编写一个程序,它接受4个数字作为输入,然后尝试查看加法减法除法和四个数字相乘的组合是否可以使它们等于24.我的方法是为四个数字的每个可能组合创建一个方法数字和四个操作数,有点冗长.以下是2种方法的示例.
public static boolean add(int a, int b, int c, int d){
boolean adBool;
adBool = a + b + c + d == 24;
return adBool;
}
public static boolean sub1(int a, int b, int c, int d){
boolean subBool1;
subBool1 = a - b - c - d == 24;
return subBool1;
}
Run Code Online (Sandbox Code Playgroud)
然后在我的Main中我为每个方法创建一个while循环,如果方法返回true,将打印它停止的方法,是解决方案.这是一个例子.
while (add(num1, num2, num3, num4)){
System.out.println("Your solution is " + num1 + " + " + num2 + " + " + num3 + …Run Code Online (Sandbox Code Playgroud) 我正在尝试生成 a 的所有排列,List<List<String>>但我没有得到独特的排列。
我的List<List<String>>看起来像
[
[Test, Test 1, Test 2],
[Apple, Sandwich, Banana],
[Cake, Ice Cream, Fruit]
]
Run Code Online (Sandbox Code Playgroud)
我试图List<String为父级中的每个组合提供所有可能的组合List<String>。因此,例如,第一个实例应该具有:
[Test, Test 1, Test 2]
[Test, Test 2, Test 1]
[Test 2, Test, Test 1]
[Test 2, Test 1, Test]
[Test 1, Test, Test 2]
[Test 1, Test 2, Test]
Run Code Online (Sandbox Code Playgroud)
现在,我的尝试将只是迭代并重复元素而不更改顺序,因此[Test, Test 1, Test 2]只会重复父级的大小List<String>。这是我的方法。任何帮助表示赞赏:
List<List<String>> allPerms = parentList.stream().map(line -> parentList.stream()).flatMap(l -> l.filter(j -> !j.equals(l))).collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud) java ×4
algorithm ×1
anagram ×1
clone ×1
collections ×1
deep-copy ×1
java-stream ×1
math ×1
permutation ×1
recursion ×1
string ×1