我不知道如何获取通用列表实例的特定项目。假设我有类似的东西;
public class Column {
private String name;
private float width;
public Column(String name, float width) {
this.name=name;
this.width=width;
}
public String getName() {
return name;
}
和另一个班级;
public class WriteColumn {
private List<Column> col = new ArrayList<>();
public void addColumn() {
col.add(new Column("yo", 0.1f));
col.add(new Column("mo", 0.3f));
writeColumn(col);
public void writeColumn(List<Column> col) {
String str = "";
for (Column col1 : col) {
str += col1 + " - ";
}
System.out.println("Cols: " + str);
}
public static void main(String[] args) {
WriteColumn wc = new WriteColumn();
wc.addColumn();
}
}
我想得到的输出是列的文本部分,但我没有得到它。有一种简单的方法吗?
答案 0 :(得分:3)
我无法理解为什么你不能使用getName()方法?
应该有效:
public void writeColumn(List<Column> col) {
String str = "";
for (Column col1 : col) {
str += col1.getName() + " - ";
}
System.out.println("Cols: " + str);
}
答案 1 :(得分:1)
下面的代码正常工作,输出: Cols:哟 - mo -
我想这就是你所期待的。
package com.vipin.test;
import java.util.*;
class Column {
private String name;
private float width;
public Column(String name, float width) {
this.name=name;
this.width=width;
}
public String getName() {
return name;
}
}
public class WriteColumn {
private List<Column> col = new ArrayList<>();
public void addColumn() {
col.add(new Column("yo", 0.1f));
col.add(new Column("mo", 0.3f));
writeColumn(col);
}
public void writeColumn(List<Column> col) {
String str = "";
for (Column col1 : col) {
str += col1.getName() + " - "; //used getName()
}
System.out.println("Cols: " + str);
}
public static void main(String[] args) {
WriteColumn wc = new WriteColumn();
wc.addColumn();
}
}