這個問題在這里已經有了答案: 嘗試從串列中洗掉元素時,為什么會收到 UnsupportedOperationException? (17 個回答) 2天前關閉。
下午好,我目前正忙于弄清楚如何從串列中洗掉特定專案,如“,”和“-”。
這是我的代碼:
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Code{
static Scanner scanner = new Scanner(System.in);
public static void main(String[] args){
String coords = scanner.next();
int a = 0;
int b = 0;
int c = 0;
int d = 0;
String tan[] = coords.split("");
List<String> ban = new ArrayList<String>();
ban = Arrays.asList(tan);
for (Object str : ban) {
if(ban.contains(",") && ban.contains(("-"))) {
ban.remove(",");
ban.remove("-");
}
}
}
}
我需要使用迭代器嗎?
uj5u.com熱心網友回復:
您的問題標題為:
如何在java中洗掉陣列串列中的特定專案?
但是,您的代碼并沒有嘗試這樣做。
這是問題所在:
List<String> ban = new ArrayList<String>();
這是語法糖:
List<String> ban;
ban = new ArrayList<String>();
第二條陳述句創建一個新的arraylist,然后將指向它的指標分配給'ban'變數(java中的所有非原語總是參考。ban不是'an arraylist'。它是一個當前參考你的串列的變數ArrayList 就像一所房子(并new ArrayList建造一所新房子),ban就像地址簿中的一頁。它不是房子——它是到房子的方向。ban = 擦掉頁面并寫下一個新地址)。
然后您立即執行以下操作:
ban = Arrays.asList(mom);
好的,現在你剛剛創建的arraylist 立即被扔進了垃圾桶。什么都沒有再提到它了,你已經覆寫了你的“禁令”變數:它在任何Arrays.asList給你的東西上都有新的點。換句話說,你建了一座新房子,在一張紙上寫下它的地址,然后立即擦掉這個地址,打電話給承包商在其他地方建造一個完全不同的房子,然后寫下那個房子的地址) .
然后我們解決了問題:創建的串列Arrays.asList不是 ArrayLists。它們是您真的不想使用的怪異串列。它們“模仿”陣列,這很糟糕,因為 java 陣列有點傻。具體來說:
- 此串列不能增長或縮小;結果,
.clear(),.add(),.addAll(),.remove(), 以及所有爵士樂都不起作用并引發例外。 - 該串列只是該陣列的一個輕包裝。你對它所做的任何事情也會改變底層陣列。
- 陣列不是不可變的。
.set(idx, newValue)確實有效。
然后,您回圈遍歷每個元素,但這根本不是您想要的 - 您不想要的 - 您永遠不會str在回圈中使用(變數)。您正在遍歷串列,每次回圈時,您都要求串列洗掉所有逗號和破折號。此外,這實際上是行不通的(你不能在迭代它的程序中弄亂一個集合)。
換句話說,您的代碼有很多錯誤。全部修復:
List<String> ban = new ArrayList<String>(Arrays.asList(mom));
This makes an actual ArrayList, initialized with the contents of the arrays. As an actual arraylist it can grow and shrink - it does support remove.
THen, get rid of the for loop. You can just invoke list.remove(",") on this. Your current code only does this if the list contains both at leat one comma and at least one dash, I'm not sure if you intended for that, either. That leaves:
String coords = scanner.next();
List<String> ban = new ArrayList<String>(Arrays.asList(coords.split("")));
ban.remove(",");
ban.remove("-");
Which is also a lot simpler and easier to read, in addition to not throwing exceptions :)
It sounds like your actual intent is to turn this stuff into a list of integers. You don't need removal in the first place then:
var digits = new ArrayList<Integer>();
for (char c : scanner.next().toCharArray()) {
int d = Character.digit(c, 10);
if (d != -1) digits.add(d);
}
The Character.digit method turns a character that represents a digit into the actual number it represents (and 10 is the base. I think you want decimal here, hence, 10). It returns -1 if the character isn't a digit (e.g. a comma or a dash or a space). Hence, if it isn't -1, we add it.
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/452138.html
標籤:爪哇 列表 数组列表 java.util.scanner
