英文:
Java: How do you remove a letter from a nested Array
问题
// 导入所需的类
import java.util.ArrayList;
import java.util.Arrays;
// 创建嵌套数组
ArrayList arrayList = new ArrayList(
Arrays.asList("H", "e", "l", "l", "o",
new ArrayList(Arrays.asList("w", "e", "l", "t",
new ArrayList(Arrays.asList("l", "e", "m", "o", "n", null)),
"c", "e", "l", "l", true, "l")),
3, 5, "!", "e"));
// 从嵌套数组中删除一个元素
((ArrayList) ((ArrayList) ((ArrayList) arrayList.get(5)).get(4))).remove(5);
英文:
How would you remove a letter from a nested array in Java?
The nested array:
ArrayList arrayList = new ArrayList(
Arrays.asList("H", "e", "l", "l", "o",
new ArrayList(Arrays.asList( "w", "e", "l", "t",
new ArrayList(Arrays.asList( "l", "e", "m", "o", "n", null)),
"c", "e", "l", l", true, "l")),
3, 5, "!", "e") );
答案1
得分: 0
static void removeLeterNestedArrayTest() {
ArrayList arrayList = new ArrayList(
Arrays.asList("H", "e", "l", "l", "o",
new ArrayList(Arrays.asList( "w", "e", "l", "t",
new ArrayList(Arrays.asList( "l", "e", "m", "o", "n", null)),
"c", "e", "l", "l", true, "l")),
3, 5, "!", "e") );
displayArrayList (arrayList);
System.out.println();
removeLetterNestedArray(arrayList, "l");
displayArrayList (arrayList);
}
static void removeLetterNestedArray(ArrayList arrayList, String s) {
for (Object obj : arrayList) {
if (obj != null && obj instanceof ArrayList) {
removeLetterNestedArray((ArrayList) obj, s);
}
}
for (int i = 0; i < arrayList.size(); i++) {
if (arrayList.get(i) != null && arrayList.get(i).toString().equals(s))
{ arrayList.remove(i); i--; }
}
}
static void displayArrayList (ArrayList arrayList) {
for (Object obj : arrayList) {
if (obj != null) {
if (obj instanceof ArrayList)
displayArrayList((ArrayList)obj);
else System.out.print(obj.toString());
} else System.out.print("null");
}
System.out.println();
}
英文:
You can remove a letter from a nested array using recursion and instanceof
.
static void removeLeterNestedArrayTest() {
ArrayList arrayList = new ArrayList(
Arrays.asList("H", "e", "l", "l", "o",
new ArrayList(Arrays.asList( "w", "e", "l", "t",
new ArrayList(Arrays.asList( "l", "e", "m", "o", "n", null)),
"c", "e", "l", "l", true, "l")),
3, 5, "!", "e") );
displayArrayList (arrayList);
System.out.println();
removeLetterNestedArray(arrayList, "l");
displayArrayList (arrayList);
}
static void removeLetterNestedArray(ArrayList arrayList, String s) {
for (Object obj:arrayList) {
if (obj != null && obj instanceof ArrayList) {
removeLetterNestedArray((ArrayList) obj, s);
}
}
for (int i = 0; i < arrayList.size(); i++) {
if (arrayList.get(i) != null && arrayList.get(i).toString().equals(s))
{ arrayList.remove(i); i--; }
}
}
static void displayArrayList (ArrayList arrayList) {
for(Object obj: arrayList) {
if (obj != null) {
if (obj instanceof ArrayList)
displayArrayList((ArrayList)obj);
else System.out.print(obj.toString()); }
else System.out.print("null");
}
System.out.println();
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论