简体   繁体   中英

right way to use collections in Java?

I have the following code. However I am doubting about if it is the right way to implement it or not.

What I mean is: in the collection framework there are many data structures to use and creating the class ( MemberList ) to manage the aggregations of many members can be implemented using ArrayList , LinkedList , priority queue ...

I would like to use a data structure that fits with my needs, and that has the least Big O possible when it comes to searching, sorting, deleting, adding, modifying and deleting.

public class MemberList{
    /**
     *a list of accounts existing in the database
     */
    private static List<Member> members = new ArrayList<Member>();
    /**
     * add a member to our member list
     * @param m the member to be added 
     */
    public static void Add(Member m)
    {
        members.add(m);

    /**
     * delete a member from our member list
     * @param m the member to be deleted
     */
    public static void Delete(Member m)
    {
        Iterator<Member> it = members.iterator();
        while(it.hasNext())
        {
            if(m.equals(it.next()))
            {
                it.remove();
            }
        }
    }

    /**
     * Search for a specific member in the member list
     * @param m the member that needs to be found
     * @return the reference of the object Member
     * @throws UserNotFoundExeption whether the member was not found in the list 
     */

    public static Member Search (Member m) throws UserNotFoundExeption
    {
        Iterator<Member> it = members.iterator();

        while(it.hasNext())
        {
            if(m.equals(it.next()))
            {
                return it.next();

            }else{
                UserNotFoundExeption ex = new UserNotFoundExeption(it.next().getUsername());
                throw ex;
            }
        }
        return null;
    }
    /**
     * The login method enables checking whether the login was made successfully or not. if not, it can throw two
     * exceptions to handle the errors
     * @param member
     * @return
     * @throws UserNotFoundExeption
     * @throws FailedLoginException
     */
    public static boolean  login (Member m)
            throws UserNotFoundExeption,FailedLoginException {

        try{
            Member member = Search(m);
            if (!m.authenticate(member.getPassword()))
            {
                FailedLoginException ex2 = new FailedLoginException (member.getPassword());
                throw ex2;
            }
            else
            {
                return true;
            }
        }catch(UserNotFoundExeption ex){
            throw ex;            
        }

     }

    /**
     * this behavior modify attributes of the corresponding class
     * @param <T> this generic helps to accept any type of parameter change, hence we can change any type
     * @param m this is the member that need to change his information
     * @param choice the choice of which information to change
     * @param change the new change on the member attribute
     * @throws UserNotFoundExeption 
     */
    public static <T> void Modify(Member m, int choice, T change) throws UserNotFoundExeption
    {
        try{
            Member member = Search(m);
            switch(choice)
            {
                case 1:
                    member.setUsername((String)change);
                    break;

                case 2:
                    member.setPassword((String)change);
                    break;

                case 3:
                    member.setCommunity((Community)change);
                    break;
            }
        }catch(UserNotFoundExeption ex){
            throw ex;            
        }

    }

    /**
     * display the member list objects information
     */
    public static void Display()
    {
        Iterator<Member> it = members.iterator();

        while(it.hasNext())
        {
            System.out.println(it.next());
        }
    }

    /**
     * Sort objects in the list
     */
    public static void Sort()
    {
        Iterator<Member> it = members.iterator();
        Member[] Members_Array = members.toArray(new Member[members.size()]);
        Member temp;

        for(int i = 0; i<members.size(); i++)
        {
            for(int j = 0; j < members.size() - (i+1); j++)
            {
                if(Members_Array[j].compareTo(Members_Array[j+1]) > 0)
                {
                    temp = Members_Array[j];
                    Members_Array[j] = Members_Array[j+1];
                    Members_Array[j+1] = temp;
                }
            }
        }

    }    
}

Thank you!

This question is too broad, and "the right way to use collections in Java" is also a philosophical question, so it cannot be scientifically answered.

Specifically to your case, depending on the pool of your members, you probably don't want to iterate over them when you need to pull a member out. I would recommend you use something like a HashMap<String,Member> , where each member has an identifiable unique key (a username for instance). This will grant you O(1) access speed and allow you to iterate when you need it using .values() .

You can use a HashMap like so:

// This is how you create a hash map:
HashMap<String,Member> members = new HashMap<String,Member>();

// This is how you add an object to it. It is slower than lists,
// but since reading happens far often, it pays off.
members.put("ben", new Member());

// This is how you access an object in the hash map.
// Accessing a hash map is O(1).
Member member = members.get("ben");

// This is how you remove an object from the hash map.
// Removing an object is also O(1)
members.remove("ben");

// Hash maps are also iterable
for(Member member : members.values()) {
}

I would use array list if you dont want to use JDBC. But later if your project going to growe, you have to use JDBC.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM