我的代码中的错误阻止它显示以下输出:
宝马别克奥迪大众雪佛兰福特欧宝雷诺标致雪铁龙野马梅赛德斯菲亚特
然后是相同的列表,但按字母顺序排序。这是一个包含3个类的小代码 请复制并粘贴代码以便自己查看。
import java.util.Collections;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
public class Data implements List<String> {
public static String[] brands = { "BMW","Buick", "Audi", "VW","Chevrolet", "Ford", "Opel",
"Renault", "Peugeot", "Citroen","Mustang", "Mercedes", "Fiat" };
public Data() {
}
}
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Brands {
List<String> brands = new ArrayList<String>();
public Brands(){
this(null);
}
public Brands(Data data){
this.brands = data;
}
public List<String> sortList(){
Collections.sort(brands);
return brands;
}
public List<String> reverseTheOrder(){
Collections.reverse(brands);
return brands;
}
public String toString(){
return ""+brands+""+sortList();
}
}
public class Brandstester {
public static void main(String[] args) {
Data data = new Data();
Brands brands = new Brands(data);
System.out.println(brands);
brands.sortList();
System.out.println(brands);
brands.reverseTheOrder();
System.out.println(brands);
}
}
答案 0 :(得分:0)
当你调用最后一个运算符:System.out.println(brands);
时,它会调用方法Brand.toString()
,在其中调用sortList()
。这个导致再次按字母顺序排序。