5

2 つの arraylist の内容を比較したい。

このようにオブジェクトを格納しています。

Arraylist 1 の場合:

Employee e1=new Employee();

e1.setID("1");
e1.setID("2");

ArrayList<Employee>list1 = new ArrayList<Employee>(); 

if(e1!=null){
    list1.add(e1);
}

Arraylist 2 の場合:

Employee e2=new Employee();

e2.setID("1");
e2.setID("2");
e2.setID("4");

ArrayList<Employee>list2 = new ArrayList<Employee>(); 

if(e2!=null){
    list2.add(e2);
}

今、私はこの方法で上記のarraylistの内容を比較しようとしています

ArrayList<Employee>unmatchedList = new ArrayList<Employee>();   

for (Employee l1 : list1){                               
    if(!list2.contains(l1.getID())){    
        System.out.println("list2 does not contains this ID"+l1.getID());   
        Employee e3=new Employee();          
        e3.setID(l1.getID());

        if(unmatchedList==null){            
        unmatchedList=new ArrayList<Employee>();            
        unmatchedList.add(e3);          
        }

        if(unmatchedList!=null){                            
            unmatchedList.add(e3);              
        }                       
    }
}

しかし、「4」のみとして正しい unmatchedList コンテンツを取得していません。unmatchedList を「1」と「2」として取得していますが、これは間違っています。では、「unmatchedList」でのみ一致しないコンテンツを取得するにはどうすればよいですか

4

5 に答える 5

5

クラスEmployeeが次のように定義されている場合:

public class Employee {

private int id;

public Employee(int id){
    this.id = id;
}

public int getId() {
    return id;
}

@Override
public String toString() {
    return "Id : " + this.id;
}

@Override
public boolean equals(Object obj) {
    return (obj instanceof Employee) && this.id == ((Employee)obj).getId();
}

Main メソッドでは、次のように不一致のコンテンツを取得できます。

 public static void main( String[] args )
{
   List<Employee> l1 = new ArrayList<Employee>();
   l1.add(new Employee(1));
   l1.add(new Employee(2));
   l1.add(new Employee(3));
   l1.add(new Employee(4));
   l1.add(new Employee(5));


   List<Employee> l2 = new ArrayList<Employee>();
   l2.add(new Employee(4));
   l2.add(new Employee(5));


   l1.removeAll(l2);
   System.out.println(l1);

}

これは印刷されます:[Id : 1, Id : 2, Id : 3]

この作業では、equalsメソッドをオーバーライドする必要があることに注意してください。

于 2012-11-22T10:13:21.217 に答える
1

equalsIDで比較するメソッドを従業員に追加し、コピーを作成しlist2て呼び出しますremoveAll

List<Employee> list1 = ...;
List<Employee> list2 = ...;
List<Employee> unmatchedList = new ArrayList<Employee>(list2);
unmatchedList.removeAll(list1);

完全な例については、@Dimitriの回答を参照してください。

于 2012-11-22T09:55:15.700 に答える
1

問題はこのコードです: -

if(!list2.contains(l1.getID())){

あなたlist2は で、ArrayList<Employee>の封じ込めをチェックしていますl1.getId()。したがって、あなたのif条件は常に真になります。


クラスでオーバーライドequalsしてhashCodeメソッドを作成し、次を使用する必要があります。Employee

if(!list2.contains(l1))

list2 に employee が含まれているかどうかを確認しますl1


idそして、リストに追加する前に、なぜ3回連続して設定しているのですか。3 つの ID をすべて追加するのではなく、IDEmployeeに最後の値が設定された単一の ID のみを追加します。あなたはそれを修正する必要があります: -

e2.setID("1");
e2.setID("2");
e2.setID("4");

list.add(e2);  // Will only add one Employee with id = 4
于 2012-11-22T09:41:15.977 に答える
0

シナリオに使用する必要があると思いますSet。この例が役立つかもしれません。

Employeeクラス_

package com.yourcomp;

/**
 * <br>
 * <div style="width:600px;text-align:justify;">
 *
 * TODO: Class comment.
 *
 * </div>
 * <br>
 *
 */
public class Employee {

    private int id;

    /**
     * Constructor for Employee. <tt></tt>
     */
    public Employee() {
        this(-1);
    }

    /**
     * Constructor for Employee. <tt></tt>
     */
    public Employee(int id) {
        this.id = id;
    }

    /**
     * Gets the id.
     * 
     * @return <tt> the id.</tt>
     */
    public int getId() {
        return id;
    }

    /**
     * Sets the id.
     *
     * @param id <tt> the id to set.</tt>
     */
    public void setId(int id) {
        this.id = id;
    }

    @Override
    public boolean equals(Object obj) {
        return this.id == ((Employee)obj).id;
    }

    /* (non-Javadoc)
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        return "Employee [id=" + id + "]";
    }

    /* (non-Javadoc)
     * @see java.lang.Object#hashCode()
     */
    @Override
    public int hashCode() {
        // TODO Auto-generated method stub
        return new Integer(id).hashCode();
    }



}

TestEmployeeクラス:

package com.yourcomp;

import java.util.HashSet;
import java.util.Set;

/**
 * <br>
 * <div style="width:600px;text-align:justify;">
 *
 * TODO: Class comment.
 *
 * </div>
 * <br>
 * 
 */
public class TestEmployee {

    public static void main(String[] args) {
        // creating the first set with employees having ID's 1 to 5
        Set<Employee> set1 = new HashSet<Employee>();
        for(int i=1;i<5;i++) 
            set1.add(new Employee(i));

        System.out.println(set1); // printing it

        // creating the first set with employees having ID's 3 to 8.
        // note that now you have two employees with same ID, 3 & 4
        Set<Employee> set2 = new HashSet<Employee>();
        for(int i=3;i<8;i++)
            set2.add(new Employee(i));

        System.out.println(set2);// printing the second set

        // creates a final set to contain all elements from above two sets without duplicates
        Set<Employee> finalSet = new HashSet<Employee>();
        for(Employee employee:set1)
            finalSet.add(employee); // adds first set content


        for(Employee employee:set2)
            finalSet.add(employee); // adds second set content. If any duplicates found, it will be overwritten

        System.out.println(finalSet); // prints the final set



    }
}

そして出力

[Employee [id=1], Employee [id=2], Employee [id=3], Employee [id=4]]
[Employee [id=3], Employee [id=4], Employee [id=5], Employee [id=6], Employee [id=7]]
[Employee [id=1], Employee [id=2], Employee [id=3], Employee [id=4], Employee [id=5], Employee [id=6], Employee [id=7]]
于 2012-11-22T09:56:41.867 に答える
0

Set を使用して違いを確認することもお勧めします。Set を使用できる場合は、Guava-Sets の差分メソッドを使用します: http://google-collections.googlecode.com/svn/trunk/javadoc/com/ google/common/collect/Sets.html#difference%28java.util.Set,%20java.util.Set%29

于 2012-11-22T10:30:21.010 に答える