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

Java入门第三季第6章——Collection.sort练习

标签:
Java

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;

public class Sort2 {
/**

  • 1.获取待选随机数列表字符串random长度; 2.获取随机数length1的长度,并判断长度不等于0;
  • 3.创建一个char[]ct数组,随机获取字符串random的其中一个字符并加入char[]中
  • 4.将char[]通过String类的valueOf()方法转成字符串
  • 5.判断ArrayList中有无当前随机数,若有,则重新获取随机数,若无,则加入ArrayList中;
  • 6.利用List中的Iterator()方法迭代输出List中的随机数
    /
    public void Sort2Test() {
    // String[] random=new
    // String[]{"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","0","1","2","3","4","5","6","7","8","9"};
    ArrayList<String> al = new ArrayList<String>();
    String random = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";// 随机数列表
    int a = random.length();// 待随机数索引长度
    String st = "";// 随机数名字
    while (true) {
    int length1 = 0;// 随机数长度
    // 创建一个length2获取值并判断不等于0的长度值
    int length2 = (int) (Math.random()
    10);
    if (length2 != 0) {
    length1 = length2;// 获取随机数长度
    }
    char[] ct = new char[length1];// 创建一个char数组
    for (int i = 0; i < length1; i++) {
    ct[i] = random.charAt((int) (Math.random() * a));
    st = String.valueOf(ct);
    }
    if (al.contains(st)) {
    continue;
    }
    al.add(st);
    System.out.println("将要添加字符串:" + st);
    if (al.size() == 10) {
    break;
    }
    }
    Iterator<String> it = al.iterator();
    System.out.println("----------------------排序前--------------------------");
    while (it.hasNext()) {
    System.out.println("元素:" + it.next());
    }
    Collections.sort(al);
    Iterator<String> it2 = al.iterator();
    System.out.println("----------------------排序后--------------------------");
    while (it2.hasNext()) {
    System.out.println("元素:" + it2.next());
    }
    }

    public static void main(String[] args) {
    Sort2 sort2 = new Sort2();
    sort2.Sort2Test();

    }
    }

点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消