我正在使用 JSP、JSTL、Servlets 和 JavaBeans 编写一个网站。
在我的代码的某个时刻,我试图使用对象的 ArrayList,并且发生了一件奇怪的事情:当我添加第一个对象时它很好,当我添加第二个对象时它在第二个位置添加它,但是index(0) 处的对象与 index(1) 处的对象获得相同的值。
也许问题出在
ArrayList<Article> articleList = new ArrayList<Article>();
Article newArticle = new Article();
由于 articleList 是 Article 类的 ArrayList。
有人可以指出我做错了什么吗?
下面是我的代码:
public ArrayList<Article> getArticles()
{
baseIO mySql = new baseIO();
ArrayList<Article> articleList = new ArrayList<Article>();
int articleId = 0;
try
{
String sql =
"select * from jsp_blog_article order by article_id Desc Limit 3";
con = (Connection)mySql.getConnection();
pstmt = (PreparedStatement) con.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
Article newArticle = new Article();
newArticle.setArticleAuthor(rs.getString("article_name"));
newArticle.setArticleBody(rs.getString("article_body"));
newArticle.setArticleAuthor(rs.getString("article_author"));
newArticle.setArticleDate(rs.getString("article_date"));
articleId = Integer.parseInt(rs.getString("article_id"));
newArticle.setArticleId(String.valueOf(articleId));
newArticle.setArticleComments(this.getCommentsNum(articleId));
articleList.add(newArticle);
}
con.close();
pstmt.close();
}
catch(Exception e)
{
return null;
}
return articleList;
}
和文章类
package objects;
import java.io.Serializable;
public class Article implements Serializable{
private String articleName;
private String articleBody;
private String articleAuthor;
private String articleComments;
private String articleDate;
private String articleId;
public Article()
{
}
// all the getters and setters in place, but it is too long
// so i am not going to post them in forum
}