【问题标题】:How do I generate random string array urls without repeating?如何在不重复的情况下生成随机字符串数组 url?
【发布时间】:2019-10-12 04:54:01
【问题描述】:

我正在尝试在 picasso 中生成随机字符串数组 url,一切正常,但它会重复,就像我在启动应用程序时有 28 个字符串数组项目一样,有些项目正在重复,但我在随机启动时一次只想要 1 个项目

这是我的代码

     ImageView imageView = itemView.findViewById(R.id.imageview);
        random = new Random(); 
        int p=  random.nextInt(icons.length);
        Picasso.get().load(icons[p]).into(imageView);

【问题讨论】:

    标签: java android arrays string random


    【解决方案1】:

    您可以在数组/列表中跟踪先前生成的整数,并在每次生成新的随机数时检查该数组。这样,如果生成的新整数已经存在于数组中,则生成一个新整数,直到生成了 28 个数字,之后需要清空数组重新开始。

    ImageView imageView = itemView.findViewById(R.id.imageview);
    Random random = new Random();
    List<Integer> prevInts = new ArrayList<>();
    Picasso.get().load(icons[randomUniqueInteger()]).into(imageView);
    
    public int randomUniqueInteger(){
        int p = 0;
        do {
            p = random.nextInt(icons.length);
        } while(prevInts.contains(p));
    
        if ((prevInts.size + 1) == icons.length){
           prevInts.clear();
        }
    
        prevInts.add(p);
    
        return p;
    }
    

    【讨论】:

      【解决方案2】:

      试试下面的

      ImageView imageView = itemView.findViewById(R.id.imageview);
      Random random = new Random();
      List<Integer> cache = new ArrayList<>();
      int p = 0;
      do {
           p = random.nextInt(icons.length);
      } while(cache.contains(p));
      cache.add(p);
      
      Picasso.get().load(icons[p]).into(imageView);
      

      【讨论】:

      • @RohanSaini 它永远不会重复,它应该被困在一个循环中,直到生成一个唯一的非持久数字,在哪里使用这个代码?它在视图支架中吗?
      • @Yousef Shamass 我在 Object instantiateItem 的寻呼机适配器中使用它
      猜你喜欢
      • 1970-01-01
      • 2017-09-13
      • 1970-01-01
      • 1970-01-01
      • 2010-12-07
      • 2017-04-05
      • 2014-02-09
      • 1970-01-01
      相关资源
      最近更新 更多