随机产生20个字符串并且字符串不能重复 且进行排序

本文介绍了一个Java程序,该程序能够生成20个不重复的随机小写字母,并利用HashSet确保唯一性,最后使用TreeSet进行排序展示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. package com.test.kaoshi;   
  2.   
  3. import java.util.HashSet;   
  4. import java.util.Iterator;   
  5. import java.util.Random;   
  6. import java.util.Set;   
  7. import java.util.TreeSet;   
  8.   
  9. public class RadomDemo {   
  10. /**  
  11.  * 随机产生20个字符串并且字符串不能重复 且进行排序  
  12.  * @param random  
  13.  * @param len  
  14.  * @return  
  15.  */  
  16.     public Set getChar(){   
  17.            
  18.         Set numberSet01 = new HashSet();   
  19.         Random rdm = new Random();   
  20.         char ch;   
  21.         while(numberSet01.size()<20){    
  22.            int rdGet = Math.abs(rdm.nextInt())%26+97;//产生97到122的随机数a-z值   
  23.             ch=(char)rdGet;   
  24.             numberSet01.add(ch);   
  25.             //Set中是不能放进重复的值的,当它有20个时,就满足你的条件了    
  26.         }    
  27.           return numberSet01;   
  28.         }   
  29.     public static void main(String[] args) {   
  30.         RadomDemo rd = new RadomDemo();   
  31.         Set numberSet01=rd.getChar();   
  32.            
  33.         Set numberSet = new TreeSet();    
  34.         numberSet.addAll(numberSet01);   
  35.         for(Iterator it=numberSet01.iterator();it.hasNext();){    
  36.             System.out.print(it.next());    
  37.             }    
  38.         System.out.println();   
  39.         for(Iterator it=numberSet.iterator();it.hasNext();){    
  40.             System.out.print(it.next());    
  41.             }    
  42.     }   
  43. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值