Suppose given 10 elements in an array. I need to keep the values ​​in it when the mouse is clicked, and when filling the first element is deleted, the last value is recorded in its place, and then this element becomes the last - like a snake eating its tail. I can add elements ArrayList (add значение) , the condition is also a simple if (size > 10) , but how to make a loop? Given that intermediate values ​​should be kept until they are overwritten. You don't have to make a dynamic array, I'm just used to it.

  • A ring buffer or something? - m9_psy
  • Hmm, I do not know, I'll look. So far such an idea (I can’t check it until the evening): 'if (size> 10) {[1] = [10]; for (int i = 1; i <11; i ++) [i] ++} 'but somehow crooked. Ps mobile code can not issue ( - Krem Soda

1 answer 1

It is not necessary to do this in the condition. If you have size = 10 , for example, and when you write the 11th, you need to overwrite the 1st item in the list, use the modulo % operator:

 static int size = 10; public static void main(String[] args) { ArrayList<Integer> arr = new ArrayList<>(); // наш массив for (int i = 0; i < 15; i++) { if (arr.size() < size) // если у нас первые элементы arr.add(i % size, i); // тогда записываем новые элементы else arr.set(i % size, i); // а тут уже ПЕРЕзаписываем новыми } for (int j = 0; j < arr.size(); j++) { System.out.print(arr.get(j) + " "); } } 

Conclusion :

enter image description here

In the example, we write numbers in sequence from 0 to 14 in the ArrayList , where there are only 10 elements - as a result, elements with values ​​of 5-9 are not overwritten, and elements of 10-14 overwrite the numbers standing there.