Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scrollable List in Java

Tags:

java

list

It may not be an appropriate term - scrollable but by scrollable, I mean a fixed size java.util.List with a different perspective.

The List should have defined number elements (predefined size). If an attempt is made to add more elements than the defined size, then those elements should be added with the removal of the top most elements in the List.

For example, let's say that the List has a predefined size of 5 elements and it already contains those many elements like the following (assuming the List is a generic type of String),

A
B
C
D
E

Now, if an additional element F is added, then the element at the top (A) should be scrolled up and vanished. The List should now have the following elements.

B
C
D
E
F

Similarly, if G is added, then it should contain the following elements.

C
D
E
F
G

Removing the top most element B and so on.

Is there a fair way to do this? Is there any library that may support this kind of functionality?

BTW, the structure is not necessarily only a java.util.List. It can be anything, starting from arrays but since I need this in a web application, components provided by swing like JList, JScrollPane cannot be used.

like image 398
Tiny Avatar asked Jun 12 '26 01:06

Tiny


2 Answers

What you need is a FIFO Data Structure like Queue.

You can write your own implementation to keep it at a fixed size like this or write a wrapper for an existing implementation like LinkedList.

like image 188
Jim Avatar answered Jun 14 '26 15:06

Jim


You can do this with an ArrayList:

ArrayList<Object> s = new ArrayList<>();
//Assuming the list has been populated
s.remove(0);
s.add(newObject);

This removes the element at index 0, then adds an element to the end of the ArrayList, giving you your desired result.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!