2015-06-16 80 views
0

我有一個數組列表中有四個對象元素,我需要將這些對象相互比較。我需要避免類似的對象比較,並在兩個對象相同的情況下做一個繼續。我已經嘗試了下面的代碼,但它避免了常見的對象迭代。任何人都可以建議我比較相同的數組列表中的元素的最佳方式?比較一個arrayList的元素與另一個

代碼:

List<Student> studentInfo= new ArrayList<Student>(); 

for (int i = 0; i < list.size(); i++) 
      { 
       for (int j = 0 ; j < list.size(); j++) 
       { 


        if(list.get(i).getstudentId().equals(list.get(j).getstudentId())) 
        continue; 

        } 

       } 

      } 
+2

你做雙比較。讓'j'從'i + 1'開始。 – RobAu

+2

您發佈的代碼沒有做任何有用的事(大概在繼續之後會有更多的代碼) - 您究竟在努力實現什麼? – NickJ

+0

尼克,我有一些條件,我需要在比較期間檢查,如果那些滿足,那麼我會將這些值設置爲一些對象。就像我說的我想避免類似對象之間的比較.. – maram05

回答

2

你需要避免的情況下我==法官在這種情況下,你如果將評估爲true

if(i != j && list.get(i).getstudentId().equals(list.get(j).getstudentId())) 
    break; 

,如果你想知道的出口如果你發現一個重複的循環,你需要一個外部變量來讓你知道(比如boolean或者int,它會顯示重複的地方)

0

你可以使用冒泡排序算法,但是instea那種,你可以用它來滿足你的需求。

一種更巧妙的方法來比較是:

public class Student { 

    private String id; 

    /** 
    * @return the id 
    */ 
    public String getId() { 
     return id; 
    } 

    /** 
    * @param id the id to set 
    */ 
    public void setId(String id) { 
     this.id = id; 
    } 



    @Override 
    public boolean equals (Object otherObject){ 
     if(!(otherObject instanceof Student)){ 
      return false; 
     } 
     if(((Student)otherObject).getId().equals(this.id)){ 
      return true; 
     } 
     return false; 
    } 

} 

在你的類:

for(int i = 0; i< studentList.size(); i++){ 
    for(int j = i+1; j< studentList.size(); j++){ 
     if(studentList.get(i).equals(studentList.get(j))){ 
      continue; 
     } 
    } 
} 
相關問題