I have an ArrayList, Whom i convert to String like
ArrayList str = (ArrayList) retrieveList.get(1);
...
makeCookie("userCredentialsCookie", str.toString(), httpServletResponce);
....
private void makeCookie(String name, String value, HttpServletResponse response) {
Cookie cookie = new Cookie(name, value);
cookie.setPath("/");
response.addCookie(cookie);
} //end of makeCookie()
Now when i retrieve cookie value, i get String, but i again want to convert it into ArrayList like
private void addCookieValueToSession(HttpSession session, Cookie cookie, String attributeName) {
if (attributeName.equalsIgnoreCase("getusercredentials")) {
String value = cookie.getValue();
ArrayList userCredntialsList = (ArrayList)value; //Need String to ArrayList
session.setAttribute(attributeName, userCredntialsList);
return;
}
String value = cookie.getValue();
session.setAttribute(attributeName, value);
} //end of addCookieValueToSession
How can i again convert it to ArrayList?
Thank you.
someList.toString() is not a proper way of serializing your data and will get you into trouble.
Since you need to store it as a String in a cookie, use JSON or XML. google-gson might be a good lib for you:
ArrayList str = (ArrayList) retrieveList.get(1);
String content = new Gson().toJson(str);
makeCookie("userCredentialsCookie", content, httpServletResponce);
//...
ArrayList userCredntialsList = new Gson().fromJson(cookie.getValue(), ArrayList.class);
As long as it's an ArrayList of String objects you should be able to write a small method which can parse the single String to re-create the list. The toString of an ArrayList will look something like this:
"[foo, bar, baz]"
So if that String is in the variable value, you could do something like this:
String debracketed = value.replace("[", "").replace("]", ""); // now be "foo, bar, baz"
String trimmed = debracketed.replaceAll("\\s+", ""); // now is "foo,bar,baz"
ArrayList<String> list = new ArrayList<String>(Arrays.asList(trimmed.split(","))); // now have an ArrayList containing "foo", "bar" and "baz"
Note, this is untested code.
Also, if it is not the case that your original ArrayList is a list of Strings, and is instead say, an ArrayList<MyDomainObject>, this approach will not work. For that your should instead find how to serialise/deserialise your objects correctly - toString is generally not a valid approach for this. It would be worth updating the question if that is the case.
You can't directly cast a String to ArrayList instead you need to create an ArrayList object to hold String values.
You need to change part of your code below:
ArrayList userCredntialsList = (ArrayList)value; //Need String to ArrayList
session.setAttribute(attributeName, userCredntialsList);
to:
ArrayList<String> userCredentialsList = ( ArrayList<Strnig> ) session.getAttribute( attributeName );
if ( userCredentialsList == null ) {
userCredentialsList = new ArrayList<String>( 10 );
session.setAttribute(attributeName, userCredentialsList);
}
userCredentialsList.add( value );
Related
private void populateArrayOfObjects(Object[] params, Employee e){
params[0] = e.getName();
params[1] = e.getEmpId();
params[2] = e.getDesignation();
}
Is there any other way we can populate above array?
You can do it like this ;
params = Arrays.asList(e.getName(), e.getEmpId(),e.getDesignation()).toArray();
Create a list as Array.asList().And convert to array with toArray(). So you dont need to send to method. Just do with simple one line.
I'm pulling data from database into an arraylist. I want to manipulate the arraylist and get a substring of the results. How can I substring the values generated in carList below?
private ArrayList<Cars> carList;
carList = CarDAO.getCarsByEngine(engineType);
Assuming you have a attribute String name in car.
String searchStr = "your_str";
for(i=0; i<carList.size();i++){
carList[i].name;
if(searchStr.toLowerCase().contains(carList[i].name.toLowerCase())){
// do somethig with your object carList[i]
}
}
I want to create a json object from existing json object. For this i want to get all the keys in JSONObject to a String[] array. Is there any default method to get the keys into a String array.
I found there exists a static method here getNames() but it's not working.
I can go over each key using iterator and can construct a keys String array but i want any default method if exists.
To construct JSONObject from other JSONObject you can use constructor that accept JSONObject and array of keys names that should be copied. To do it:
Iterator keysToCopyIterator = firstJSONObject.keys();
List<String> keysList = new ArrayList<String>();
while(keysToCopyIterator.hasNext()) {
String key = (String) keysToCopyIterator.next();
keysList.add(key);
}
String[] kesyArray = keysList.toArray(new String[keysList.size()]);
JSONObject secondJSONObject = new JSONObject(firstJSONObject, );
There is not getNames(), but there is Names()
I converted the ArrayList<String> list which contains "String1", "String2" to String by using list.toString(). The resulted string format is [String1, String2]. Is there any way to convert this result back to ArrayList<String>?
Try applying the following code
String value = "[String1,String2,String3]";
value = value.subString(1,value.length()-1);
String[] split = value.split(",");
List<String> sampleList = Arrays.asList(split);
create a new Class extending Array List
public class CustomArrayList<Item> extends ArrayList<Item> {
and override
toString
method, which could give a comma separated String representation.
Now use
new CustomArrayList<Item>(Arrays.asList(list.toString().split(",")))
to get it back in ArrayList.
No direct way. Just get that String remove those [] from String and then split by , then add back to list.
Something like this,considering the given format.
String s = "[String1, String2]";
s = s.substring(1, s.length() - 1);
List<String> list = new ArrayList<>();
for (String string : s.split(",")) {
list.add(string.trim());
}
How can I fix this:
class Name {
public void createArray(String name)
{
String name=new String[200];//we know, we can't do this- duplicate local variable,need a fix here.
}
}
I want to create array of strings with name of array as input parameter = name,
Example:
1) for function call createArray(domain1) -> I need essentially this to happen-> String domain1=new String[200];
2)for function call createArray(domain22)-> I need function to create String domain22=new String[200];
Hope this edit helps.
NOTE: There is a possibility that same name is passed byfunction twice/thrice. like createArray(domain1);, at that point of time I want to ignore the creation of array.
Store your new String[200] objects in a Map keyed by the name
Map<String, String[]> myarrays = new HashMap<String, String[]>();
myarrays.put("name", createArray("name"));
myarrays.put("test", createAray("test"));
then when you want one of them do
String[] data = myarrays.get("test");