![](/img/trans.png)
[英]How can I convert ArrayList<Object> to ArrayList<String> or ArrayList<Timestamp>?
[英]How do I convert a String ArrayList to an Object ArrayList
我想將 String ArrayList 轉換為 Object Arraylist(如果可能的話)。 原因是因為我試圖返回一個 ArrayList 但不斷收到不兼容類型錯誤。 也許有另一種方法可以解決這個問題?
這是我寫的代碼:
import java.util.ArrayList;
import java.util.Arrays;
public class Phone
{
private String Brand;
private String Type;
private String Model;
private String UniqueID;
private int ManufCost;
public static ArrayList<Phone> Phones = new ArrayList<Phone>();
public static int counter;
public Phone(String Brand, String Type, String Model, String UniqueID, int ManufCost)
{
this.Brand=Brand;
this.Type=Type;
this.Model=Model;
this.UniqueID=UniqueID;
this.ManufCost=ManufCost;
Phones.add(this);
counter =counter +1;
}
public static ArrayList<String> getCurrentRun()
{
ArrayList<String> phonetext = new ArrayList<>();
String temptext;
for (int count = 0; count < counter+1; count++)
{
temptext = (Phones.get(count).Brand + " " + Phones.get(count).Type + " " +
Phones.get(count).Model + " " + Phones.get(count).UniqueID + " " +
Phones.get(count).ManufCost);
phonetext.add(temptext);
}
return phonetext;
}
我指的方法是 getCurrentRun()
在 main 中調用 getCurrentRun 使用:
ArrayList<Phone> phones = Phone.getCurrentRun();
for (Phone phone : phones)
{
System.out.println(phone);
}
這是我無法改變的。 請幫我解決我的問題。
最終結果應該是它打印出存儲在數組列表 Phones 中的對象。
您在這里從getCurrentRun()
返回ArrayList<String>
並期望它在main
方法中是ArrayList<Phone>
。 這是不正確的,這些應該是兼容的。
可能有 2 種可能的解決方案(根據您的需要):
a) 要么返回ArrayList<Phone>
類型(或返回List<Phone>
將是正確的方式)
public static List<Phone> getCurrentRun(){
return Phones; // although correct variable name should be phone as per java coding standards
}
如果您想按照定義的字符串打印電話詳細信息,請另外覆蓋電話類中的toString
方法,如下所示:
@Override
public String toString() {
return this.Brand + " " + this.Type + " " + this.Model + " " + this.UniqueID + " " + this.ManufCost;
}
b) 將其保存在List<String>
,如下所示:
List<String> phones = Phone.getCurrentRun(); // correct variable name should be phone
for (String phone : phones)
{
System.out.println(phone);
}
在這里你還可以用for-each
循環替換這個 for 循環。
您應該做兩件事:1. 修復getCurrentRun()
方法以返回正確的類型 - List<Phone>
和 2. 實現toString()
方法以生成電話的字符串表示。
修復getCurrentRun()
方法以返回正確的類型。 請注意,以下內容是phones
的副本,而不是傳遞原件。 調用者可能會修改列表,我們不希望這影響我們的內部列表。
public static List<Phone> getCurrentRun() {
List<Phone> copy = new ArrayList<>();
Collections.copy(copy, phones);
return copy;
}
實現一個toString()
方法。 請注意,這會覆蓋Object
基類提供的實現(Override 注釋是可選的,但很好的做法)。 JRE 將使用它從對象的實例中生成一個字符串,其中語法暗示它是合適的。 例如,當main
方法遍歷List<Phone>
並將每個方法傳遞給System.out.println
,JRE 將自動調用它以生成 String 表示。
@Override public String toString() {
StringJoiner joiner = new StringJoiner(" ");
joiner.add(this.Brand);
joiner.add(this.Type);
joiner.add(this.Model);
joiner.add(this.UniqueID);
joiner.add(this.ManufCost);
return joiner.toString();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.