为了账号安全,请及时绑定邮箱和手机立即绑定

StringBuffer这个类能用用collections中的sort方法进行排序吗

StringBuffer这个类能用用collections中的sort方法进行排序吗

Hello_成 2015-04-16 11:14:44
package en.cc.course;import java.util.ArrayList;import java.util.Collections;import java.util.List;import java.util.Random;public class CollectionSort { public static List<StringBuffer>string = new ArrayList<StringBuffer>();——————————实例化一个List对象public StringBuffer randomChar(){ StringBuffer along = new StringBuffer("ASDFGHJKLQWERTYuiopzxcvbnm1234567890"); StringBuffer buffer = new StringBuffer(); Random random = new Random(); for(int i=0;i<random.nextInt(10)+1;i++){ int s=random.nextInt(along.length()); char d=along.charAt(s); buffer.append(d); } return buffer; //System.out.println(buffer); } /* * 生成10个随机字符串 */ public void foreach(){ for (int i = 0; i < 10; i++) { StringBuffer randomString = randomChar(); string.add(randomString); } } /* * 输出未排序前的10个字符串 */ public void foreach2(){ for (StringBuffer stringBuffer : string) { System.out.println(stringBuffer); } } public void testSort(){ } public static void main(String args[]){ CollectionSort ct = new CollectionSort(); ct.foreach(); ct.foreach2(); //Collections.sort(string);  ——————————老师为什么不能这样用啊;, }}
查看完整描述

1 回答

?
D许咚

TA贡献7条经验 获得超2个赞

1、Collections的void sort(List<T> list)方法,只能对泛型为T的list进行排序,而泛型T必须是Comparable(比较)接口的子类。

2、其他类型的数据要进行比较排序,必须继承Comparable接口并覆写equals()和compareTo()方法。

3、String和Integer都是Comparable接口的子类可以进行排序。


查看完整回答
反对 回复 2017-05-05
  • 1 回答
  • 0 关注
  • 1989 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信