2017-03-15 62 views
-2

我有一个存储其他对象的通用数组类。当我尝试从泛型数组中获取对象值时,它会打印插入对象类路径。我如何获取价值?获取通用数组中的对象而不是类路径的值

public class Shop implements Initializable { 
    @FXML private TextField name; 
    @FXML private TextField quantity; 
    @FXML private TextArea list; 

    MyArrayList<Item> array = new MyArrayList<>(); 

    @Override 
    public void initialize(URL location, ResourceBundle resources) { 

    } 

    @FXML 
    private void addItem() { 

     int q = Integer.parseInt(quantity.getText()); 
     String n = name.getText(); 

     Item item = new Item(n,q); 

     MyArrayList.getInstance().add(item); 

     System.out.println(MyArrayList.getInstance().getItem(0)); 
     //Outputs [email protected] instead of the value Banana. 

    } 
+0

'的System.out.println(MyArrayList.getInstance()的getItem(0).getName());'。如果没有'getName()'方法,请添加一个。 – NAMS

+0

它说“无法解决方法”。我在Item类中有一个getName()方法,但我无法通过MyArrayList类访问它。 – mattesj

+0

'System.out.println(MyArrayList.getInstance()。getItem(0).getClass()。getN ame());' –

回答

1

所以你正在把整数和字符串放入项目? ().getItem(0).getName()或 MyArrayList.getInstance()。getItem(0).getQuantity() 应该打印出你放的值。

如果您没有get方法创建它们,或者如果这些字段是公共的,您可以直接访问它们。

如果你想从类中列出所有的值,你可能想要覆盖toString()方法。

@Overwrite 
public String toString(){ 
    return name + "," + quantity; 
} 

并调用

System.out.println(MyArrayList.getInstance().getItem(0).toString()); 
相关问题