Results 1 to 3 of 3
  1. #1
    soichi is offline Member
    Join Date
    Jan 2011
    Posts
    14
    Rep Power
    0

    Default contents of List<object> array changed?

    Hi, I am trying to develop a servlet that parses Google Calendar XML data.
    Getting XML and parsing is OK, but when it comes to storing the data to Array, which is "List<GCalendar>gcalendar", a funny thing happens.

    In the code below, at "//★★★★★HERE!!!" the data is to be stored in the array defined in the servlet. And at "//★★★★★AGAIN HERE!!!", three lines below, all the entries of the array become the same!, which is the last element inserted in to it. In the "for" loop, the separate elements are certainly inserted into the array. Once it gets out of the loop, they all become identical. I do not understand why.

    Could anyone help me out?

    soichi

    P.S. the code follows.

    Java Code:
    public class GetCalendarServlet extends HttpServlet {
    	private static String key = "CALENDAR";
    	String strurl = "http://www.google.com/calendar/feeds/***";
    	
    	Date date;
    	String html;
    	String time;
    	String youbi;
    	String naiyou;
    	GCalendar addlist = new GCalendar(date, youbi, time, naiyou);
    	GCalendar addHTML = new GCalendar(html);
    	List<GCalendar>gcalendar = new ArrayList<GCalendar>();
    	private static final String head =     
            "<html>\n" 
          + "<body>\n"
          + " <span style=\"font-size: 200%\">RainbowCalendar</span>\n"
          + "<div id=\"list\">\n"
          + "</div>";
    	private static final String memoTmpl = 
    	        "  <div>\n"
    	      + "    <span class=\"date\">  {0} {1}</span> \n"
    	      + "    <pre>{2}</pre> \n"
    	      + "    <pre>{3}</pre> \n"
    	      + "  </div> \n";
    	private static final String tail =      
    		"  </body> \n" + "</html>\n";
    	public void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws IOException {
    
    		GetCalendarServlet();
            resp.setContentType("text/html");
            resp.setCharacterEncoding("utf-8");
            resp.getWriter().print(htmlGenerate());
    		//resp.sendRedirect("/");
    	}
    	public String renderPart(Date d, String y, String t, String n) {
    		StringBuffer sb = new StringBuffer();
    		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
    		String tmp = sdf.format(d);
    		sb.append(MessageFormat.format(memoTmpl,tmp,y,t,n));
    		return sb.toString();
    	}
    
    	public void GetCalendarServlet(){
    		
    		try {
    			
    			URL url = new URL(strurl);
    			InputStream in = url.openStream();
    			 
    			DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); 
    			DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
    			
    			Document doc = docBuilder.parse (in);
    			doc.getDocumentElement().normalize();
    			NodeList nodeLst = doc.getElementsByTagName("entry");
    						
    			for (int s = 0; s < nodeLst.getLength(); s++) {
    
    				Node fstNode = nodeLst.item(s);
    				
    				if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
    				  
    					Element fstElmnt = (Element) fstNode;
    					NodeList fstTlElmntLst = fstElmnt.getElementsByTagName("title");
    					Element fstTlElmnt = (Element) fstTlElmntLst.item(0);
    					NodeList title = fstTlElmnt.getChildNodes();
    					
    					NodeList lstSumElmntLst = fstElmnt.getElementsByTagName("content");
    					Element lstSumElmnt = (Element) lstSumElmntLst.item(0);
    					NodeList sum = lstSumElmnt.getChildNodes();
    					String summary = ((Node) sum.item(0)).getNodeValue();
    					
    					String date_exp = "[0-9]{4}/[01]?[0-9]/[0123]?[0-9]";
    					Pattern pd = Pattern.compile(date_exp);
    					String youbi_exp = "\\([月|火|水|木|金|土|日]\\)";
    					Pattern py = Pattern.compile(youbi_exp);
    					String time_exp = "([0-9]|([0-1][0-9]|[2][0-3]))[:][0-5][0-9]";
    					Pattern pt = Pattern.compile(time_exp);
    										
    					Matcher md = pd.matcher(summary);
    					Matcher mt = pt.matcher(summary);
    					Matcher my = py.matcher(summary);
    					
    					SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
    					if (md.find()) {
    						try {
    							date = sdf.parse(md.group());
    							addlist.setDate(date);
    						} catch (ParseException e) {
    							// TODO Auto-generated catch block
    							e.printStackTrace();
    						}
    					}
    					if (my.find()){
    						youbi = my.group();
    						addlist.setYoubi(youbi);
    					}
    					int count = 0;
    					String tmp = "";
    					while (mt.find()) {
    						//creates "10:00~12:30" like expression
    						tmp = tmp + mt.group(0);
    						if (count == 0) tmp = tmp + ("〜");
    						++count;
    					}
    					time = tmp;
    					addlist.setTime(time);
    					naiyou = ((Node) title.item(0)).getNodeValue();
    					addlist.setNaiyou(naiyou);
    				}
    				gcalendar.add(addlist);	//★★★★★HERE!!!			
    			}
    			in.close();
                            //★★★★★AGAIN HERE!!!
                            System.out.println("gcalendar.get(7).getDate()");
    		}
    		StringBuffer sbTotal = new StringBuffer();
    		sbTotal.append(head);
    		for (int i = 0; i < gcalendar.size(); i++){
    			sbTotal.append(renderPart(gcalendar.get(i).getDate(),
    					gcalendar.get(i).getYoubi(), gcalendar.get(i).getTime(),
    					gcalendar.get(i).getNaiyou()));
    		}
    		sbTotal.append(tail);
    		addHTML.setHtml(sbTotal.toString());
    	}
    	private String htmlGenerate(){
    		System.out.println(addHTML.getHtml());
    		return null;
    	}
    }

  2. #2
    masijade is offline Senior Member
    Join Date
    Jun 2008
    Posts
    2,571
    Rep Power
    8

    Default

    Because you are setting all of the elements to the same Object reference. You do know that when you change the object that a reference references, that all references to that object see those same changes (since they all reference the same object), right? You also know that calling add in a list does not create a copy of the object added, right? It simply adds a reference to the object in the list, right? So calling add(object) multiple times using the same object reference, obviously, makes all the elements in the list the same, and all will have the same value, nemaely the last values set in the object.

    Either add a clone to the list (if the object is clonable) or define a new object each time, rather than using the same one again and again.

  3. #3
    soichi is offline Member
    Join Date
    Jan 2011
    Posts
    14
    Rep Power
    0

    Default

    It was simple... Why did I not see that?
    Thanks for your help. I moved the declaration of the class, and it worked as I wished.

    Thanks again.

Similar Threads

  1. Replies: 2
    Last Post: 09-06-2010, 01:03 AM
  2. Scanning text file and inserting contents into array
    By jmwalloh in forum New To Java
    Replies: 8
    Last Post: 03-24-2010, 12:33 PM
  3. Concatinating contents of a string array based on condition
    By gangsterooseven in forum Advanced Java
    Replies: 2
    Last Post: 10-07-2009, 07:35 AM
  4. Printing the contents of an array of objects
    By Mr.Paplu in forum New To Java
    Replies: 1
    Last Post: 03-19-2009, 04:49 PM
  5. how to remove an object from the array list
    By cecily in forum New To Java
    Replies: 3
    Last Post: 08-02-2007, 02:26 PM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •