Over a million developers have joined DZone.

Creating a Fixed Sized List in Java Using Apache Commons

· Java Zone

Check out this 8-step guide to see how you can increase your productivity by skipping slow application redeploys and by implementing application profiling, as you code! Brought to you in partnership with ZeroTurnaround.

There are many ways to create a fixed list in Java, one of them is by using the FixedSizeList class, found in the Apache org.apache.commons.collections package (http://commons.apache.org/collections/). FixedSizeList does not support the add, remove, clear and retain methods and the set method is allowed as far as it doesn’t change the list size:
package fixedsizelist.exemple;

import java.util.Arrays;
import java.util.List;
import org.apache.commons.collections.list.FixedSizeList;

public class FixedSizeListExemple {

    public static void main(String[] args) {

        List fixedList = FixedSizeList.decorate(Arrays.asList(new String[5]));

        fixedList.set(0, "some_name@yahoo.com");
        fixedList.set(1, "some_other_name@gmail.com");
        fixedList.set(2, "777_name@rocketmail.com");
        fixedList.set(3, "bond_007@yahoo.com");
        fixedList.set(4, "james99@yahoo.com");

        System.out.println("\tDisplay list values...\n");
        for (String obj : fixedList) {
            System.out.println(obj.toString());
        }

        try {
            System.out.println("\n\tTrying to modify our fixed list...\n");

            fixedList.add("paul01_mac@yahoo.com");
            fixedList.remove(3);
            fixedList.clear();

        } catch (Exception e) {
          System.out.println
          (" The add, remove, clear and retain operations are unsupported."
          + "\nThe set method is allowed (as it doesn't change the list size).\n");
        }
    }
}


And the output is:

From http://e-blog-java.blogspot.com/2012/02/how-to-create-fixed-list-in-java-using.html

The Java Zone is brought to you in partnership with ZeroTurnaround. Check out this 8-step guide to see how you can increase your productivity by skipping slow application redeploys and by implementing application profiling, as you code!

Topics:

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}