遍历输出的程序照着文中写的,但是不能够遍历输出集合中的元素是怎么回事,职能单独输出某一个。
public void testSort() {
List<Food> food = new ArrayList<Food>();//初始化一个List容器,并确定泛型为Food
Random random = new Random();
food.add(new Food(random.nextInt(1000)+"", "Orange"));
food.add(new Food(random.nextInt(1000)+"", "Apple"));
food.add(new Food(random.nextInt(1000)+"", "Apple"));
System.out.println("---------------排序------------------");
Collections.sort(food);
//food2是个Food对象,从food的List集合中取出(定义出了泛型(Food),取出的对象就是Food,无需强转)
for (Food food2 : food) {
//直接调用Food对象的getId()和getName()方法
System.out.println("ID:"+food2.getId()+" "+ "名称:"+food2.getName());
}
}
代码看下