[英]Storing First Case Variables from a String Expression (ArrayList to Array)
我正在將變量的第一種情況存儲到數組中,因為我不知道會決定使用多少個數組列表。
編譯時出現以下錯誤:
javac TruthTester.java
TruthTester.java:102: error: no suitable method found for toArray(char[])
char[] charArr = letters.toArray(x);
^
method ArrayList.<T>toArray(T[]) is not applicable
(inferred type does not conform to declared bound(s)
inferred: char bound(s): Object)
method ArrayList.toArray() is not applicable
(actual and formal argument lists differ in length)
where T is a type-variable:
T extends Object declared in method <T>toArray(T[])
1 error
這是我的代碼段。
private static char[] getVariables(String[] lines)
{
ArrayList<Character> letters = new ArrayList<Character>();
int count = 0;
for(int x = 0; x < lines.length; x++)
{
for(int i = 0; i < lines[x].length(); i++)
{
char tempStore = 'a';
boolean isCopy = false;
int counter = 0;
for(char letter : letters)
{
if(isAlphabeticToken(letter)){
if(lines[x].charAt(counter) == letter)
{
isCopy = true;
}
else
{
isCopy = false;
tempStore = letter;
}
}
else
{
isCopy = true;
}
counter++;
}
if(!isCopy)
{
letters.add(tempStore);
count++;
}
}
}
/*
* ==========
* ERROR HERE
* ==========
*/
char[] x = new char[letters.size()];
char[] charArr = letters.toArray(x);
return charArr;
}
您不能從ArrayList<Character>
獲取char[]
,只能獲取Character[]
,並且裝箱/拆箱不會使它們等效。
您是否考慮過使用StringBuilder
? 實際上,這是專門為容納可變的,長度未知的字符組而設計的。
由於ArrayList的類型為Character,因此可以將其轉換為Character [],但是不能轉換為char []。
因此,您可以執行以下操作:
Character [] x =新的Character [letters.size()];
Character [] charArr = letter.toArray(x);
要么
使用stringbuilder可以工作:
StringBuilder sb = new StringBuilder(letters.size());
for (Character c : letters)
sb.append(c);
String result = sb.toString();
return result.toCharArray();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.