英文:
Assigning first element of arraylist to another arraylist
问题
如何从另一个类获取ArrayList的第一个元素,并将其赋值给另一个ArrayList?
public class PaymentScreenController {
public ListView<Customer> lvCustomer1;
public ArrayList<Customer> allcustomers;
public ArrayList<Customer> cusarray;
private Table tbl = new Table();
@FXML
public void initialize() {
allcustomers = tbl.getCustomers();
// 从'allcustomers'获取第一个元素并赋值给cusarray?
// 我已经尝试过 cusarray = allcustomers.get(0),但那行不通?
}
}
然后将cusarray
赋值给一个ListView?
如有帮助,感激不尽。谢谢!
英文:
How do I get the first element of an ArrayList from another class and assign it to another ArrayList?
public class PaymentScreenController {
public ListView<Customer> lvCustomer1;
public ArrayList<Customer> allcustomers;
public ArrayList<Customer> cusarray;
private Table tbl = new Table();
@FXML
public void initialize() {
allcustomers = tbl.getCustomers();
// Getting first element from 'allcustomers and assigning it to cusarray?
// I have tried cusarray = allcustomers.get(0) but that doesn't work?
}
}
And then assign cus array to a listview?
Any help would be appreciated thanks
答案1
得分: 0
尝试:
cusarray.add(allcustomers.get(0));
英文:
try:
cusarray.add(allcustomers.get(0));
答案2
得分: 0
你可以初始化 cusarray
并将项目添加到列表中:
cusarray = new ArrayList<>();
cusarray.add(allcustomers.get(0));
这对你应该有效。
然后对于 ListView,我想你可能想要类似这样的代码:
lvCustomer1 = new ListView(FXCollections.observableArrayList(cusarray));
lvCustomer1.setCellFactory(param -> new ListCell<Customer>() {
@Override
protected void updateItem(Customer item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null || item.<function to get name>() == null) {
setText(null);
} else {
setText(item.<function to get name>());
}
}
});
虽然我还没有测试过 ListView 的部分。
编辑:现在已经测试了 ListView 的代码,它按预期工作。
英文:
You can initialize the cusarray and add the item to the list:
cusarray = new ArrayList<>();
cusarray.add(allcustomers.get(0);
That should work for you.
Then for the ListView, I guess you'd want something like this:
lvCustomer1 = new ListView(FXCollections.observableArrayList(cusarray));
lvCustomer1.setCellFactory(param -> new ListCell<Customer>() {
@Override
protected void updateItem(Customer item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null || item.<function to get name>() == null) {
setText(null);
} else {
setText(item.<function to get name>());
}
}
});
Though I haven't tested the ListView bit.
EDIT: Now tested the code for the ListView and it works as intended.
专注分享java语言的经验与见解,让所有开发者获益!
评论