2012-07-27 145 views
3

我有一個基本問題。我有這樣的ArrayList:如何從Java ArrayList中獲取元素

@Named("AccountProfileController") 
@ViewScoped 
public class AccountProfile implements Serializable 
{ 

    @Resource(name = "jdbc/Oracle") 
    private DataSource ds; 
    private int id; 

    // Constructor 
    public AccountProfile() 
    { 
     // get the ID value 
     try 
     { 
      this.id = Integer.parseInt((String) FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("id")); 
     } 
     catch (Exception e) 
     { 
      this.id = 0; 
     } 
    } 
    // Create List to store user data 
    public ArrayList<userdata> dataList = new ArrayList<>(); 

    public class userdata 
    { 

     int userid; 
     int groupid; 
     String specialnumber; 
     String username; 
     String passwd; 
     Date datetochangepasswd; 
     String address; 
     String stateregion; 
     String country; 
     String userstatus; 
     String telephone; 
     Date dateuseradded; 
     Date userexpiredate; 
     Date dateuserlocked; 
     String city; 
     String email; 
     String description; 

     public userdata(int userid, int groupid, String specialnumber, String username, String passwd, Date datetochangepasswd, 
       String address, String stateregion, String country, String userstatus, String telephone, Date dateuseradded, 
       Date userexpiredate, Date dateuserlocked, String city, String email, String description) 
     { 

      this.userid = userid; 
      this.groupid = groupid; 
      this.specialnumber = specialnumber; 
      this.username = username; 
      this.passwd = passwd; 
      this.datetochangepasswd = datetochangepasswd; 
      this.address = address; 
      this.stateregion = stateregion; 
      this.country = country; 
      this.userstatus = userstatus; 
      this.telephone = telephone; 
      this.dateuseradded = dateuseradded; 
      this.userexpiredate = userexpiredate; 
      this.dateuserlocked = dateuserlocked; 
      this.city = city; 
      this.email = email; 
      this.description = description; 
     } 

     public String getAddress() 
     { 
      return address; 
     } 

     public void setAddress(String address) 
     { 
      this.address = address; 
     } 

     public String getCity() 
     { 
      return city; 
     } 

     public void setCity(String city) 
     { 
      this.city = city; 
     } 

     public String getCountry() 
     { 
      return country; 
     } 

     public void setCountry(String country) 
     { 
      this.country = country; 
     } 

     public Date getDatetochangepasswd() 
     { 
      return datetochangepasswd; 
     } 

     public void setDatetochangepasswd(Date datetochangepasswd) 
     { 
      this.datetochangepasswd = datetochangepasswd; 
     } 

     public Date getDateuseradded() 
     { 
      return dateuseradded; 
     } 

     public void setDateuseradded(Date dateuseradded) 
     { 
      this.dateuseradded = dateuseradded; 
     } 

     public Date getDateuserlocked() 
     { 
      return dateuserlocked; 
     } 

     public void setDateuserlocked(Date dateuserlocked) 
     { 
      this.dateuserlocked = dateuserlocked; 
     } 

     public String getDescription() 
     { 
      return description; 
     } 

     public void setDescription(String description) 
     { 
      this.description = description; 
     } 

     public String getEmail() 
     { 
      return email; 
     } 

     public void setEmail(String email) 
     { 
      this.email = email; 
     } 

     public int getGroupid() 
     { 
      return groupid; 
     } 

     public void setGroupid(int groupid) 
     { 
      this.groupid = groupid; 
     } 

     public String getPasswd() 
     { 
      return passwd; 
     } 

     public void setPasswd(String passwd) 
     { 
      this.passwd = passwd; 
     } 

     public String getSpecialnumber() 
     { 
      return specialnumber; 
     } 

     public void setSpecialnumber(String specialnumber) 
     { 
      this.specialnumber = specialnumber; 
     } 

     public String getStateregion() 
     { 
      return stateregion; 
     } 

     public void setStateregion(String stateregion) 
     { 
      this.stateregion = stateregion; 
     } 

     public String getTelephone() 
     { 
      return telephone; 
     } 

     public void setTelephone(String telephone) 
     { 
      this.telephone = telephone; 
     } 

     public Date getUserexpiredate() 
     { 
      return userexpiredate; 
     } 

     public void setUserexpiredate(Date userexpiredate) 
     { 
      this.userexpiredate = userexpiredate; 
     } 

     public int getUserid() 
     { 
      return userid; 
     } 

     public void setUserid(int userid) 
     { 
      this.userid = userid; 
     } 

     public String getUsername() 
     { 
      return username; 
     } 

     public void setUsername(String username) 
     { 
      this.username = username; 
     } 

     public String getUserstatus() 
     { 
      return userstatus; 
     } 

     public void setUserstatus(String userstatus) 
     { 
      this.userstatus = userstatus; 
     } 
    } 

    // Getter for the data list 
    public ArrayList<userdata> getuserdata() 
    { 

     return dataList; 
    } 

    @PostConstruct 
    public void initData() throws SQLException 
    { 
     //  settingsMap = new HashMap<String, String>(); 

     if (ds == null) 
     { 
      throw new SQLException("Can't get data source"); 
     } 
     // Initialize a connection to Oracle 
     Connection conn = ds.getConnection(); 

     if (conn == null) 
     { 
      throw new SQLException("Can't get database connection"); 
     } 
     // With SQL statement get all settings and values 
     PreparedStatement ps = conn.prepareStatement("SELECT * from USERS where USERID = ?"); 
     ps.setInt(1, id); 
     try 
     { 
      //get data from database   
      ResultSet result = ps.executeQuery(); 
      while (result.next()) 
      { 
       // Put the the data from Oracle into Array List 

       dataList.add(new userdata(result.getInt("USERID"), 
         result.getInt("GROUPID"), 
         result.getString("SPECIALNUMBER"), 
         result.getString("USERNAME"), 
         result.getString("PASSWD"), 
         toDate(result.getString("DATETOCHANGEPASSWD")), 
         result.getString("ADDRESS"), 
         result.getString("STATEREGION"), 
         result.getString("COUNTRY"), 
         result.getString("USERSTATUS"), 
         result.getString("TELEPHONE"), 
         toDate(result.getString("DATEUSERADDED")), 
         toDate(result.getString("USEREXPIREDATE")), 
         toDate(result.getString("DATEUSERLOCKED")), 
         result.getString("CITY"), 
         result.getString("EMAIL"), 
         result.getString("DESCRIPTION"))); 

      } 
     } 
     finally 
     { 
      ps.close(); 
      conn.close(); 
     } 
    } 
    // Call Crypto library for password convert into SHA hash 
    @Inject 
    @OSGiService(dynamic = true, waitTimeout = 5) 
    transient CryptoSHA SHA; 

    // Convert Password String into SHA hash 
    public String passwdConvert(String password) throws NoSuchAlgorithmException 
    { 
     return SHA.ShaEncryptHash(password); 
    } 

    // Insert the data into Oracle 
    public void saveData() throws SQLException, java.text.ParseException, NoSuchAlgorithmException 
    { 

     String SqlStatement = null; 

     if (ds == null) 
     { 
      throw new SQLException(); 
     } 

     Connection conn = ds.getConnection(); 
     if (conn == null) 
     { 
      throw new SQLException(); 
     } 

     PreparedStatement ps = null; 

     try 
     { 
      conn.setAutoCommit(false); 
      boolean committed = false; 
      try 
      {   /* 
       * insert into Oracle the default system(Linux) time 
       */ 


       SqlStatement = "UPDATE USERS " 
         + "SET " 
         + "USERID = ?, " 
         + "GROUPID = ?, " 
         + "SPECIALNUMBER = ?, " 
         + "USERNAME = ?, " 
         + "PASSWD = ?, " 
         + "DATETOCHANGEPASSWD = ?, " 
         + "ADDRESS = ?, " 
         + "STATEREGION = ?, " 
         + "COUNTRY = ?, " 
         + "USERSTATUS = ?, " 
         + "TELEPHONE = ?, " 
         + "DATEUSERADDED = ?, " 
         + "USEREXPIREDATE = ?, " 
         + "DATEUSERLOCKED = ?, " 
         + "CITY = ?, " 
         + "EMAIL = ?, " 
         + "DESCRIPTION = ? " 
         + "WHERE USERID = " + id; 

       ps = conn.prepareStatement(SqlStatement); 

       ps.setInt(1, dataList.get(userid)); 
       ps.setInt(2, dataList.get(groupid)); 
       ps.setString(3, dataList.get(specialnumber)); 
       ps.setString(4, dataList.get(username)); 
       ps.setString(5, passwdConvert(dataList.get(passwd))); 
       ps.setDate(6, toDate(dataList.get(datetochangepasswd))); 
       ps.setString(7, dataList.get(address)); 
       ps.setString(8, dataList.get(stateregion)); 
       ps.setString(9, dataList.get(country)); 
       ps.setString(10, dataList.get(userstatus)); 
       ps.setString(11, dataList.get(telephone)); 
       ps.setDate(12, toDate(dataList.get(dateuseradded))); 
       ps.setDate(13, toDate(dataList.get(userexpiredate))); 
       ps.setDate(14, toDate(dataList.get(dateuserlocked))); 
       ps.setString(15, dataList.get(city)); 
       ps.setString(16, dataList.get(email)); 
       ps.setString(17, dataList.get(description)); 


       ps.executeUpdate(); 

       conn.commit(); 
       committed = true; 
      } 
      finally 
      { 
       if (!committed) 
       { 
        conn.rollback(); 
       } 
      } 
     } 
     finally 
     { 
      /* 
      * Release the resources 
      */ 
      ps.close(); 
      conn.close(); 
     } 

    } 
    //!!!! http://stackoverflow.com/questions/11135675/unparseable-date-30-jun-12 
    // Convert the Date format 

    public Date toDate(String s) 
    { 
     Date d = null; 
     if (s == null || s.trim().isEmpty()) 
     { 
      return d; 
     } 

     try 
     { 
      d = Date.valueOf(s); 
     } 
     catch (Exception x) 
     { 
      x.printStackTrace(); 
     } 

     return d; 
    } 
} 

我試圖讓使用該Java代碼的元素:

ps.setInt(1, dataList.get(userid)); 
ps.setInt(2, dataList.get(groupid)); 
ps.setString(3, dataList.get(specialnumber)); 
ps.setString(4, dataList.get(username)); 
ps.setString(5, passwdConvert(dataList.get(passwd))); 
ps.setDate(6, toDate(dataList.get(datetochangepasswd))); 
ps.setString(7, dataList.get(address)); 
ps.setString(8, dataList.get(stateregion)); 
ps.setString(9, dataList.get(country)); 
ps.setString(10, dataList.get(userstatus)); 
ps.setString(11, dataList.get(telephone)); 
ps.setDate(12, toDate(dataList.get(dateuseradded))); 
ps.setDate(13, toDate(dataList.get(userexpiredate))); 
ps.setDate(14, toDate(dataList.get(dateuserlocked))); 
ps.setString(15, dataList.get(city)); 
ps.setString(16, dataList.get(email)); 
ps.setString(17, dataList.get(description)); 

但我在Netbeans中出現錯誤。你能告訴我什麼是從ArrayList中獲取元素的正確方法嗎?

祝福

+0

誰說Java是冗長的? – Tom 2012-07-27 15:31:41

+4

誰說這是使用Java的好方法? – 2012-07-27 15:32:43

+0

我是Java新手。你能向我解釋問題在哪裏,我該如何解決? – user1285928 2012-07-27 15:33:25

回答

9

使用for-each loop this is optimize way...

for(userdata obj : dataList){ 

    System.out.println("User ID :: " + obj.userid); 
    System.out.println("Group ID :: " + obj.groupid); 
    . 
    . 
    . 

} 

使用for循環

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

     userdate obj=datalist.get(i); 
     System.out.println("User ID :: " + obj.userid); 
     System.out.println("Group ID :: " + obj.groupid); 
     . 
     . 
     . 

    } 
+0

我只是使用getter方法添加,因爲取決於他在列表中迭代的位置,它可能無法按照您的方式工作。 – 2012-07-27 15:35:47

5
ArrayList<userdata> dataList = new ArrayList<>(); 
dataList.add(new userdata(...)); // The ... is for all your params 
userdata data = dataList.get(0); // This gets the first element of the list, the one we just added 
System.out.println(data.getCity()); // This will print the String called city 

一個側面說明,用戶數據應的UserData,它是一個Java約定爲您定義的任何類的第一個字母使用大寫字母。

編輯:

我看你是想現在做什麼,你想改變你的插入更類似如下:

for (userdata data : dataList) { 
    ps.setInt(1, data.getUserid()); 
    ps.setInt(2, data.getGroupid()); 
    ... 
} 

你也將需要進行新的刀片項目和舊項目的更新。

3
ps.setInt(1, dataList.get(i).getUserId()); 
2

您的對象dataList包含userData類型的對象(順便說一句,應該是UserData)。

當您撥打dataList.get(something)時,應該是一個整數值,並且get方法檢索該位置處的對象。

如果要填補的PreparedStatement在列表中的第一個對象,你會做的是:

UserData user = dataList.get(0); 
ps.setInt(1, user.getUserId()) 
... 

如果你想爲每個用戶做同樣的:

for(userdata obj : dataList){ 

    ps.setInt(1, obj.userid); 
    ... 

    //do something with PS for this object. 
} 
2

試試這個

for(userdata datum : dataList) 
{ //for each userdata instance in dataList collection 
      ps.setInt(1, datum.userid); //ps.setInt(1, datum.getUserid()); 
      ps.setInt(2, datum.groupid); 
      ps.setString(3, datum.specialnumber); 
      //... you get the idea 
} 

基本上,你需要使用dataLi從列表中獲得你的userdata項目st.get(index),然後從userdata的實例中取出你的字段。

還挺喜歡這個

for(int i = 0; i < dataList.size(); i++) 
{ 
      ps.setInt(1, dataList.get(i).getUserid()); //ps.setInt(1, datum.getUserid()); 
      ps.setInt(2, dataList.get(i).getGroupId()); 
      ps.setString(3, dataList.get(i).specialnumber); 
      //... you get the idea 
} 
2

如果你想在你列出你的每個項目,需要循環和indidually執行這些更新每一個項目。

public void saveData() throws SQLException, java.text.ParseException, NoSuchAlgorithmException { 
    String SqlStatement = null; 
    if (ds == null) { 
     throw new SQLException(); 
    } 

    Connection conn = ds.getConnection(); 
    if (conn == null) { 
     throw new SQLException(); 
    } 

    PreparedStatement ps = null; 
    try { 
     conn.setAutoCommit(false); 
     boolean committed = false; 
      //removed the userid as that is used in the where to determine what record to update 
      //so it will be the same 
      SqlStatement = "UPDATE USERS " 
        + "SET " 
        + "GROUPID = ?, " 
        + "SPECIALNUMBER = ?, " 
        + "USERNAME = ?, " 
        + "PASSWD = ?, " 
        + "DATETOCHANGEPASSWD = ?, " 
        + "ADDRESS = ?, " 
        + "STATEREGION = ?, " 
        + "COUNTRY = ?, " 
        + "USERSTATUS = ?, " 
        + "TELEPHONE = ?, " 
        + "DATEUSERADDED = ?, " 
        + "USEREXPIREDATE = ?, " 
        + "DATEUSERLOCKED = ?, " 
        + "CITY = ?, " 
        + "EMAIL = ?, " 
        + "DESCRIPTION = ? " 
        + "WHERE USERID = " + ?; //also changed this to be a parameter 

      ps = conn.prepareStatement(SqlStatement); 

      for (userdata data: datalist) { 
       ps.setInt(1, dataList.getGroupid()); 
       ps.setString(2, dataList.getSpecialnumber()); 
       ... 
       //continue setting the others variables 
       //the last on will be the userid in the where clause 
       ps.setInt(17, dataList.getUserId()); 
       //execute the update 
       ps.executeUpdate(); 
      } 
      //now we commit since they have all ran. We want an all or nothing update 
      //meaning if one fails, nothing is updated 
      conn.commit(); 
      committed = true; 

    } 
    finally 
    { 
     if (!committed){ 
      conn.rollback(); 
     } 
     ps.close(); 
     conn.close(); 
    } 

} 

我也鞏固了最後的塊,因爲沒有理由在這種情況下有兩個。