我有一个ArrayList<Item>
,如下所示
ArrayList<Item> items = new ArrayList<Item>();
items.add(new SectionItem("Category 1"));
items.add(new EntryItem("Item 1", "This is item 1.1"));
items.add(new EntryItem("Item 2", "This is item 1.2"));
items.add(new EntryItem("Item 3", "This is item 1.3"));
items.add(new SectionItem("Category 2"));
items.add(new EntryItem("Item 4", "This is item 2.1"));
items.add(new EntryItem("Item 5", "This is item 2.2"));
items.add(new EntryItem("Item 6", "This is item 2.3"));
items.add(new EntryItem("Item 7", "This is item 2.4"));
items.add(new SectionItem("Category 3"));
items.add(new EntryItem("Item 8", "This is item 3.1"));
items.add(new EntryItem("Item 9", "This is item 3.2"));
items.add(new EntryItem("Item 10", "This is item 3.3"));
items.add(new EntryItem("Item 11", "This is item 3.4"));
items.add(new EntryItem("Item 12", "This is item 3.5"));
我想将其转换为List<String>
。我怎样才能做到这一点?我做了如下,但它没有工作。
List<String> result = new ArrayList<String>();
for (Object Item : items) {
result.add(Item != null ? Item.toString() : null);
}
下面是我的sectionItem和EntryItem
public class SectionItem implements Item{
private final String title;
public SectionItem(String title) {
this.title = title;
}
public String getTitle(){
return title;
}
@Override
public boolean isSection() {
return true;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return super.toString();
}
}
public class EntryItem implements Item{
public final String title;
public final String subtitle;
public EntryItem(String title, String subtitle) {
this.title = title;
this.subtitle = subtitle;
}
@Override
public boolean isSection() {
return false;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return super.toString();
}
}
答案 0 :(得分:-1)
以下是字符串示例。
List<String> itemsList2 = new ArrayList<String>(items);
for(String item:itemsList2)
System.out.println(item);
如果要分配新内存,并创建arraylist副本。
List<String> itemsList= items;
for(String item:itemsList)
System.out.println(item);
如果您只想将其映射到列表,并重复使用相同的arraylist对象。
{{1}}
答案 1 :(得分:-2)
您应该使用if
而不是尝试将null
添加到列表中:
List<String> result = new ArrayList<String>();
for (Object Item : items) {
if(Item != null)
result.add(Item.toString());