Android 从数组中提取随机字符串,仅一次
我有一个程序,它使用Random生成一个随机数,从数组中选择一个字符串。我想做的是避免同一个字符串被选中两次!我还想存储拉取的随机字符串的整个列表,并能够在需要时清除它们 “我的随机字符串”显示在文本视图中。Android 从数组中提取随机字符串,仅一次,android,arrays,string,random,Android,Arrays,String,Random,我有一个程序,它使用Random生成一个随机数,从数组中选择一个字符串。我想做的是避免同一个字符串被选中两次!我还想存储拉取的随机字符串的整个列表,并能够在需要时清除它们 “我的随机字符串”显示在文本视图中。//使用set可避免重复。。。。 //use set to avoid Duplicatess.... Set<String> objSet = new HashSet<String>(); boolean one= objSet .add("hello"); Sy
//使用set可避免重复。。。。
//use set to avoid Duplicatess....
Set<String> objSet = new HashSet<String>();
boolean one= objSet .add("hello");
System.out.println(one); // Prints "true"
boolean two= objSet .add("hello");
System.out.println(two); // Prints "false"
// if you want to remove Specific String after add then you have to use HashMap
Set objSet=new HashSet();
boolean one=objSet.add(“hello”);
System.out.println(一);//打印“真实”
布尔值2=objSet.add(“hello”);
System.out.println(二);//打印“假”
//如果要在添加后删除特定字符串,则必须使用HashMap
一个简单的解决方案是将数组转换为一个列表,然后创建另一个列表来存储拉入的字符串。因此,当您拉取随机字符串时,请将其从原始列表中删除,并将其添加到拉取字符串列表中
差不多
List<String> strings = Arrays.asList(stringsArray);
List<String> usedStrings = new ArrayList<>();
String s = strings.remove(index);
doSomethingWithString(s);
usedStrings.add(s);
List strings=Arrays.asList(stringsArray);
List usedStrings=new ArrayList();
字符串s=字符串。删除(索引);
带字符串的dosomething;
使用字符串。添加(s);
这样,您就不会两次使用同一个字符串,并且可以跟踪使用过的字符串将随机字符串放入ArrayList中。在此之前,请检查是否已经不包含任何字符串。使用!contains(randomstr)method else find other random您是否可以提供您尝试过的代码,运行时发生了什么?将列表(Collections.shuffle)(或列表的副本)洗牌,然后从列表中按顺序提取项目。