[英]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.