Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 6 of 6

Thread: Looking for Collection class to do first if first out

  1. #1
    Junior Member
    Join Date
    Oct 2010
    Posts
    10
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Looking for Collection class to do first if first out

    I am a beginner to Java, so this is probably a very simple question:

    Is there an object that does this: I can set a size limit during instantiation, then as I add new items to it, if the size limit is reached, then the oldest item is automatically removed. First in, First out is what I am looking for.

    Suppose I want to write a simple program for Twitter streaming API, so I want to have a collection of no more than 100 items (tweets) at any time, so as new tweets come it, then should be added to the collection and if collection grows to > 100 items, then the oldest item is automatically removed.
    The order of items should always be preserved from oldest to newest item.

    Is there a collection object that does this automatically?


  2. #2
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,320
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: Looking for Collection class to do first if first out

    I don't think there is, but you could just as easily extend LinkedList and override its add function
    @Override 
    public void add(E object){
        super.add(object);
        if ( size() > 100){
            remove();
        }
    }

    If you think there may be use for the other add functions (eg addAll), you may need to override these functions as well and deal with the sizing as needed.

  3. #3
    Junior Member
    Join Date
    Oct 2010
    Posts
    10
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Looking for Collection class to do first if first out

    Thanks. Another question then: which Collection class should I use for storing items if I want to preserve the order of items?
    You mentioned LinkedList, is it better than ArrayList? What about Vector? Which one is more suitable for my case?

  4. #4
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,320
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: Looking for Collection class to do first if first out

    Quote Originally Posted by snytkine View Post
    Thanks. Another question then: which Collection class should I use for storing items if I want to preserve the order of items?
    You mentioned LinkedList, is it better than ArrayList? What about Vector? Which one is more suitable for my case?
    Each has its advantage in different situations. All implement List, which is the interface which defines a collection of ordered items. Vector is synchronized so is nice for a multithreading environment (although you can get a synchronized list using Collections.syncrhonizedList on any list implementation). The difference between ArrayList and LinkedList is subtle: LinkedList is theoretically faster when it comes to frequent resizing (ArrayList requires copying to a larger array if its max is met - resizing shouldn't happen often so this may not be a huge deal unless you are using many different ArrayList's that increase a lot) and removal of the first or inner elements (ArrayList requires moving all the elements after the position of removal), ArrayList is theoretically faster when retrieving indexes. Long story short, use a LinkedList for something like a Queue, and an ArrayList for times when you need something like an Array.

  5. #5
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Looking for Collection class to do first if first out

    If you want a Collection class that will allow you to add items and remove the earlier items, here is one I just made. Feel free to use/add/whatever to it:
    import java.util.Vector;
     
    public class LimitedArray<E> extends Vector<E>
    {
    	int size;
     
        public LimitedArray(int s) 
        {
        	size = s;
        }
     
        public boolean add(E e)
        {
        	if(this.size()==size)
        	{
        		this.remove(0);
        	}
        	return super.add(e);
        }
     
    }

    And a Test Class for it:
    public class MainClassTest 
    {
        public static void main(String args[]) 
        {
        	LimitedArray<String> array = new LimitedArray<String>(10);
        	System.out.println(array.size());
        	for(int i=0;i<20;i++)
        	{
        		array.add(i+"");
        	}
        	System.out.println(array);
        }
    }

    Works like a charm.
    Last edited by aussiemcgr; October 7th, 2010 at 08:45 PM.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  6. #6
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,320
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: Looking for Collection class to do first if first out

    As a demonstration (and because I'm a nerd and find Collections fascinating) this snipped benchmarks one of the differences between LinkedList and ArrayList. This code adds thousands of identical values to instances of both objects, then removes all objects starting at the beginning of the list. Since ArrayList is basically an array, removals at the beginning of the array require copying all subsequent values to their new positions. Linked list requires resetting a single reference (or 'pointer').
    	public static void main(String[] args){
    		java.util.List<String> list = new ArrayList<String>();
    		java.util.List<String> ll = new LinkedList<String>();
    		final int max = 100000;
    		for ( int i = 0; i < max; i++ ){
    			list.add("1");
    			ll.add("1");
    		}
    		long start = System.currentTimeMillis();
    		for ( int i = 0; i < max; i++ ){
    			list.remove(0);
    		}
    		System.out.println("ArrayList Time: " + (System.currentTimeMillis()- start));
    		start = System.currentTimeMillis();
    		for ( int i = 0; i < max; i++ ){
    			ll.remove(0);
    		}
    		System.out.println("LinkedList Time: " + (System.currentTimeMillis()- start));
    	 }

    Results:
    ArrayList Time: 4290
    LinkedList Time: 14

    Pushing it to the limit yes, but some occasions are pushed to the limit.

Similar Threads

  1. Collection.sort problem
    By Minken in forum What's Wrong With My Code?
    Replies: 12
    Last Post: September 21st, 2010, 06:24 PM
  2. Replies: 0
    Last Post: April 11th, 2010, 08:56 AM
  3. problem with data access when a class call another class
    By ea09530 in forum What's Wrong With My Code?
    Replies: 1
    Last Post: April 4th, 2010, 05:20 PM
  4. Java Garbage Collection and destructors
    By riddhik84 in forum Java Theory & Questions
    Replies: 5
    Last Post: October 1st, 2009, 09:06 AM
  5. Garbage Collection?
    By kalees in forum Collections and Generics
    Replies: 6
    Last Post: September 23rd, 2009, 03:07 AM