Currently working on a project where we have a message board server. I've gotten most everything to work except my last part where we want an arrayList that returns Oldest Messages and one for newest messages. Here is what I have so far and have tweeked and commented out some just trying new things.

public ArrayList<Message> getNewestMessages(int index) 
    {
        if (index < 0) {
            throw new IllegalArgumentException("Invalid index: " + index);
        }
        if (index >= this.messages.size()) {
            throw new IllegalArgumentException("Invalid index: " + index);
        }

        return this.messages.get(index);

        ArrayList<Message> userMessages = new ArrayList<Message>();

        //for (Message nextMessage : this.messages) {
           // if (nextMessage.getUserName().equals(name)) {
             //   userMessages.add(nextMessage);
           // }
        //}

        //return userMessages;
    }

This code is partial, please elaborate what is the problem...

The following is the entire code that I currently have for my messageCollection Class which follows my Message Class

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;

/**
 * MessageCollection represents the list of messages that have been
 * posted to the message board.
 * 
 * @author CS 1301 and **** Carolyn Leithner ****                                  
 * @version 10-21-10
 */
public class MessageCollection implements Serializable
 {
    private ArrayList<Message> messages;

    /**
     * Creates a MessageCollection object with size 0
     * <p>
     * Precondition: none
     * <p>
     * Postcondition: size() == 0
     */
    public MessageCollection()
    {
        this.messages = new ArrayList<Message>();
    }

    /**
     * Returns the number of Message objects in the messages.
     * <p>
     * Precondition: none
     * 
     * @return the size of the messages of messages
     */
    public int size()
    {
        return this.messages.size();
    }

    /**
     * Adds the specified Message to this MessageCollection.
     * 
     * Precondition: aMessage != null
     * <p>
     * Postcondiiton: get(size()-1).equals(aMessage) AND 
     *                size() == (size()@pre + 1)
     * 
     * @param aMessage the message to add 
     */

    public void add(Message aMessage)
    {
        if (aMessage == null) 
        {
            throw new IllegalArgumentException("The message cannot be null!");
        }

        this.messages.add(aMessage);
    }

    /**
     * Returns the message at the given index in the collection.
     * <p>
     * Precondition: 0 <= index < messages.size()
     * 
     * @param index the index of the message to return.
     * 
     * @return the message at that index
     */

    public Message get(int index)
    {
        if (index < 0) {
            throw new IllegalArgumentException("Invalid index: " + index);
        }
        if (index >= this.messages.size()) {
            throw new IllegalArgumentException("Invalid index: " + index);
        }

        return this.messages.get(index);
    }

    /**
     * Returns a list of posts from this MessageCollection by the given user.
     * <p>
     * Precondition: name != null
     * 
     * @param name the target user name
     * 
     * @return an ArrayList of Message objects with posts by the given user.
     */
    public ArrayList<Message> getAllFromUser(String name) 
    {
        if (name == null) {
            throw new IllegalArgumentException("The username cannot be null!");
        }

        ArrayList<Message> userMessages = new ArrayList<Message>();

        for (Message nextMessage : this.messages) {
            if (nextMessage.getUserName().equals(name)) {
                userMessages.add(nextMessage);
            }
        }

        return userMessages;
    }

    /**
     * Returns a list of posts from this MessageCollection whose timestamp
     * is less than the specified timestamp.
     * <p>
     * Precondition: aTimestamp != null
     * 
     * @param aTimestamp the timestamp that is the cutoff
     * 
     * @return an ArrayList of Message objects with timestamps 
     *         before the specifed timestamp.
     */
    public ArrayList<Message> getPostTimestampedBefore(Calendar aTimestamp)
    {
        if (aTimestamp ==null)
        {
            throw new IllegalArgumentException("the Timestamp cannot be null!");
        }

        ArrayList<Message> userMessages = new ArrayList<Message>();
        //for (Message nextMessage.compareTimestampTo
        // **** replace this comment with the header & body for getPostsTimestampedBefore    // TO DO

    }

    /**
     * Returns the index of the first Message object in this MessageCollection
     * from the user with the specified name, or -1 if there is no Message with
     * the specified name.
     * <p>
     * Precondition: aName != null
     * 
     * @param aName the name to search for
     * 
     * @return the index of the Message with the specified name,
     *         or -1 if no such Message exists
     */
    public int indexOf(String aName)
    {
        if (aName == null)
        {
            throw new IllegalArgumentException ("the name searching for cannot be null!");
        }
    }
    // **** replace this comment with the header and body for indexOf                    // TO DO

    /**
     * Removes each Message object from this MessageCollection
     * whose timestamp is less than the specified timestamp.
     * <p>
     * Precondition: aTimestamp != null
     * <p>
     * Postcondition: getPostsTimestampedBefore().size() == 0
     * 
     * @param aTimestamp the timestamp that is the cutoff
     */
    public void removePostsTimestampedBefore(Calendar aTimestamp)
    {
        if (aTimestamp == null)
        {
            throw new IllegalArgumentException ("a Timestamp cannot be null!");
        }

    }
    // **** replace this comment with the header & body for removePostsTimestampedBefore  // TO DO

    /**
     * Returns a list of the oldest 'count' Messages in this MessageCollection,
     * which are those first in the collection.
     * <p>
     * Precondition: count <= size()
     * 
     * @return  a list of the first 'count' Member objects from the collection
     */
    public ArrayList<Message> getOldestMessages(int index)

    {

        {
            throw new IllegalArgumentException ("size count of current ArrayList must be >= ArrayList size");
        }

    }
    // **** replace this comment with the header & body for getOldestMessages            // TO DO

    /**
     * Returns a list of the newest 'count' Messages in this MessageCollecion,
     * which are those last in the collection.
     * <p>
     * Precondition:  count <=size()
     * 
     * @return a list of the last 'count' Member objects from the collection
     */

    //public ArrayList<Message> getNewestMessages(int index)
    //{
        //ArrayList<Messages> newestMessagesList = new ArrayList<Messages>.get>= size-5();
            //{
              //  if (ArrayList<Message>.getNewestMessages() > size())
               // {

                //    throw new IllegalArgumentException ("size count of current ArrayList must be >= ArrayList size");
                //}
            //}

    //}
    public ArrayList<Message> getNewestMessages(int index)
    ArrayList<Messages> newestMessagesList = new ArrayList<Messages>.get>= this.size(5);
    {
        //ArrayList<Messages> newestMessagesList = new ArrayList<Messages>.get>= size(-5);
        if (index < 0)
        {
            throw new IllegalArgumentException("Invalid index: " + index);
        }
        if (index >= this.messages.size()) {
            throw new IllegalArgumentException("Invalid index: " + index);
        }

        return this.messages.get(index);

        ArrayList<Message> userMessages = new ArrayList<Message>();

        //for (Message nextMessage : this.messages) {
           // if (nextMessage.getUserName().equals(name)) {
             //   userMessages.add(nextMessage);
           // }
        //}

        //return userMessages;
    }

Ach, please use the [ code ] tag to post your code portion. It is very difficult to read a long code without the tag. :(

Anyway, you want to get the newest and oldest message of a user by specifying a user name? The way you add messages is to add at the end of ArrayList. An easiest way to find the oldest message for a user is to traverse from the front of ArrayList to find the message belongs to the user. The first message belongs to the user is the oldest message. The same way goes when you find the newest message (traverse the ArrayList from the back).

// Assumption
// ==========
// name - a username passed into the method
// messages - the class's variable which is an ArrayList of Message objects
// return found message object; otherwise return null if not found

// example to find oldest message
int pos = 0;
int max = messages.size();
Message foundMsg = null;
while (pos<max && foundMsg==null) {
  if (messages.get(pos).getUserName().equals(name)) {
    foundMsg = messages.get(pos);
  }
  pos++;
}
return foundMsg;

// example to find newest message
int pos = messages.size()-1;
Message foundMsg = null;
while (pos>=0 && foundMsg==null) {
  if (messages.get(pos).getUserName().equals(name)) {
    foundMsg = messages.get(pos);
  }
  pos--;
}
return foundMsg;

Sorry new at this. I thought it was to be in format of the program you were writing in. IE Java CS major so I'm sure I'll post more, but I think I'm to return the oldest and newest messages not based on userName but aTimestamp of when they were posted to the server. Confused as to if I should be using aTimestamp or my get method which gets the index number in conjunction with the arraylist size method. Still working on it and thanks for the help.

If your addMessage method always add a message to the end (not use index add), then the first message in the ArrayList is the oldest and the last is the newest. If you have time in the message and you add it using index, you could go through the ArrayList and have 2 message variables to keep oldest and newest. The psudo code below shows how to find oldest and newest message at the same time. You could, however, break it down into 2 methods to return newest and oldest.

oldest <- a message variable initialize to null
newest <- a message variable initialize to null
for each message in ArrayList
  if oldest is null
    oldest <- message timestamp
    newest <- message timestamp
  else
    if oldest timestamp is newer than message timestamp
      oldest <- message timestamp
    if newest timestamp is older than message timestamp
      newest <- message timestamp
return oldest, newest

The problem with this is that if there are 2 messages that are added at the same time, you have to pick one. In this one, it will pick the one it has found first.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.