JSP, JSTL, Servlets 및 JavaBeans를 사용하여 웹 사이트를 작성하고 있습니다.ArrayList의 이상한 동작
내 코드의 한 지점에서 객체의 ArrayList를 사용하려고하는데 이상한 일이 일어났습니다. 첫 번째 객체를 추가하면 두 번째 객체를 추가 할 때 객체가 추가됩니다. 두 번째 자리에 있지만 인덱스 (0)의 객체는 인덱스 (1)의 객체와 동일한 값을 가져옵니다. articleList이 제 클래스의 ArrayList를이기 때문에
은 어쩌면 문제는
ArrayList<Article> articleList = new ArrayList<Article>();
Article newArticle = new Article();
입니다.
누군가 내가 잘못하고있는 것을 지적 할 수 있습니까? 다음은
내 코드입니다 :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
}
먼저 articleId를 구문 분석 한 다음 즉시 다시 문자열로 변환해야하는 특별한 이유가 있습니까? –
getArticles() 메서드를 복사하여 붙여 넣거나 실제 코드가 약간 다릅니 까? 코드와 Soldier.moth의 코드간에 기능상의 차이가 없어야하기 때문입니다. 그는 매번 새로운 Article 객체를 생성합니다. –
사실 내 코드가 왜 돌아 가지 않았는지 모르겠다. –