Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/google-apps-script/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
向JavaBean添加业务逻辑的良好设计_Java_Compare_Software Design_Compareto - Fatal编程技术网

向JavaBean添加业务逻辑的良好设计

向JavaBean添加业务逻辑的良好设计,java,compare,software-design,compareto,Java,Compare,Software Design,Compareto,在下面的代码中,将ismatch放在Value对象/javabean中有意义吗 ? 什么是好的设计。顺便说一句,我尝试了compareTo、compare、hashSet等,方法是跟随其他关于堆栈溢出的帖子,但不知何故,我仍然无法从两个列表中删除DUP public class SessionAttributes { private static final Logger LOGGER = Logger .getLogger(SessionAttributes.class);

在下面的代码中,将ismatch放在Value对象/javabean中有意义吗 ? 什么是好的设计。顺便说一句,我尝试了compareTo、compare、hashSet等,方法是跟随其他关于堆栈溢出的帖子,但不知何故,我仍然无法从两个列表中删除DUP

public class SessionAttributes { 

private static final Logger LOGGER = Logger
        .getLogger(SessionAttributes.class);

public SessionNotificationAttributes(String userName, String sessionState) {
    this.userName = userName;
    this.sessionState = sessionState;
}

String userName;
public String getUserName() {
    return userName;
}
public void setUserName(String userName) {
    this.userName = userName;
}
// .. getters/setters for sessionState

 public static isMatched (List<SessionAttributes> list1, 
             List<SessionAttributes> list2) {

   //.. custom logic here...
 }
设置removeDups=新树集

        boolean b1 = removeDups.add(user11);
        boolean b2 = removeDups.add(user12);
        boolean b3 = removeDups.add(user13);
        boolean b4 = removeDups.add(user3);
        boolean b5 = removeDups.add(user4);
        boolean b6 = removeDups.add(user5);

        System.out.println(" Set--" + removeDups);
设置-[ 用户名:postureuser2会话状态:已断开连接 , 用户名:postureuser1会话状态:已启动 , 用户名:postureuser5会话状态:已启动 , 用户名:postureuser1会话状态:已断开连接 , 用户名:postureuser1会话状态:已启动
]

我不会创建一个isMatched方法来比较两个SessionAttributes列表

我肯定会让SessionAttributes实现equals和hashCode。以相同的方式实现它们是至关重要的。如果要比较两个字符串是否相等,请使用这两个字符串计算哈希代码。如果您没有正确获得equals和hashCode,那么这一切都不起作用

如果您想将SessionAttributes放在SortedSet中,我也会让SessionAttributes实现Compariable

另外,我将使SessionAttributes不可变,因此没有setter,并将两个字符串元素声明为final。如果这样做,就可以将SessionAttribute添加到集合或映射中,而不必担心它们的值会发生变化。如果不使其不可变,则必须确保在将SessionAttributes值添加到列表或集合后不更改任何SessionAttributes值

我不会将它们放在列表中,而是将它们放在一个集合中,以确保在同一个SessionAttributes集合中没有重复项

如果要从其中一个集合中删除重复项,请对其使用集合的removeAll方法,将其传递给另一个SessionAttribute集合

作为一个旁注,SeStices状态看起来像一个具有有限数量可能值的变量,所以我会考虑为它定义一个枚举,而不是将它作为一个字符串。

我希望这有帮助

编辑:

compareTo方法不起作用,因为如果相等,则返回0;如果不相等,则返回-1。 相比之下,它没有履行合同。请看它

以下是SSCCE,其中包含一些更改和注释。因为在equals中,比较相等忽略大小写,所以必须在hashCode方法中将字符串转换为所有大写或小写,以便与equals保持一致。为了保持一致性,您还必须在compareTo方法中使用compareIgnoreCase。 由于compareTo方法有效,现在您可以简单地使用树集对对象集合进行排序

我删除了您不再需要的方法,并尝试在代码中添加一些有用的注释

package snippet;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

// You don't need to implement Comparator.
public class SessionAttributes implements Comparable<SessionAttributes> {

    // You typically define member variables at the top of the class definition.
    private final String userName;
    private final String sessionState;

    public SessionAttributes(String userName, String sessionState) {

        // Throw a NullPointerException from the constructor if either of the Strings is null. This way, you know that
        // if the object is constructed successfully, it is free of nulls.
        if (userName == null) {
            throw new NullPointerException("userName must not be null");
        }
        if (sessionState == null) {
            throw new NullPointerException("sessionState must not be null");
        }
        /*
         * String nasPort, String endpointProfile, String audiSessionId, String epsStatus, String securityGroup, String
         * nasIp, String postureStatus, String postureTimestamp) {
         */

        this.userName = userName;
        this.sessionState = sessionState;

        /*
         * this.nasPort = nasPort; this.endpoinProfile = endpointProfile; this.auditSessionId = audiSessionId;
         * this.epsStatus = epsStatus; this.securityGroup = securityGroup; this.nasIp = nasIp; this.postureStatus =
         * postureStatus; this.postureTimestamp = postureTimestamp;
         */

    }

    public String getUserName() {
        return userName;
    }

    public String getSessionState() {
        return sessionState;
    }

    @Override
    public int compareTo(SessionAttributes o) {
        if (this == o) {
            return 0;
        }
        // Null is considered less than any object.
        if (o == null) {
            return 1;
        }

        // Use compareToIgnoreCase since you used equalsIgnoreCase in equals.

        int diff = userName.compareToIgnoreCase(o.userName);
        if (diff != 0)
            return diff;

        diff = sessionState.compareToIgnoreCase(o.sessionState);
        return diff;
    }

    // public int compareTo(SessionAttributes o) {
    // // TODO Auto-generated method stub
    // if (this.getUserName().equals(o.getUserName()) && this.getSessionState().equalsIgnoreCase(o.getSessionState())) {
    // return 0;
    // }
    // return -1;
    // }

    public String toString() {

        return "\n User Name : " + this.getUserName() + " Session State : " + getSessionState() + "\n";
    }

    // public boolean equals(SessionAttributes obj) {
    //
    // if (obj == null || !(obj instanceof SessionAttributes)) {
    // return false;
    // }
    // System.out.println(" In equals==");
    // boolean isSameUserName = obj.userName.equalsIgnoreCase(this.userName);
    // boolean isSameState = obj.sessionState.equalsIgnoreCase(this.sessionState);
    // return (isSameUserName && isSameState);
    // }

    public boolean equals(Object o) {
        // See if o is the same object. If it is, return true.
        if (o == this) {
            return true;
        }

        // The instanceof check also checks for null. If o is null, instanceof will be false.
        if (!(o instanceof SessionAttributes)) {
            return false;
        }

        SessionAttributes that = (SessionAttributes) o;
        return userName.equalsIgnoreCase(that.userName) && sessionState.equalsIgnoreCase(sessionState);
    }

    public int hashCode() {

        System.out.println(" in hashcode ");
        int hash = 1;
        // Since in equals you are comparing for equality and ignoring case, you must convert the Strings to either
        // lower
        // or upper case when computing the hashCode so that it will always be consistent with equals.
        hash = hash * 17 + this.getUserName().toUpperCase().hashCode();
        hash = hash * 31 + this.getSessionState().toUpperCase().hashCode();
        // hash = hash * 13 + this.getAuditSessionId().hashCode();
        System.out.println(" hash=>" + hash);
        return hash;
    }

    public static void main(String[] args) {
        // sortSet();
        // sortLists();

        // expectedSessionList
        List<SessionAttributes> expectedSessionList = new ArrayList<SessionAttributes>();

        SessionAttributes user11 = new SessionAttributes("postureuser1", "STARTED"); //
        // ,null,null,null,null,null,null,null,null);

        SessionAttributes user12 = new SessionAttributes("postureuser1", "DISCONNECTED");

        SessionAttributes user13 = new SessionAttributes("postureuser5", "STARTED");

        expectedSessionList.add(user11);
        expectedSessionList.add(user12);
        expectedSessionList.add(user13);

        System.out.println("expectedSessionList: " + expectedSessionList);

        // actualSessionList
        List<SessionAttributes> actualSessionList = new ArrayList<SessionAttributes>();

        SessionAttributes user3 = new SessionAttributes("postureuser1", "STARTED");
        // ,null,null,null,null,null,null,null,null);

        SessionAttributes user4 = new SessionAttributes("postureuser1", "DISCONNECTED");

        SessionAttributes user5 = new SessionAttributes("postureuser2", "DISCONNECTED");

        // ,null,null,null,null,null,null,null,null);

        actualSessionList.add(user3);
        actualSessionList.add(user4);
        actualSessionList.add(user5);

        System.out.println("actualSessionList: " + actualSessionList);

        // removeDups
        // Use a TreeSet to sort it.
        Set<SessionAttributes> removeDups = new TreeSet<SessionAttributes>();

        boolean b1 = removeDups.add(user11);
        boolean b2 = removeDups.add(user12);
        boolean b3 = removeDups.add(user13);
        boolean b4 = removeDups.add(user3);
        boolean b5 = removeDups.add(user4);
        boolean b6 = removeDups.add(user5);

        System.out.println(" Set--" + removeDups);

        actualSessionList.removeAll(expectedSessionList);
        System.out.println("actualSessionList after removeAll: " + actualSessionList);

    }

}
输出:

expectedSessionList:[ 用户名:postureuser1会话状态:已启动 , 用户名:postureuser1会话状态:已断开连接 , 用户名:postureuser5会话状态:已启动 ]

实际任务列表:[ 用户名:postureuser1会话状态:已启动 , 用户名:postureuser1会话状态:已断开连接 , 用户名:postureuser2会话状态:已断开连接 ]

设置-[ 用户名:postureuser1会话状态:已断开连接 , 用户名:postureuser1会话状态:已启动 , 用户名:postureuser2会话状态:已断开连接 , 用户名:postureuser5会话状态:已启动 ]

removeAll后的actualSessionList:[ 用户名:postureuser2会话状态:已断开连接
]

谢谢您的评论。我实现了equals和hashCode。我没有粘贴整个代码。关于删除setter的好观点。我确实尝试过comparable,comparator,向集合中添加对象,HashSet,但不知何故它对我不起作用。我想要两个值匹配,比如userName=user1,sessionState=disconnected。不知何故,设置etc对我不起作用。这里有与此相关的帖子,所以我遵循了这些帖子,但没有起作用。不确定是不是由getter/setter引起的。让我尝试删除setter/getter并尝试Set/removaAll方法。如果您仍然无法使其工作,请使用一个简短、自包含、可编译的示例更新您的问题。实际上,上面的代码是针对SSCCE的。让我获取完整的代码,您可以建议可能缺少的内容。我放弃了Comparator,用蛮力的方式迭代会话bean列表,用EqualsThank找到匹配项谢谢,David。你测试过了吗?看起来和我贴的很像。谢谢你花时间在这上面。谢谢。嗨,是的,我试过了。它起作用了。不客气。表示感谢的方式是批准回答。如果您觉得我对您的问题的回答令您满意,请批准。谢谢
        boolean b1 = removeDups.add(user11);
        boolean b2 = removeDups.add(user12);
        boolean b3 = removeDups.add(user13);
        boolean b4 = removeDups.add(user3);
        boolean b5 = removeDups.add(user4);
        boolean b6 = removeDups.add(user5);

        System.out.println(" Set--" + removeDups);
package snippet;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

// You don't need to implement Comparator.
public class SessionAttributes implements Comparable<SessionAttributes> {

    // You typically define member variables at the top of the class definition.
    private final String userName;
    private final String sessionState;

    public SessionAttributes(String userName, String sessionState) {

        // Throw a NullPointerException from the constructor if either of the Strings is null. This way, you know that
        // if the object is constructed successfully, it is free of nulls.
        if (userName == null) {
            throw new NullPointerException("userName must not be null");
        }
        if (sessionState == null) {
            throw new NullPointerException("sessionState must not be null");
        }
        /*
         * String nasPort, String endpointProfile, String audiSessionId, String epsStatus, String securityGroup, String
         * nasIp, String postureStatus, String postureTimestamp) {
         */

        this.userName = userName;
        this.sessionState = sessionState;

        /*
         * this.nasPort = nasPort; this.endpoinProfile = endpointProfile; this.auditSessionId = audiSessionId;
         * this.epsStatus = epsStatus; this.securityGroup = securityGroup; this.nasIp = nasIp; this.postureStatus =
         * postureStatus; this.postureTimestamp = postureTimestamp;
         */

    }

    public String getUserName() {
        return userName;
    }

    public String getSessionState() {
        return sessionState;
    }

    @Override
    public int compareTo(SessionAttributes o) {
        if (this == o) {
            return 0;
        }
        // Null is considered less than any object.
        if (o == null) {
            return 1;
        }

        // Use compareToIgnoreCase since you used equalsIgnoreCase in equals.

        int diff = userName.compareToIgnoreCase(o.userName);
        if (diff != 0)
            return diff;

        diff = sessionState.compareToIgnoreCase(o.sessionState);
        return diff;
    }

    // public int compareTo(SessionAttributes o) {
    // // TODO Auto-generated method stub
    // if (this.getUserName().equals(o.getUserName()) && this.getSessionState().equalsIgnoreCase(o.getSessionState())) {
    // return 0;
    // }
    // return -1;
    // }

    public String toString() {

        return "\n User Name : " + this.getUserName() + " Session State : " + getSessionState() + "\n";
    }

    // public boolean equals(SessionAttributes obj) {
    //
    // if (obj == null || !(obj instanceof SessionAttributes)) {
    // return false;
    // }
    // System.out.println(" In equals==");
    // boolean isSameUserName = obj.userName.equalsIgnoreCase(this.userName);
    // boolean isSameState = obj.sessionState.equalsIgnoreCase(this.sessionState);
    // return (isSameUserName && isSameState);
    // }

    public boolean equals(Object o) {
        // See if o is the same object. If it is, return true.
        if (o == this) {
            return true;
        }

        // The instanceof check also checks for null. If o is null, instanceof will be false.
        if (!(o instanceof SessionAttributes)) {
            return false;
        }

        SessionAttributes that = (SessionAttributes) o;
        return userName.equalsIgnoreCase(that.userName) && sessionState.equalsIgnoreCase(sessionState);
    }

    public int hashCode() {

        System.out.println(" in hashcode ");
        int hash = 1;
        // Since in equals you are comparing for equality and ignoring case, you must convert the Strings to either
        // lower
        // or upper case when computing the hashCode so that it will always be consistent with equals.
        hash = hash * 17 + this.getUserName().toUpperCase().hashCode();
        hash = hash * 31 + this.getSessionState().toUpperCase().hashCode();
        // hash = hash * 13 + this.getAuditSessionId().hashCode();
        System.out.println(" hash=>" + hash);
        return hash;
    }

    public static void main(String[] args) {
        // sortSet();
        // sortLists();

        // expectedSessionList
        List<SessionAttributes> expectedSessionList = new ArrayList<SessionAttributes>();

        SessionAttributes user11 = new SessionAttributes("postureuser1", "STARTED"); //
        // ,null,null,null,null,null,null,null,null);

        SessionAttributes user12 = new SessionAttributes("postureuser1", "DISCONNECTED");

        SessionAttributes user13 = new SessionAttributes("postureuser5", "STARTED");

        expectedSessionList.add(user11);
        expectedSessionList.add(user12);
        expectedSessionList.add(user13);

        System.out.println("expectedSessionList: " + expectedSessionList);

        // actualSessionList
        List<SessionAttributes> actualSessionList = new ArrayList<SessionAttributes>();

        SessionAttributes user3 = new SessionAttributes("postureuser1", "STARTED");
        // ,null,null,null,null,null,null,null,null);

        SessionAttributes user4 = new SessionAttributes("postureuser1", "DISCONNECTED");

        SessionAttributes user5 = new SessionAttributes("postureuser2", "DISCONNECTED");

        // ,null,null,null,null,null,null,null,null);

        actualSessionList.add(user3);
        actualSessionList.add(user4);
        actualSessionList.add(user5);

        System.out.println("actualSessionList: " + actualSessionList);

        // removeDups
        // Use a TreeSet to sort it.
        Set<SessionAttributes> removeDups = new TreeSet<SessionAttributes>();

        boolean b1 = removeDups.add(user11);
        boolean b2 = removeDups.add(user12);
        boolean b3 = removeDups.add(user13);
        boolean b4 = removeDups.add(user3);
        boolean b5 = removeDups.add(user4);
        boolean b6 = removeDups.add(user5);

        System.out.println(" Set--" + removeDups);

        actualSessionList.removeAll(expectedSessionList);
        System.out.println("actualSessionList after removeAll: " + actualSessionList);

    }

}