romancha

Collections 2

Jan 22nd, 2018
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.39 KB | None | 0 0
  1. import java.util.*;
  2.  
  3. public class Main {
  4.     public static void main(String[] args) {
  5.         List<String> list = new LinkedList<>();
  6.  
  7.         Random random = new Random();
  8.  
  9.         for (int i = 0; i < 10; i++) {
  10.             int index = random.nextInt(i + 1); //Генерируем индекс куда будем вставлять элемент
  11.             while(true) { //Бесконечный цикл до тех пор пока мы не найдем число, которого еще нет в списке
  12.                 int element = random.nextInt(11); //Генерируем произвольное число до 11 (11 можно заменить на любое значение, я брал 11 что бы было видно что значения не повторяются)
  13.                 if (!list.contains(Integer.toString(element))) { //Проверяем есть ли объект который мы сгенерировали в списке
  14.                     list.add(index, Integer.toString(element)); //Если не было, то добавляем его в список
  15.                     break; // и выходим из бесконечного цикла
  16.                 }
  17.             }
  18.         }
  19.         Iterator iterator = list.iterator();
  20.         while (iterator.hasNext()) {
  21.             System.out.print(iterator.next() + " ");
  22.         }
  23.     }
  24. }
Add Comment
Please, Sign In to add comment