public class EmpArray {
private int id;
private String name,address;
EmpArray(int id, String name, String addr)
{
this.id = id;
this.name = name;
address = addr;
}
int getId()
{
return id;
}
void display()
{
System.out.println("Employee details are ---");
System.out.println("Id - "+id);
System.out.println("Name - "+name);
System.out.println("Address - "+address);
}
}
在main()迭代類對象,我創建了一個ArrayList來存儲EmpArray類對象 我的意圖這裏,就是不存儲重複ID ..如何從一個ArrayList迭代
import java.util.*;
import java.io.*;
public class EmpArrayList {
/**
* @param args
* @throws IOException
* @throws NumberFormatException
*/
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String name,address;
int id;
//Create ArrayList
ArrayList<EmpArray> arl = new ArrayList<EmpArray>();
//Attach iterator to ArraList to check if Id is already added!!
Iterator it = arl.iterator();
enter:
{
for(int i =0 ; i < 3; i++)
{
System.out.println("Enter Id:");
id = Integer.parseInt(br.readLine());
while(it.hasNext())
{
EmpArray temp = (EmpArray) (it.next());
if(id == temp.getId())
{
System.out.println("Id already exists! Add another Id : ");
break enter;
}
}
System.out.println("Enter Name:");
name = br.readLine();
System.out.println("Enter Address:");
address = br.readLine();
//Create an object of EmpArray Class
EmpArray e = new EmpArray(id,name,address);
//Add this EmpArray object to the ArrayList
arl.add(e);
}
}
//Now display all the elements stored in the ArrayList
/*for(int i=0 ; i< 3; i++)
{
EmpArray ea = arl.get(i);
ea.display();
}*/
//Get Id from the user and display only that employee's details
System.out.println("Enter Id whose details are required? : ");
int searchId = Integer.parseInt(br.readLine());
boolean isIdAvailable = false;
for(int i = 0; i < 3 ; i++)
{
EmpArray ea = arl.get(i);
if(searchId == ea.getId())
{
ea.display();
isIdAvailable = true;
break;
}
}
if(!isIdAvailable)
System.out.println("Employee details are not available");
}
}
我第二次嘗試輸入Id時收到異常。異常是在 it.next() 異常是併發修改異常 有人可以請幫助,爲什麼我有這種例外?
它的定義應該可以幫助你理解爲什麼。 http://docs.oracle.com/javase/7/docs/api/java/util/ConcurrentModificationException.html'當這樣的修改不被允許時,可以通過檢測到對象的併發修改的方法拋出此異常。' – 2015-03-02 13:10:02
迭代時,你在'arl.add(e);列表中添加一個元素,''Iterator被設計爲快速失敗,所以在迭代過程中的任何修改都會拋出異常。 – Saravana 2015-03-02 13:13:15
如果需要,您可以使用防故障的ListIterator – Saravana 2015-03-02 13:14:11