简体   繁体   English

在Java中使用集合的正确方法?

[英]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 ... 我的意思是:在收集框架中,有许多数据结构可供使用,并且可以使用ArrayListLinkedList ,Priority queue来实现创建类( MemberList )以管理许多成员的聚合。

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. 我想使用一种适合我的需求的数据结构,当涉及搜索,排序,删除,添加,修改和删除时,它具有尽可能小的Big O的可能。

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. 这个问题太笼统了,“在Java中使用集合的正确方法”也是一个哲学问题,因此无法科学地回答。

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). 我建议您使用HashMap<String,Member>类的东西,其中每个成员都有一个可识别的唯一键(例如用户名)。 This will grant you O(1) access speed and allow you to iterate when you need it using .values() . 这将为您提供O(1)访问速度,并允许您在需要时使用.values()进行迭代。

You can use a HashMap like so: 您可以像这样使用HashMap:

// 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. 如果您不想使用JDBC,我将使用数组列表。 But later if your project going to growe, you have to use JDBC. 但是以后如果您的项目要发展,则必须使用JDBC。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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