2016-09-11 23 views
-2

我試圖提取用戶標識並根據列表檢查它是否已經存在。如果是,則打印「ID已存在」,如果不存在,則接收用戶名並將其存儲在列表中。我如何在列表中找到重複的內容

private LinkedList<Person> people = new LinkedList<Person>(); 

    private void addPerson(){ 
      int personId = readPersonId(); 
      Person person = person(personId); 
      if (person.hasId){ 
      System.out.println("ID already exists"); 
      } 
      else{ 
      String s = readName(); 
      people.add(new Person(personId, s, 2)); 
      } 
     } 

但是我的程序由於某種原因停在第一個循環中。

+3

您還沒有顯示任何循環...您的程序「停止」是什麼意思?它是否掛起或發出異常? – John3136

+0

什麼是'person.hasId'? – UnholySheep

+0

考慮使用Set而不是List。它不允許包含重複項。 –

回答

0

檢查已經存在的人員列表,並查找具有相同ID的任何人。如果沒有匹配的人,就去找一個人並將新人加入列表。

private LinkedList<Person> people = new LinkedList<Person>(); 

private void addPerson(){ 
    int personId = readPersonId(); 
    boolean found = false; 

    for (Person curr : people) { 
     if (curr.getId() == personId){ 
      System.out.println("ID already exists"); 
      found = true; 
      break; 
     } 
    } 

    if (!found) { 
     Person person = person(personId); 
     String s = readName(); 
     people.add(person); 
    } 
} 
+1

沒有解釋的代碼無助於人!請添加解釋以更好地解答此問題 – Li357

0

你可以轉儲的ArrayList轉換爲一組,比比較這些2.如果集合的大小比ArrayList的尺寸下,則有重複。

ArrayList<Integer> list = ...; 
Set<Integer> set = new HashSet<Integer>(list); 

if(set.size() < list.size()){ 
    /* There are duplicates in your arrayList */ 
} 
+0

無法確定給定的id是否重複。 – John3136

相關問題