Getting an Object out of ArrayList
Hello, I have a question about getting an Object out of an ArrayList. I have an object that's made up of four fields: name, average, total and position. Now, I need to read in values from a formatted text file, and stick those values into an array (the values correspond to the Object values), but since there's a variable number of items in the text file, I figured I could just use an ArrayList to store the objects, and when it's finished looping through the file, just copy the ArrayList items into my object. I have it working fine, except I can't seem to get the data in the ArrayList copied over to the array.
I guess my question is simple: how can I copy over the ArrayList of objects into my object?
Thanks very much for any help! :)
Thanks a lot, I got it! After spending two hours on this problem, two lines of code fixed it for me. :P
@Petes1234: Well basically because the data that's being read can have a variable length, I wanted to use an ArrayList to hold it temporarily. After it's done reading I have the size, so I guess that I wanted to extract the object data into a regular array so that it can be formatted and displayed to the user.
Message was edited by:
mistah-java
Similar Messages
-
Why can't get the object "out" in this way?
We use "PrintWriter out=response.getWriter()"to get a "out" object in Servlet and output text to webbrowser with it.But I think the PrintWriter is a class and Why can't I get the object "out" use this way:"PrintWriter out=new PrintWriter()"?I think the later is easier to understand.Anyone can help me?
I check the Servlet API.The PrintWriter has a constructor with a abstract object Writer as it's parameter.I couldn't create the Writer object so I can't create the out object.Why it's constructor is protected by java?
-
Hi I have this code, below, The set methods in the class Website work just fine to get the data into the arraylist, but i just can't figure out the get methods to get the objects back out to compare. Could someone please help. i'm almost finished with this thing!!
Iterator itr1 = Websites1.iterator();
Iterator itr2 = Websites2.iterator();
outer: while (itr1.hasNext()) {
while (itr2.hasNext()) {
//Object site1 = new Object ();
//Object site2 = new Object ();
Object site1 = (Website)itr1.next();
content1 = site1.getCon();
date1 = site1.getMod();
Object site2 = (Website)itr2.next();
content2 = site2.getCon();
date2 = site2.getMod();
if (date1 != date2 ) {
if (content1 != content2)
alert.play();
//do other stuff//
else;
else;
continue outer;
class Website {
public String WebsiteName, WebsiteContent, Content;
public Date LastModified, Modified;
public Website() {
WebsiteName = "";
WebsiteContent = "";
LastModified = null;
public Website (String Name, String Content, Date Modified) {
WebsiteName = Name;
WebsiteContent = Content;
LastModified = Modified;
public void setName(String Name) {
WebsiteName = Name;
public void setContent(String Content) {
WebsiteContent = Content;
public void setModified(Date Modified) {
LastModified = Modified;
public String getCon() {
Content = WebsiteContent;
public Date getMod() {
Modified = LastModified;I think that worked (duh i should have noticed it earlier), but now i'm getting a real weird error when i try to compile on my custom get methods
missing return statement
public String getCon() {//(points to this)
and the same thing on the public Date getMod() method
any ideas?
I'm lost now i've never seen that before -
Getting items out of arrayList
Hi everyone
I have the following scenario:
Have two java class files which gets used to extract data from database and a jsp which display data.
I get the data out of the database, but my problem is displaying it correctly using the jsp which uses JSTL.
The ContactsData.class file extracts the data out of the database and puts it in the Contacts.class class which then gets written to an arraylist which stores the Contacts.class and then returns the ArrayList to the requester.
Here is the code, can someone please help me to manipulate the arraylist to display the right info.
Contacts.class which holds the contacts.
package contacts;
import java.io.Serializable;
import java.util.*;
public class Contacts implements Serializable
//String varialbes to store the details about the contact
private String contactName,company, workNumber, cellNumber, faxNumber, email,country;
//contacts constructor
public Contacts()
//method to set the company
public void setCompany(String company)
this.company = company;
//method to set the Contact name
public void setContactName(String contactName)
this.contactName = contactName;
//method to set the work teletphone number
public void setWorkNumber(String workNumber)
this.workNumber = workNumber;
//method to set the cellphone number
public void setCellNumber(String cellNumber)
this.cellNumber = cellNumber;
//method to set the fax number
public void setFaxNumber(String faxNumber)
this.faxNumber = faxNumber;
//method to set the email
public void setEmail(String email)
this.email = email;
//method to set the country
public void setCountry(String country)
this.country = country;
//method to get the company
public String getCompany()
return company;
//method to get the contact name
public String getContactName()
return contactName;
//method to get the work telephone number
public String getWorkNumber()
return workNumber;
//method to get the cellphone number
public String getCellNumber()
return cellNumber;
//method to get the fax number
public String getFaxNumber()
return faxNumber;
//method to get the email
public String getEmail()
return email;
//method to get the country
public String getCountry()
return country;
}piece of the contactsData.class class which retrieves the data out of the database and stores it in Contacts.class class and then store the Contacts class in the arrayList which gets returned to the requester.
public ArrayList getContactList()
//arrayList to hold the contacts
contactList = new ArrayList<Contacts>();
try
ResultSet rs = stmt.executeQuery("SELECT * FROM Contacts"); //selecting from the database
while(rs.next())
//creating contacts object
contact = new Contacts();
//adding details to the Contacts object
contact.setContactName(rs.getString(1));
contact.setCompany(rs.getString(2));
contact.setWorkNumber(rs.getString(3));
contact.setCellNumber(rs.getString(4));
contact.setFaxNumber(rs.getString(5));
contact.setEmail(rs.getString(6));
contact.setCountry(rs.getString(7));
//adding Contacts object to the Arraylist
contactList.add(contact);
catch(SQLException se)
System.out.println("Could not retrieve contacts");
return contactList; //returning the arraylist
}The jsp that need to display the contacts within the arraylist, which I don't get right.
<?xml version="1.0"?>
<%@ page import="contacts.Contacts"%>
<%@ page import="java.util.*"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<jsp:useBean id = "contactsData" scope = "page" class ="contacts.ContactsData"/>
<html>
<head>
<title>Contact List</title>
<meta http-equiv="cache-control" content="max-age=0, must-revalidate, no-cache, no-store, private">
<meta http-equiv="expires" content="-1">
<meta http-equiv="pragma" content="no-cache">
<script language=JavaScript>
<!--
function clicked(clickedValue)
if(clickedValue == "add")
window.location = "AddContact.jsp";
-->
</script>
</head>
<body>
<h1>Contacts</h1>
<form>
<table cellpadding="5">
<c:forEach var="contacts" items="${contactsData.contactList}"> //getting the list from the ContactData class
<tr>
<td><input type="radio" name="deleteContact" value="${contacts.company}"></td> //want to display the company name from the contacts
</tr>
</c:forEach>
</table>
<br>
<input type="button" value="Add" onClick="clicked('add')"/>
<input type="submit" value="Delete" onClick="clicked('del')"/>
</form>
</body>
</html>HI, we need to specify the scope we used,In my Ex its request
so my forEach tag ..
<c:forEach var="stud" items="${requestScope.studli}">
<c:out value="${stud.SID}"></c:out>
<c:out value="${stud.SNAME}"></c:out>
</c:forEach> -
Get Object[] length in ArrayList
How do I get the size of the Object[] in ArrayList?
Not ArrayList.size() which returns how many Elements
are in the List.You could use reflection if you really wanted to know
how much memory you have "wasted".
KajHere's a stupid class to do just that.
Thanks.
import java.util.*;
import java.lang.reflect.*;
public class Test{
public static void main(String[] args){
new Test();
public Test(){
List list = new ArrayList(1);
double capacity = 0;
double size = 0;
Random rand = new Random();
int iter = rand.nextInt(100);
System.out.println("Iter: " + iter);
for(int i = 0; i < iter; i++){
int rn = rand.nextInt(10);
Integer integer = new Integer(rn);
list.add(integer);
size = list.size();
System.out.println("List Size: " + size);
try{
Class al = list.getClass();
// Get Declared Fields
System.out.println("\nGet Declared Fields");
Field[] fields1 = al.getDeclaredFields();
for(int i = 0; i < fields1.length; i++){
System.out.println("Field: " + fields1.getName());
// Get Fields
System.out.println("\nGet Fields");
Field[] fields2 = al.getFields();
for(int i = 0; i < fields2.length; i++){
System.out.println("Field: " + fields2[i].getName());
// Get Field
System.out.println("\nGet Field");
//Field field = al.getField("elementData");
Field field = fields1[1];
field.setAccessible(true);
System.out.println("Field (elementData): " + field.getName());
Object obj = field.get(list);
Object[] elementData = (Object[])obj;
capacity = elementData.length;
} catch(Exception e){
e.printStackTrace();
System.out.println("List Capacity: " + capacity);
int percentOver = (int)(((capacity - size) / capacity) * 100);
System.out.println("Percent Over: " + percentOver); -
How to get the intersection of two arraylist containing user defined obj??
How to get the intersection of two arraylist containing user defined obj??
I can easily get the intersection of two array list which containing some simple class(Integer, String). But how to get the intersection of two arrayList which contain user defined object?
Here is the sample code..I can not run this out...anybody can help me? thank you very much..
The correct result should be like this:
2
2
but I can only get this:
2
0
import java.util.*;
public class testRetain{
public static void main(String[] args){
ArrayList a = new ArrayList();
ArrayList b = new ArrayList();
a.add( new dog(1,2,2) );
a.add( new dog(1,2,1) );
System.out.println(a.size() );
b.add( new dog(1,2,2) );
a.retainAll(b);
System.out.println(a.size() );
class dog implements Comparable{
int head;
int arms;
int legs;
dog(int head, int arms, int legs){
this.head = head;
this.arms = arms;
this.legs = legs;
public int compareTo(Object o){
if ( ((dog)o).head > this.head )
return -1;
else if ( ((dog)o).head < this.head )
return 1;
else
return 0;
}@Op. Your classes should override equals and hashCode
Kaj -
Getting an object from HttpSession...
Hi all,
I am stuck which is according to me is very obvious...please correct me if I am wrong.
I have a java.util.ArrayList object in my HttpSession object.
Now in my helper class to which the request is passed from the servlet I am extracting this ArrayList object in one ArrayList object and putting it into the HashMap. After this, I am again extracting this ArrayList object from the HttpSession and assigning it to a newly created ArrayList object in my helper class. Now I am passing this newly created ArrayList object to a method. This method after processing changes this ArrayList object. And finally I am putting this changed ArrayList object in the HashMap I created earlier.
After doing all this, when I am trying to extract and print these ArrayList Objects from the session object...I found my first ArrayList object has also been affected by the same change as the second one. The expected result was only the second object will be changed. I am stuck with this.
I know it has something to do with references....but I am not able to understand that when I am trying to create two new copies by extracting an object from the Session...and changing one how is my second object getting affected. Any help will be appriciated.
The code for this is as follows:
"phSessionState" is a collection object in HttpSession which holds all the other objects. We are not putting different objects directly in the HttpSession.
"LineObject" is a simple JavaBean kind of class with gettrs and setters
ArrayList originalList = (ArrayList)phSessionState.getData("lineObjectList");
HashMap stagedLineObjects = new HashMap();
stagedLineObjects.put("OriginalList", originalList);
//Extracting same in another object and calling a method to update it.
ArrayList tempList = (ArrayList)phSessionState.getData("lineObjectList");
//Method to update the ArrayList
updateLineObjectList(tempList, request);
stagedLineObjects.put("UpdatedList", tempList);
//Trying to get the objects from the HashMap and print
System.out.println("Retriving OriginalList...");
ArrayList List1 = (ArrayList)stagedLineObjects.get("OriginalList");
for(int i=0; i<List1.size(); i++)
LineObject lo = (LineObject)List1.get(i);
System.out.println(lo.getUserID() + "\t" + lo.getPassword()
+ "\t" + lo.getFirstName() + "\t" + lo.getMiddleName() + "\t" +
lo.getLastName());
System.out.println("Retriving UpdatedList...");
ArrayList List2 = (ArrayList)stagedLineObjects.get("UpdatedList");
for(int i=0; i<List2.size(); i++)
LineObject lo = (LineObject)List2.get(i);
System.out.println(lo.getUserID() + "\t" + lo.getPassword()
+ "\t" + lo.getFirstName() + "\t" + lo.getMiddleName() + "\t" +
lo.getLastName());
Waiting for your valuable help...
Thanks & Regards,
GauzYou must remember that objects are passed by reference. So when you are passing around your ArrayList, you are actually passing a reference to the ArrayList. In other words, there exists one instance of your specific ArrayList in memory and what you are passing around are copies of the "reference" to that memory location.
If you want to pass a copy of your ArrayList, you can create a copy of the ArrayList and pass the reference to that new copy. One way to do this is as follows:ArrayList originalList = new ArrayList();
//Let's put two objects into the ArrayList
originalList.add(1, new StringBuffer("object1"));
originalList.add(2, new StringBuffer("object2"));
//Now let's copy the ArrayList
ArrayList copyOfList = new ArrayList(originalList);
//now, you have two copies of the ArrayList. You can make
//changes to copyOfList without affecting originalList
copyOfList.add(3, new StringBuffer("object3"));
//Checking the size of each ArrayList will demonstrate a difference
System.out.println("Original's size is " + originalList.size());
System.out.println("Copy's size is " + copyOfList.size());
//Output should be:
// Original's size is 2
// Copy's size is 3Please keep in mind that the objects within the ArrayList are also being passed by reference. So if you modify an object within originalList, those modifications will be reflected in the same object found in copyOfList.
For example,StringBuffer sb = (StringBuffer)copyOfList.get(1);
sb.append(":modified");
//Now print the values of the first object in each ArrayList
StringBuffer sbFromOriginal = (StringBuffer)originalList.get(1);
StringBuffer sbFromCopy = (StringBuffer)copyOfList.get(1);
System.out.println("Original's value is " + sbFromOriginal.toString());
System.out.println("Copy's value is " + sbFromCopy.toString());
//Your output should read
// Original's value is object1:modified
// Copy's value is object1:modifiedThis is because you made a copy of the ArrayList, but not a copy of each object within the ArrayList. So you actually have two seperate copies of ArrayList but they are referencing the same two objects in positions 1 and 2. The object in position 3 exists only in copyOfList.
Hope this helps. -
How to get record which store in arraylist?
Hi all ,
I want to get the out put from arraylist, but just don't how to deal with it.
method 1
List data = new ArrayList();
String[] checked = request.getParameterValues("mybox");
for(int i=0; i<checked.length;i++){
String select=checked;
String Sql=" select NewNum, Name, Length, Segment, Sequence";
Sql+=" from Sec04";
Sql+=" where NewNum=?";
Sql+=" union";
Sql+=" select NewNum, Name, Segment, Sequence";
Sql+=" from Sec00";
Sql+=" where NewNum=?";
Sql+=" union";
Sql+=" select NewNum, Name, Segment, Sequence";
Sql+=" from Sec03";
Sql+=" where NewNum=?";
Sql+=" union";
Sql+=" select NewNum, Name, Segment, Sequence";
Sql+=" from Sec02";
Sql+=" where NewNum=?";
Sql+=" union";
Sql+=" select NewNum, Name, Segment, Sequence";
Sql+=" from Sec01";
Sql+=" where NewNum=?";
Sql+=" union";
Sql+=" select NewNum, Name, Segment, Sequence";
Sql+=" from Sec05";
Sql+=" where NewNum=?";
Sql+=" union";
Sql+=" select NewNum, Name, Segment, Sequence";
Sql+=" from Secold";
Sql+=" where NewNum=?";
//clear any values from request object
ps.clearParameters();
// set paramenter from request object
ps.setString(1, select);
rs = ps.executeQuery (Sql);
MyDataBean mydata = new MyDataBean();
while(rs.next()) {
mydata.setName(rs.getString("Name"));
mydata.setSegment(rs.getString("Segment"));
mydata.setSequence(rs.getString("sequence"));
data.add(mydata);
}//end for
for(int j=0; j<data.size();j++)
data.get(j);
System.out.println(">");
System.out.println(mydata.getName());
System.out.println(mydata.getSegment());
System.out.println(mydata.getSequence());
List nameList = new ArrayList();
List sequencList =new ArrayList();
String[] checked = request.getParameterValues("mybox");
for(int i=0; i<checked.length;i++){
String select=checked;
String Sql=" select NewNum, Name, Length, Segment, Sequence";
Sql+=" from Sec04";
Sql+=" where NewNum='"+select+"'";
Sql+=" union";
Sql+=" select NewNum, Name, Segment, Sequence";
Sql+=" from Sec00";
Sql+=" where NewNum='"+select+"'";
Sql+=" union";
Sql+=" select NewNum, Name, Segment, Sequence";
Sql+=" from Sec03";
Sql+=" where NewNum='"+select+"'";
Sql+=" union";
Sql+=" select NewNum, Name, Segment, Sequence";
Sql+=" from Sec02";
Sql+=" where NewNum='"+select+"'";
Sql+=" union";
Sql+=" select NewNum, Name, Segment, Sequence";
Sql+=" from Sec01";
Sql+=" where NewNum='"+select+"'";
Sql+=" union";
Sql+=" select NewNum, Name, Segment, Sequence";
Sql+=" from Sec05";
Sql+=" where NewNum='"+select+"'";
Sql+=" union";
Sql+=" select NewNum, Name, Segment, Sequence";
Sql+=" from Secold";
Sql+=" where NewNum='"+select+"'";
rs = ps.executeQuery (Sql);
int rowCount=0;
while(rs.next()) {
nameList.add(rs.getString("Name"));
sequenceList.add(rs.getString("Segment"));
rowCount++;
for(int j=0; j<rowCount; j++){
nameList.get(j);
sequenceList.get(j);
out.println(">");
any hit?
Thank youHi munyul,
still get empty display. I post all my code, how can find what is wrong.
I still not sure, want the select is a group of value, how to deal with search, I put then in loop , but still fell not sure, I did some basic search, did not got the result yet.
my bean
public class MyDataBean implements java.io.Serializable {
private String name;
private String sequence;
/* Constructor*/
public MyDataBean() {
name =null;
sequence=null;
public String getName() {
return name;
public void setName(String name) {
this.name = name;
public String getSequence() {
return sequence;
public void setSequence(String sequence) {
this.sequence = sequence;
import java.util.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import javax.sql.*;
import Sec.MyDataBean;
* TryJdbc.java
* This servlet demonstrates using JDBC
public class Formate1 extends HttpServlet {
ResultSet rs = null;
PreparedStatement ps = null;
Connection conn =null;
OutputStream outStream = null;
* We want to initialized the JDBC connections here
public void init()
try{
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
catch( Exception e )
e.printStackTrace();
public void doGet(
HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
}// end of DoGet
* This responds to an HTTP GET request.
public void doPost(
HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
try {
conn = DriverManager.getConnection("jdbc:microsoft:sqlserver://localhost:1433","A#$","RE@89");
conn.setCatalog("sequences");
List data = new ArrayList();
String[] checked = request.getParameterValues("mybox");
for(int i=0; i<checked.length;i++){
String select=checked;
ps=conn.prepareStatement(" select NewNum, Name, Length, Segment, Sequence" +
" from Sec04" +
" where NewNum= ?" +
" union" +
" select NewNum, Name, Segment, Sequence" +
" from Sec00" +
" where NewNum= ?" +
" union" +
" select NewNum, Name, Segment, Sequence" +
" from Sec03" +
" where NewNum= ?" +
" union" +
" select NewNum, Name, Segment, Sequence" +
" from Sec02" +
" where NewNum= ?"+
" union" +
" select NewNum, Name, Segment, Sequence" +
" from Sec01" +
" where NewNum= ?" +
" union" +
" select NewNum, Name, Segment, Sequence" +
" from Sec05" +
" where NewNum= ?" +
" union" +
" select NewNum, Name, Segment, Sequence" +
" from Secold" +
" where NewNum= ? " );
//clear any values from request object
ps.clearParameters();
// set paramenter from request object
ps.setString(1, select);
rs = ps.executeQuery ();
while(rs.next()) {
MyDataBean mydata = new MyDataBean();
mydata.setName(rs.getString("Name"));
mydata.setSequence(rs.getString("sequence"));
data.add(mydata);
}//end for
MyDataBean mdb;
for ( int j = 0; j < data.size(); j++ )
mdb = (MyDataBean)data.get(j);
System.out.print("> ");
System.out.print(mdb.getName());
System.out.print(", ");
System.out.print(mdb.getSequence());
System.out.println();
}catch(SQLException e) {
finally {
try {
if(rs != null)
rs.close();
rs = null;
if (ps != null)
ps.close();
ps = null;
if(conn != null)
conn.close();
conn = null;
catch (SQLException e) {}
public String getServletInfo()
return "A Simple Servlet"; -
How to create and object from an arrayList
Hi I want to create an object from an arrayList.
here is my code...
BillingQueryParam billingQueryParam = new BillingQueryParam();
/*This BillingQueryParam and billingItemManagerActionForm has getter and setter method for following attributes.
private int billingItemId;
private String[] paramName;
private String[] defaultParamValue;
List billingQueryParamList = new ArrayList();
for(int i = 0; i < billingItemManagerActionForm.getParamName().length; i++) {
billingQueryParam.setParamName(billingItemManagerActionForm.getParamName());
for(int i = 0; i < billingItemManagerActionForm.getDefaultParamValue().length; i++) {
billingQueryParam.setDefaultParamValue(billingItemManagerActionForm.getDefaultParamValue());
billingQueryParam.setBillingItemId(billingItem.getBillingItemId());
billingQueryParamList.add(billingQueryParam);
System.out.println("****** ArrayList Size-->"+billingQueryParamList.size());
for (Iterator iter = billingQueryParamList.iterator();iter.hasNext();) {
billingQueryParam = (BillingQueryParam)iter.next();
System.out.println("****** BillingItemId-->"+billingQueryParam.getBillingItemId());
System.out.println("****** Param Name-->"+billingQueryParam.getParamName()); //printing an array of paramName
System.out.println("****** Default param value-->"+billingQueryParam.getDefaultParamValue());
}Here after iterating this list I want to create an object of billingQueryParam which contains a single value of itemId, paramName,paramTypeId and defaultParamName and I want to persist this object in database.
Please help...!!!
ThanksNow this is too much.. Do i need to tell this thing to u as well. How did u come to this forum?
Can't u see link to Java programming forum at the top. -
How to get Request object and LDAP user
Hi All,
How to get Request object, coz i want to see the out put of this code
IUser myUser = request.getUser();
String uid=myUser.getUid();
I want to get only LDAP user from the server, for that i am having code but i think this code is returning me all user from the server.
com.sap.security.api.IUser user = null;
try {
IUserFactory userFactory = UMFactory.getUserFactory();
IUserSearchFilter searchFilter = userFactory.getUserSearchFilter();
ISearchResult searchResult = userFactory.searchUsers(searchFilter);
int count = 0;
List list = new ArrayList();
while (searchResult.hasNext()) {
count++;
String uniqueid = (String) searchResult.next();
user = userFactory.getUser(uniqueid);
list.add(user.getUniqueName());
This code is giving me all user from the server LDAP and as well as portal user.
But i want only LDAP.
Please help me out. It's urgent.
Regards,
DeepakHi
use the following code
//Request
IWDRequest = WDProtocolAdapter.getProtocolAdapter().getRequestObject();
//User
IWDClientUser = WDClientUser.getCurrentUser();
Regards
Ayyapparaj -
Removing a object from an arraylist
hi,
i am putting an object into an arraylist like:
<code>
Hashtable userList = new Hashtable();
userList = this.loadUsers();
boolean found = false;
//look for the user in the list
for(int i = 0; i< userList.size(); i++)
User user = new User();
user = (User)userList.get(""+i);
if (user.userName.equalsIgnoreCase(userName) && user.password.equalsIgnoreCase(password))
try
found = true;
clientList.add(user);
System.out.println(userName);
catch (Exception e)
e.printStackTrace();
<\code>
and removing it like this:
<code>
Hashtable userList = new Hashtable();
userList = this.loadUsers();
boolean found = false;
//look for the user in the list
for(int i = 0; i< userList.size(); i++)
User user = new User();
user = (User)userList.get(""+i);
System.out.println(user);
if (user.userName.equalsIgnoreCase(userName))
try
found = true;
//add the logged in user to the Arraylist
int arraylist = clientList.size();
System.out.println(user);
System.out.println("client removed = "+clientList.remove(user));
System.out.println(userName);
catch (Exception e)
e.printStackTrace();
<\code>
however the object reference is not the same when i take it out so it wont remove... why?
Assignment.ChatImp$User@11121f6
Assignment.ChatImp$User@f7f540This code is brain dead.
Looks like your User class has public data members. True?
Why are you using a Hashtable when you appear to want a List?
You probably don't override equals and hashcode for your object.
Try this:
package user;
import java.io.Serializable;
import java.util.List;
import java.util.ArrayList;
* Created by IntelliJ IDEA.
* User: Michael
* Date: Dec 2, 2006
* Time: 9:59:11 AM
* To change this template use File | Settings | File Templates.
public class User implements Serializable
private String username;
private String password;
public static void main(String[] args)
if (args.length > 0)
List<User> users = new ArrayList<User>(args.length);
User userToRemove = new User(args[0], args[0]);
for (int i = 0; i < args.length; ++i)
User u = new User(args, args[i]);
users.add(u);
System.out.println("before: " + users);
System.out.println("users " + (users.contains(userToRemove) ? "" : "does not ") + "contain " + userToRemove);
users.remove(userToRemove);
System.out.println("after : " + users);
System.out.println("users " + (users.contains(userToRemove) ? "" : "does not ") + "contain " + userToRemove);
private User()
this("", "");
public User(String username, String password)
if ((username == null) || "".equals(username.trim()))
throw new IllegalArgumentException("username cannot be blank or null");
if ((password == null) || "".equals(password.trim()))
throw new IllegalArgumentException("password cannot be blank or null");
this.username = username;
this.password = password;
public String getUsername()
return username;
public String getPassword()
return password;
public boolean equals(Object o)
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
User user = (User) o;
if (password != null ? !password.equals(user.password) : user.password != null)
return false;
if (username != null ? !username.equals(user.username) : user.username != null)
return false;
return true;
public int hashCode()
int result;
result = (username != null ? username.hashCode() : 0);
result = 31 * result + (password != null ? password.hashCode() : 0);
return result;
public String toString()
return new StringBuilder().append("User{").append("username='").append(username).append('\'').append(", password='").append(password).append('\'').append('}').toString(); -
hi all...i hope somebody could show me some direction on my problem...i want to pass a arraylist `s cd information to an other arraylist
and save the new arraylist `s object to a file...i try to solve for a long ..pls help...
import java.text.*;
import java.util.*;
import java.io.*;
public class Demo{
readOperation theRo = new readOperation();
errorCheckingOperation theEco = new errorCheckingOperation();
ArrayList<MusicCd> MusicCdList;
private void heading()
System.out.println("\tTesting read data from console, save to file, reopen that file\t");
private void readDataFromConsole()
//private void insertCd()
MusicCdList = new ArrayList<MusicCd>( );
MusicCd theCd;
int muiseCdsYearOfRelease;
int validMuiseCdsYearOfRelease;
String muiseCdsTitle;
while(true)
String continueInsertCd = "Y";
do
muiseCdsTitle = theRo.readString("Please enter your CD`s title : ");
muiseCdsYearOfRelease = theRo.readInt("Please enter your CD`s year of release : ");
validMuiseCdsYearOfRelease = theEco.errorCheckingInteger(muiseCdsYearOfRelease, 1000, 9999);
MusicCdList.add(new MusicCd(muiseCdsTitle, validMuiseCdsYearOfRelease));//i try add the cd`s information to the arrayList
MusicCdList.trimToSize();
//saveToFile(MusicCdList);
continueInsertCd = theRo.readString("Do you have another Cd ? (Y/N) : ");
}while(continueInsertCd.equals("Y") || continueInsertCd.equals("y") );
if(continueInsertCd.equals("N") || continueInsertCd.equals("n"));
//MusicCdList.add(new MusicCd(muiseCdsTitle, muiseCdsYearOfRelease));
break;
//System.out.println("You `ve an invalid input " + continueInsertCd + " Please enter (Y/N) only!!");
//i want to pass those information that i just add to the arrayList to file
//I am going to pass the arraylist that contains my cd`s information to new arraylist "saveitems and save it to a file...
//i stuck on this problem
//how do i pass all the arrayList `s object to another arraylist ..pls help
//it is better show me some example how to solve thx a lot
private void saveToFile(ArrayList<MusicCd> tempItems)
ArrayList<MusicCd> saveItems;
saveItems = new ArrayList<MusicCd>();
try
File f = new File("cdData.txt");
FileOutputStream fos = new FileOutputStream(f);
ObjectOutputStream oos = new ObjectOutputStream(fos);
saveItems.add(ArrayList<MusicCd> tempItems);
//items.add("Second item.");
//items.add("Third item.");
//items.add("Blah Blah.");
oos.writeObject(items);
oos.close();
catch (IOException ioe)
ioe.printStackTrace();
try
File g = new File("test.fil");
FileInputStream fis = new FileInputStream(g);
ObjectInputStream ois = new ObjectInputStream(fis);
ArrayList<String> stuff = (ArrayList<String>)ois.readObject();
for( String s : stuff ) System.out.println(s);
ois.close();
catch (Exception ioe)
ioe.printStackTrace();
public static void main(String[] args)
Demo one = new Demo();
one.readDataFromConsole();
//one.saveToFile();
//the followring code for better understang
import java.io.Serializable;
public class MusicCd implements Serializable
private String musicCdsTitle;
private int yearOfRelease;
public MusicCd()
musicCdsTitle = "";
yearOfRelease = 1000;
public MusicCd(String newMusicCdsTitle, int newYearOfRelease)
musicCdsTitle = newMusicCdsTitle;
yearOfRelease = newYearOfRelease;
public String getTitle()
return musicCdsTitle;
public int getYearOfRelease()
return yearOfRelease;
public void setTitle(String newMusicCdsTitle)
musicCdsTitle = newMusicCdsTitle;
public void setYearOfRelease(int newYearOfRelease)
yearOfRelease = newYearOfRelease;
public boolean equalsName(MusicCd otherCd)
if(otherCd == null)
return false;
else
return (musicCdsTitle.equals(otherCd.musicCdsTitle));
public String toString()
return("Music Cd`s Title: " + musicCdsTitle + "\t"
+ "Year of release: " + yearOfRelease + "\t");
public ArrayList<MusicCd> getMusicCd(ArrayList<MusicCd> tempList)
return new ArrayList<MusicCd>(ArrayList<MusicCd> tempList);
import java.util.Scanner;
import java.util.InputMismatchException;
import java.util.NoSuchElementException;
public class errorCheckingOperation
public int errorCheckingInteger(int checkThing, int lowerBound, int upperBound)
int aInt = checkThing;
try
while((checkThing < lowerBound ) || (checkThing > upperBound) )
throw new Exception("Invaild value....Please enter the value between " + lowerBound + " & " + upperBound );
catch (Exception e)
String message = e.getMessage();
System.out.println(message);
return aInt;
public int errorCheckingSelectionValue(String userInstruction)
int validSelectionValue = 0;
try
int selectionValue;
Scanner scan = new Scanner(System.in);
System.out.print(userInstruction);
selectionValue = scan.nextInt();
validSelectionValue = errorCheckingInteger(selectionValue , 1, 5);
catch (NoSuchElementException e)
//if no line was found
System.out.println("\nNoSuchElementException error occurred (no line was found) " + e);
catch (IllegalStateException e)
// if this scanner is closed
System.out.println("\nIllegalStateException error occurred (scanner is closed)" + e);
return validSelectionValue;
import java.util.*;
public class readOperation{
public String readString(String userInstruction)
String aString = null;
try
Scanner scan = new Scanner(System.in);
System.out.print(userInstruction);
aString = scan.nextLine();
catch (NoSuchElementException e)
//if no line was found
System.out.println("\nNoSuchElementException error occurred (no line was found) " + e);
catch (IllegalStateException e)
// if this scanner is closed
System.out.println("\nIllegalStateException error occurred (scanner is closed)" + e);
return aString;
public char readTheFirstChar(String userInstruction)
char aChar = ' ';
String strSelection = null;
try
//char charSelection;
Scanner scan = new Scanner(System.in);
System.out.print(userInstruction);
strSelection = scan.next();
aChar = strSelection.charAt(0);
catch (NoSuchElementException e)
//if no line was found
System.out.println("\nNoSuchElementException error occurred (no line was found) " + e);
catch (IllegalStateException e)
// if this scanner is closed
System.out.println("\nIllegalStateException error occurred (scanner is closed)" + e);
return aChar;
public int readInt(String userInstruction) {
int aInt = 0;
try {
Scanner scan = new Scanner(System.in);
System.out.print(userInstruction);
aInt = scan.nextInt();
} catch (InputMismatchException e) {
System.out.println("\nInputMismatchException error occurred (the next token does not match the Integer regular expression, or is out of range) " + e);
} catch (NoSuchElementException e) {
System.out.println("\nNoSuchElementException error occurred (input is exhausted)" + e);
} catch (IllegalStateException e) {
System.out.println("\nIllegalStateException error occurred (scanner is closed)" + e);
return aInt;
}sorry for my not-clear descprtion...thc for your help....i got a problem on store some data to a file ....u can see my from demo..
Step1: i try to prompt the user to enter his/her cd `s information
and i pass those cd `s information to an object "MuiscCd" ..and i am going to add this "MuiscCd" to the arrayList " MusicCdList ". i am fine here..
Step2: and i want to save the object that `s in my arrayList " MusicCdList " to a file....i got stuck here..<_> ..(confused).
Step3:
i will reopen the file and print it out..(here i am alright ) -
Get JSF objects in a Filter Class
Hi! I have a problem with my JSF application. As the most of the web applications I have a login at the begining and I place a Listener - Filter classes for catching the session timeout to returning the user to the login page. All this works OK. The problem it´s to validate that the user only has 1 session open at the time, when the user begin session I change a flag into it's database row, and when the user logout the flags change again to false (both actions (login and logout) was fired by the user clicking it's respective buttons), this works fine, but I want to change the data flag in the database row with the timeout Filter classes after pass 1 minute. My Filter class it's like this:
public void doFilter(ServletRequest request,ServletResponse response, FilterChain filterChain) throws IOException,ServletException {
if ((request instanceof HttpServletRequest) && (response instanceof HttpServletResponse)) {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
if (!StringUtils.contains(httpServletRequest.getRequestURI(), "welcomeJSF.jsp")) {
if((httpServletRequest.getRequestedSessionId() != null) && !httpServletRequest.isRequestedSessionIdValid()){
/* 1 */
FacesContext context = FacesContext.getCurrentInstance();
User user = (User) context.getExternalContext().getSessionMap().get("simpleUser");
UserDAO conn = new UserDAO();
List users = conn.findByNumber(new Long(user.getNumber()));
persistence.User userDB = (persistence.User) users.get(0);
userDB.setUse(false);
Transaction tx = conn.getSession().beginTransaction();
conn.save(userDB);
tx.commit();
conn.getSession().close();
/* 2 */
String timeoutUrl = httpServletRequest.getContextPath()+ "/faces/" + "welcomeJSF.jsp";
System.out.println("Session is not invalid. Redirecting to login page. ");
httpServletResponse.sendRedirect(timeoutUrl);
return;
filterChain.doFilter(request, response);
}When I comment from 1 to 2 works fine, but if I want to get the context.getExternalContext().getSessionMap().get("simpleUser") i get this error:
java.lang.NullPointerException
at validadores.SessionTimeoutFilter.doFilter(SessionTimeoutFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:230)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:261)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:581)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
at java.lang.Thread.run(Thread.java:619)This is because I'm working in a diferent conexts? How can I get Jsf objects from ServletRequest? or to pass getExternalContext().getSessionMap() to the filter class? Any ideas to change the database when the session timeouts if I'm using hibernate?
Thanks for your time and help!correction :
MyObjectProxy extends ObjectProxy{
override callProperty(
// your dyna logic
and expose new MyObjectProxy(dynaInstance) -
Help to get text objects in ABAP
Hi guys!
I've created my first report program and need some help to get text objects into the report. The program combines the tables KNA1, LIKP, LIPS, VBAK, VBAP and VBKD to create a deliverylist which we import as excel info a shipping service. The issue at hand is that our website allows customers to change the ship-to party's address when creating an order. The adress are not updated to KNA1, but are comitted as a text on the ship-to on the delivery itself.
The text I need in the report is RV50A-TXTWE.
Can you help me get going on how to add this from the delivery?
Thanks a lot!Your problem is that its a structure. Structures are filled in a program and no longer exist after the program is closed. They are temporary data. It will have been moved to tables somewhere most likely. The next step is to debug / trace through the code to find out what was done with it.
What program were you using that created the structure?
Neal -
How to get an object's references through JVM
Hi,
I am performing some runtime program analysis and would like to know at exactly what point an object becomes "unreachable".
For example, I have a Testing Program (TP) and a Program Under Test (PUT) containing a set of classes. For each object o created by the PUT, TP maintains an object reference to it. At some point later, if TP decides that the only reference to object o is from TP (i.e., o is pointed to by some object out of the scope of PUT), then object o is considered to be "dead" (although it is not real garbage from the GC's point of view).
Hence, I am wondering if it is possible for any given object, to retrieve all the references that are pointing to it. If I am able to do this, maybe I can know whether the reference from TP is the only reference to an object in PUT.
Thank you and have a nice weekend,
-- SunnyThis could be achieved with JVMTI. See http://java.sun.com/j2se/1.5.0/docs/guide/jvmti/jvmti.html#Heap
There is no ready made function for achieving what you want, but all the building blocks are there, since you can iterate over the heap and you can get information about all reference relationships.
Regards,
Daniel
Maybe you are looking for
-
Report Region incrementing ID number by 1 using Javascript
I have a report that pulls file names and id numbers from a table and displays them on the page. I have set the 'id' column, which is a number type field in the table, to be a link to a javascript url that uses that number to delete the file from the
-
New 9 Cell S10 Battery-Advcie For First Time Charge and After?
Did search on first time charge for laptop batteries. I just picked up a 9 cell laptop battery for my S10. What is the best way to keep the life of these battries long. Read discharge fully then charge for 12 hours. Read charge fully then discharge 3
-
I updated itunes last week and since then it wont open
After the last update iTunes wont open all i get is an error saying iTunes.exe - Entry Point Not Found The procedure entry point ADAdPolicyEngine_DidEnterStation could not be located in the dynamic link library iAdCore.dll. then after i click ok on
-
HowTo: Show Non SAP forms properly?
I have tried ... Public Sub New() frm.Show() frm.Visible = False End and then to show the form finally frm.Visible = True. <i>Is there a more proper way to show a visual studio form?</i> I can't just instance the form (dim frm as Form1) or
-
Hi, I am getting following error for no ranges with different registers. I ve maintained the no ranges in SNRO w.r.t my excise group. still the same error occers,, plz revert imm "Maintain number range object for object J_1IINTNUM, year 2007, excise