java - Arraylist 打印带有计数的对象
问题描述
这是我的代码
ArrayList<Restaurant> restaurant= new ArrayList<Restaurant>();
餐厅课内,
@Override
public String toString() {
int i=1;
return "\n"+(i++)+". "+this.restaurantName +
"\t\t"+this.location;
}
我想这样打印
[ 1. 班加罗尔必胜客,2. 多米诺骨牌德里]
相反,它打印
[ 1. 班加罗尔必胜客,1. 多米诺骨牌德里]
需要代码帮助。
解决方案
这是另一种解决方案,我不确定您有什么实际问题,因此请提供另一种可能的解决方案。这可能对你有用。
public class Restaurant {
static int index = 1;
String restaurantName;
String location;
int curIndex;
Restaurant(final String restaurantName, final String location) {
this.restaurantName = restaurantName;
this.location = location;
this.curIndex = index++;
}
public static void main(final String[] input) {
final ArrayList<Restaurant> restaurant = new ArrayList<Restaurant>();
restaurant.add(new Restaurant("pizzahut", "bangalore"));
restaurant.add(new Restaurant("dominos", "delhi"));
restaurant.forEach(r -> System.out.println(r));
}
public String toString() {
return "\n" + curIndex + ". " + this.restaurantName +
"\t\t" + this.location;
}
}
推荐阅读
- node.js - 如何在节点js中获取router.get()之外的变量
- chart.js - ChartJS 3.0.2 中的时间序列刻度。带来错误“此方法未实现:找不到适配器或集成不完整......”
- python - Pytest 参数化在最后一次迭代后运行
- mkmapview - 从 MKMapView 上的 CLLocationCoordinate2D 数组添加点不起作用
- macos - DriverKit IOUSBHostInterface 的 CopyPipe 失败并出现 kIOReturnError (0xe00002bc)
- jupyter-notebook - 模块“torch.jit”没有属性“未使用”
- javascript - 如何使用 React Router 将道具从一页传递到另一页
- powershell - 使用 PowerShell 下载并安装 CCleaner
- ruby-on-rails - 数组的未定义方法“permit”
- sql - 嵌套选择语句的 LINQ Lambda 查询