首页 > 解决方案 > 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. 多米诺骨牌德里]

需要代码帮助。

标签: java

解决方案


这是另一种解决方案,我不确定您有什么实际问题,因此请提供另一种可能的解决方案。这可能对你有用。

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;
    }
}

推荐阅读